PHP Manual

PHP Manual

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


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.

There are two primary decisions to be made configuring APC. First, how much memory is going to be allocated to APC; and second, whether APC will check if a file has been modified on every request. The two ini directives that control these settings are apc.shm_size and apc.stat, respectively. Read the sections on these two directive carefully below.

Once the server is running, the apc.php script that is bundled with the extension should be copied somewhere into the docroot and viewed with a browser as it provides a detailed analysis of the internal workings of APC. If GD is enabled in PHP, it will even display some interesting graphs. The first thing to ensure, of course, is that it is actually caching files. If APC is working, the Cache full count number (on the left) will display the number of times the cache has reached maximum capacity and has had to forcefully clean any entries that haven't been accessed in the last apc.ttl seconds. This number is minimized in a well-configured cache. If the cache is constantly being filled, and thusly forcefully freed, the resulting churning will have disparaging effects on script performance. The easiest way to minimize this number is to allocate more memory for APC. Barring that, the apc.filters ought to be used to cache fewer scripts.

APC configuration options
Name | Default | Changeable | Changelog
apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in APC 2. PHP_INI_ALL in APC <= 3.0.12.
apc.shm_segments | "1" | PHP_INI_SYSTEM |
apc.shm_size | "30" | PHP_INI_SYSTEM |
apc.optimization | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in APC 2. Removed in APC 3.0.13.
apc.num_files_hint | "1000" | PHP_INI_SYSTEM |
apc.user_entries_hint | "4096" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.user_ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12. Available since APC 3.0.0.
apc.filters | NULL | PHP_INI_SYSTEM |
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.slam_defense | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.file_update_protection | "2" | PHP_INI_SYSTEM | Available since APC 3.0.6.
apc.enable_cli | "0" | PHP_INI_SYSTEM | Available since APC 3.0.7.
apc.max_file_size | "1M" | PHP_INI_SYSTEM | Available since APC 3.0.7.
apc.stat | "1" | PHP_INI_SYSTEM | Available since APC 3.0.10.
apc.write_lock | "1" | PHP_INI_SYSTEM | Available since APC 3.0.11.
apc.report_autofilter | "0" | PHP_INI_SYSTEM | Available since APC 3.0.11.
apc.include_once_override | "0" | PHP_INI_SYSTEM | Available since APC 3.0.12.
apc.rfc1867 | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13.
apc.rfc1867_prefix | "upload_" | PHP_INI_SYSTEM |
apc.rfc1867_name | "APC_UPLOAD_PROGRESS" | PHP_INI_SYSTEM |
apc.rfc1867_freq | "0" | PHP_INI_SYSTEM |
apc.localcache | "0" | PHP_INI_SYSTEM | Available since APC 3.0.14.
apc.localcache.size | "512" | PHP_INI_SYSTEM | Available since APC 3.0.14.
apc.coredump_unmap | "0" | PHP_INI_SYSTEM | Available since APC 3.0.16.
apc.stat_ctime | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

apc.enabled boolean

apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).

apc.shm_segments integer

The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but apc.shm_size is set as high as the system allows, raising this value might prevent APC from exhausting its memory.

apc.shm_size integer

The size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.

apc.optimization integer

The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.

apc.num_files_hint integer

A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if unsure; this setting is mainly useful for sites that have many thousands of source files.

apc.user_entries_hint integer

Just like apc.num_files_hint, a "hint" about the number of distinct user cache variables to store. Set to zero or omit if not sure.

apc.ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.

apc.user_ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.

apc.gc_ttl integer

The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a fail-safe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.

apc.cache_by_default boolean

On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.

apc.filters string

A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.

apc.mmap_file_mask string

If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determining whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.

apc.slam_defense integer

On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.

Deprecated by apc.write_lock.

apc.file_update_protection integer

When a file is modified on a live web server it really ought to be done in an atomic manner. That is, written to a temporary file and renamed (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds, which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If all of the webserver's files are atomically updated, via some method like rsync (which updates correctly), this protection can be disabled by setting this directive to 0. If the system is flooded with i/o and some update procedures are taking longer than 2 seconds, this setting should be increased to enable the protection on those slower update operations.

apc.enable_cli integer

Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Under normal circumstances, it is not ideal to create, populate and destroy the APC cache on every CLI request, but for various test scenarios it is useful to be able to enable APC for the CLI version of PHP easily.

apc.max_file_size integer

Prevent files larger than this value from getting cached. Defaults to 1M.

apc.stat integer

Be careful changing this setting. This defaults to on, forcing APC to stat (check) the script on each request to determine if it has been modified. If it has been modified it will recompile and cache the new version. If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared. Note that FastCGI web server configurations may not clear the cache on restart. On a production server where the script files rarely change, a significant performance boost can be achieved by disabled stats.

For included/required files this option applies as well, but note that for relative path includes (any path that doesn't start with / on Unix) APC has to check in order to uniquely identify the file. If you use absolute path includes APC can skip the stat and use that absolute path as the unique identifier for the file.

apc.write_lock boolean

On busy servers, when the web server is first started, or when many files have been modified at the same time, APC may try to compile and cache the same file multiple times. Write_lock guarantees that only one process will attempt to compile and cache an uncached script. The other processes attempting to use the script will run without using the opcode cache, rather than locking and waiting for the cache to prime.

apc.report_autofilter boolean

Logs any scripts that were automatically excluded from being cached due to early/late binding issues.

apc.include_once_override boolean

Optimize include_once() and require_once() calls and avoid the expensive system calls used.

apc.rfc1867 boolean

RFC1867 File Upload Progress hook handler is only available if APC was compiled against PHP 5.2.0 or later. When enabled, any file uploads which includes a field called APC_UPLOAD_PROGRESS before the file field in an upload form will cause APC to automatically create an upload_key user cache entry where key is the value of the APC_UPLOAD_PROGRESS form entry.

Note that the hidden field specified by APC_UPLOAD_PROGRESS must come before the file field, otherwise the upload progress will not work correctly.

Note that the file upload tracking is not threadsafe at this point, so new uploads that happen while a previous one is still going will disable the tracking for the previous.

Example #1 An apc.rfc1867 example

<?php
print_r(apc_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>

The above example will output something similar to:

Array
(
    [total] => 1142543
    [current] => 1142543
    [rate] => 1828068.8
    [filename] => test
    [name] => file
    [temp_filename] => /tmp/php8F
    [cancel_upload] => 0
    [done] => 1
)

apc.rfc1867_prefix string

Key prefix to use for the user cache entry generated by rfc1867 upload progress functionality.

apc.rfc1867_name string

Specify the hidden form entry name that activates APC upload progress and specifies the user cache key suffix.

apc.rfc1867_freq string

The frequency that updates should be made to the user cache entry for upload progress. This can take the form of a percentage of the total file size or a size in bytes optionally suffixed with "k", "m", or "g" for kilobytes, megabytes, or gigabytes respectively (case insensitive). A setting of 0 updates as often as possible, which may cause slower uploads.

apc.localcache boolean

This enables a lock-free local process shadow-cache which reduces lock contention when the cache is being written to.

apc.localcache.size integer

The size of the local process shadow-cache, should be set to a sufficiently large value, approximately half of apc.num_files_hint.

apc.coredump_unmap boolean

Enables APC handling of signals, such as SIGSEGV, that write core files when signaled. When these signals are received, APC will attempt to unmap the shared memory segment in order to exclude it from the core file. This setting may improve system stability when fatal signals are received and a large APC shared memory segment is configured.

Warning

This feature is potentially dangerous. Unmapping the shared memory segment in a fatal signal handler may cause undefined behaviour if a fatal error occurs.

Note: Although some kernels may provide a facility to ignore various types of shared memory when generating a core dump file, these implementations may also ignore important shared memory segments such as the Apache scoreboard.

apc.stat_ctime integer

Verification with ctime will avoid problems caused by programs such as svn or rsync by making sure inodes haven't changed since the last stat. APC will normally only check mtime.

Installation
Resource Types
Installing/Configuring
PHP Manual


Predefined Constants

This extension has no constants defined.

Resource Types
APC Functions
APC


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/apc.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Note: On Windows, APC needs a temp path to exist, and be writable by the web server. It checks TMP, TEMP, USERPROFILE environment variables in that order and finally tries the WINDOWS directory if none of those are set.

Note: For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .

Requirements
Runtime Configuration
Installing/Configuring


Requirements

No external libraries are needed to build this extension.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension has no resource types defined.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
APC


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

APD Configuration Options
Name | Default | Changeable | Changelog
apd.dumpdir | NULL | PHP_INI_ALL |
apd.statement_tracing | "0" | PHP_INI_ALL | Available since apd 0.9.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

apd.dumpdir string

Sets the directory in which APD writes profile dump files. You can specify an absolute path or a relative path.

You can specify a different directory as an argument to apd_set_pprof_trace().

apd.statement_tracing boolean

Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.

Building on Win32
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

APD constants
Constant | Value | Description
FUNCTION_TRACE (integer) | 1 |
ARGS_TRACE (integer) | 2 |
ASSIGNMENT_TRACE (integer) | 4 |
STATEMENT_TRACE (integer) | 8 |
MEMORY_TRACE (integer) | 16 |
TIMING_TRACE (integer) | 32 |
SUMMARY_TRACE (integer) | 64 |
ERROR_TRACE (integer) | 128 |
PROF_TRACE (integer) | 256 |
APD_VERSION (string) | example: 1.0.2-dev |
Resource Types
Examples
APD


Examples

Table of Contents

  • How to use PHP-APD in your scripts
Predefined Constants
How to use PHP-APD in your scripts
APD


How to use PHP-APD in your scripts

  1. As the first line of your PHP script, call the apd_set_pprof_trace() function to start the trace:

    apd_set_pprof_trace();

    You can insert the line anywhere in your script, but if you do not start tracing at the beginning of your script you discard profile data that might otherwise lead you to a performance bottleneck.

  2. Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.

    Tip

    If you're running the CGI version of PHP, you will need to add the '-e' flag to enable extended information for apd to work properly. For example: php -e -f script.php

  3. To display formatted profile data, issue the pprofp command with the sort and display options of your choice. The formatted output will look something like:

    bash-2.05b$ pprofp -R /tmp/pprof.22141.0

Trace for /home/dan/testapd.php
Total Elapsed Time = 0.00
Total System Time  = 0.00
Total User Time    = 0.00

Real         User        System             secs/    cumm
%Time (excl/cumm)  (excl/cumm)  (excl/cumm) Calls    call    s/call  Memory Usage Name
--------------------------------------------------------------------------------------
100.0 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0000   0.0009            0 main
56.9 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0005   0.0005            0 apd_set_pprof_trace
28.0 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 preg_replace
14.3 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 str_replace

    The -R option used in this example sorts the profile table by the amount of real time the script spent executing a given function. The "cumm call" column reveals how many times each function was called, and the "s/call" column reveals how many seconds each call to the function required, on average.

  4. To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.

Examples
APD Functions
Examples


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/apd.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

In your INI file, add the following lines:

zend_extension = /absolute/path/to/apd.so
apd.dumpdir = /absolute/path/to/trace/directory
apd.statement_tracing = 0

Depending on your PHP build, the zend_extension directive can be one of the following:

zend_extension              (non ZTS, non debug build)
zend_extension_ts           (    ZTS, non debug build)
zend_extension_debug        (non ZTS,     debug build)
zend_extension_debug_ts     (    ZTS,     debug build)

Requirements
Building on Win32
Installing/Configuring


Building on Win32

To build APD under Windows you need a working PHP compilation environment as described on http://php.net/ -- basically, it requires you to have Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get it to work. Also ensure that adp.dsp has DOS line endings; if it has unix line endings, Microsoft Visual C++ will complain about it.

Installation
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Building on Win32
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
APD


Whether a offset exists

ArrayAccess
ArrayAccess::offsetGet
ArrayAccess
PHP Manual

ArrayAccess::offsetExists

(PHP 5 >= 5.1.0)

ArrayAccess::offsetExists — Whether a offset exists

Description

abstract public boolean ArrayAccess::offsetExists ( mixed $offset )

Whether or not an offset exists.

This method is executed when using isset() or empty() on objects implementing ArrayAccess.

Note: When using empty() ArrayAccess::offsetGet() will be called and checked if empty only if ArrayAccess::offsetExists() returns TRUE.

Parameters

offset

An offset to check for.

Return Values

Returns TRUE on success or FALSE on failure.

Note: The return value will be casted to boolean if non-boolean was returned.

Examples

Example #1 ArrayAccess::offsetExists() example

<?php
class obj implements arrayaccess {
    public function offsetSet($offset, $value) {
        var_dump(__METHOD__);
    }
    public function offsetExists($var) {
        var_dump(__METHOD__);
        if ($var == "foobar") {
            return true;
        }
        return false;
    }
    public function offsetUnset($var) {
        var_dump(__METHOD__);
    }
    public function offsetGet($var) {
        var_dump(__METHOD__);
        return "value";
    }
}

$obj = new obj;

echo "Runs obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));

echo "\nRuns obj::offsetExists() and obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));

echo "\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";
var_dump(empty($obj["foobaz"]));
?>

The above example will output something similar to:

Runs obj::offsetExists()
string(17) "obj::offsetExists"
bool(true)

Runs obj::offsetExists() and obj::offsetGet()
string(17) "obj::offsetExists"
string(14) "obj::offsetGet"
bool(false)

Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get
string(17) "obj::offsetExists"
bool(true)

ArrayAccess
ArrayAccess::offsetGet
ArrayAccess


Offset to retrieve

ArrayAccess::offsetExists
ArrayAccess::offsetSet
ArrayAccess
PHP Manual

ArrayAccess::offsetGet

(PHP 5 >= 5.1.0)

ArrayAccess::offsetGet — Offset to retrieve

Description

abstract public mixed ArrayAccess::offsetGet ( mixed $offset )

Returns the value at specified offset.

This method is executed when checking if offset is empty().

Parameters

offset

The offset to retrieve.

Return Values

Can return all value types.

See Also

  • ArrayAccess::offsetExists - Whether a offset exists

ArrayAccess::offsetExists
ArrayAccess::offsetSet
ArrayAccess


Offset to set

ArrayAccess::offsetGet
ArrayAccess::offsetUnset
ArrayAccess
PHP Manual

ArrayAccess::offsetSet

(PHP 5 >= 5.1.0)

ArrayAccess::offsetSet — Offset to set

Description

abstract public void ArrayAccess::offsetSet ( mixed $offset , mixed $value )

Assigns a value to the specified offset.

Parameters

offset

The offset to assign the value to.

value

The value to set.

Return Values

No value is returned.

Notes

Note: The offset parameter will be set to NULL if another value is not available, like in the following example.

<?php
$arrayaccess[] = "value";
?>

ArrayAccess::offsetGet
ArrayAccess::offsetUnset
ArrayAccess


Offset to unset

ArrayAccess::offsetSet
Serializable
ArrayAccess
PHP Manual

ArrayAccess::offsetUnset

(PHP 5 >= 5.1.0)

ArrayAccess::offsetUnset — Offset to unset

Description

abstract public void ArrayAccess::offsetUnset ( mixed $offset )

Unsets an offset.

Note: This method will not be called when type-casting to (unset)

Parameters

offset

The offset to unset.

Return Values

No value is returned.

ArrayAccess::offsetSet
Serializable
ArrayAccess


Returns the bitrate of the MPEG file

KTaglib_MPEG_AudioProperties
KTaglib_MPEG_AudioProperties::getChannels
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getBitrate ( void )

Returns the bitrate of the MPEG file

Return Values

Returns the bitrate as an integer

KTaglib_MPEG_AudioProperties
KTaglib_MPEG_AudioProperties::getChannels
KTaglib_MPEG_AudioProperties


Returns the amount of channels of a MPEG file

KTaglib_MPEG_AudioProperties::getBitrate
KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getChannels

(0.0.1)

KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getChannels ( void )

Returns the amount of channels of the MPEG file

Return Values

Returns the channel count as an integer

KTaglib_MPEG_AudioProperties::getBitrate
KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties


Returns the layer of a MPEG file

KTaglib_MPEG_AudioProperties::getChannels
KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getLayer

(0.0.1)

KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getLayer ( void )

Returns the layer of the MPEG file (usually 3 for MP3).

Return Values

Returns the layer as an integer

KTaglib_MPEG_AudioProperties::getChannels
KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getLength

(0.0.1)

KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getLength ( void )

Returns the length of the MPEG file

Return Values

Returns the length as an integer

KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties


Returns the sample bitrate of a MPEG file

KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getSampleBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getSampleBitrate ( void )

Returns the sample bitrate of the MPEG file

Return Values

Returns the sample bitrate as an integer

KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties


Returns the version of a MPEG file

KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getVersion

(0.0.1)

KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file

Description

public int KTaglib_MPEG_AudioProperties::getVersion ( void )

Returns the version of the MPEG file header. The possible versions are defined in Tag_MPEG_Header (Version1, Version2, Version2.5).

Return Values

Returns the version

KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::isCopyrighted

(0.0.1)

KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the length of a MPEG file

Description

public bool KTaglib_MPEG_AudioProperties::isCopyrighted ( void )

Returns true if the MPEG file is copyrighted

Return Values

Returns true if the MPEG file is copyrighted

KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties::isProtectionEnabled
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::isOriginal

(0.0.1)

KTaglib_MPEG_AudioProperties::isOriginal — Returns the length of a MPEG file

Description

public bool KTaglib_MPEG_AudioProperties::isOriginal ( void )

Returns true if the file is marked as the original file

Return Values

Returns true if the file is marked as the original file

KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties::isProtectionEnabled
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_Tag
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::isProtectionEnabled

(0.0.1)

KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns the length of a MPEG file

Description

public bool KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void )

Returns true if protection mechanism (like DRM) are enabled for this file

Return Values

Returns true if protection mechanism (like DRM) are enabled for this file

KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_Tag
KTaglib_MPEG_AudioProperties


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

BC math configuration options
Name | Default | Changeable | Changelog
bcmath.scale | "0" | PHP_INI_ALL |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

bcmath.scale integer

Number of decimal digits for all bcmath functions. See also bcscale().

Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

Resource Types
BC Math Functions
BC Math


Installation

These functions are only available if PHP was configured with --enable-bcmath.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

Since PHP 4.0.4, libbcmath is bundled with PHP. You don't need any external libraries for this extension.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
BC Math


Runtime Configuration

This extension has no configuration directives defined in php.ini.

Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

Resource Types
bcompiler Functions
bcompiler


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/bcompiler.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
bcompiler


Alternative PHP Cache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • APC Functions
    • apc_add — Cache a variable in the data store
    • apc_cache_info — Retrieves cached information from APC's data store
    • apc_clear_cache — Clears the APC cache
    • apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.
    • apc_define_constants — Defines a set of constants for retrieval and mass-definition
    • apc_delete — Removes a stored variable from the cache
    • apc_fetch — Fetch a stored variable from the cache
    • apc_load_constants — Loads a set of constants from the cache
    • apc_sma_info — Retrieves APC's Shared Memory Allocation information
    • apc_store — Cache a variable in the data store
Affecting PHP's Behaviour
Introduction
Affecting PHP's Behaviour


Advanced PHP debugger

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Building on Win32
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • How to use PHP-APD in your scripts
  • APD Functions
    • apd_breakpoint — Stops the interpreter and waits on a CR from the socket
    • apd_callstack — Returns the current call stack as an array
    • apd_clunk — Throw a warning and a callstack
    • apd_continue — Restarts the interpreter
    • apd_croak — Throw an error, a callstack and then exit
    • apd_dump_function_table — Outputs the current function table
    • apd_dump_persistent_resources — Return all persistent resources as an array
    • apd_dump_regular_resources — Return all current regular resources as an array
    • apd_echo — Echo to the debugging socket
    • apd_get_active_symbols — Get an array of the current variables names in the local scope
    • apd_set_pprof_trace — Starts the session debugging
    • apd_set_session_trace_socket — Starts the remote session debugging
    • apd_set_session_trace — Starts the session debugging
    • apd_set_session — Changes or sets the current debugging level
    • override_function — Overrides built-in functions
    • rename_function — Renames orig_name to new_name in the global function table
apc_store
Introduction
Affecting PHP's Behaviour


BCMath Arbitrary Precision Mathematics

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • BC Math Functions
    • bcadd — Add two arbitrary precision numbers
    • bccomp — Compare two arbitrary precision numbers
    • bcdiv — Divide two arbitrary precision numbers
    • bcmod — Get modulus of an arbitrary precision number
    • bcmul — Multiply two arbitrary precision number
    • bcpow — Raise an arbitrary precision number to another
    • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
    • bcscale — Set default scale parameter for all bc math functions
    • bcsqrt — Get the square root of an arbitrary precision number
    • bcsub — Subtract one arbitrary precision number from another
Mathematical Extensions
Introduction
Mathematical Extensions


PHP bytecode Compiler

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • bcompiler Functions
    • bcompiler_load_exe — Reads and creates classes from a bcompiler exe file
    • bcompiler_load — Reads and creates classes from a bz compressed file
    • bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function
    • bcompiler_read — Reads and creates classes from a filehandle
    • bcompiler_write_class — Writes an defined class as bytecodes
    • bcompiler_write_constant — Writes a defined constant as bytecodes
    • bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file
    • bcompiler_write_file — Writes a php source file as bytecodes
    • bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data
    • bcompiler_write_function — Writes an defined function as bytecodes
    • bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
    • bcompiler_write_header — Writes the bcompiler header
    • bcompiler_write_included_filename — Writes an included file as bytecodes
rename_function
Introduction
Affecting PHP's Behaviour


Bzip2

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Bzip2 Functions
    • bzclose — Close a bzip2 file
    • bzcompress — Compress a string into bzip2 encoded data
    • bzdecompress — Decompresses bzip2 encoded data
    • bzerrno — Returns a bzip2 error number
    • bzerror — Returns the bzip2 error number and error string in an array
    • bzerrstr — Returns a bzip2 error string
    • bzflush — Force a write of all buffered data
    • bzopen — Opens a bzip2 compressed file
    • bzread — Binary safe bzip2 file read
    • bzwrite — Binary safe bzip2 file write
Compression and Archive Extensions
Introduction
Compression and Archive Extensions


Cairo

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Cairo Functions
    • cairo_create — Description
    • cairo_font_face_get_type — Description
    • cairo_font_face_status — Description
    • cairo_font_options_create — Description
    • cairo_font_options_equal — Description
    • cairo_font_options_get_antialias — Description
    • cairo_font_options_get_hint_metrics — Description
    • cairo_font_options_get_hint_style — Description
    • cairo_font_options_get_subpixel_order — Description
    • cairo_font_options_hash — Description
    • cairo_font_options_merge — Description
    • cairo_font_options_set_antialias — Description
    • cairo_font_options_set_hint_metrics — Description
    • cairo_font_options_set_hint_style — Description
    • cairo_font_options_set_subpixel_order — Description
    • cairo_font_options_status — Description
    • cairo_format_stride_for_width — Description
    • cairo_image_surface_create_for_data — Description
    • cairo_image_surface_create_from_png — Description
    • cairo_image_surface_create — Description
    • cairo_image_surface_get_data — Description
    • cairo_image_surface_get_format — Description
    • cairo_image_surface_get_height — Description
    • cairo_image_surface_get_stride — Description
    • cairo_image_surface_get_width — Description
    • cairo_matrix_create_scale — Alias of CairoMatrix::initScale
    • cairo_matrix_create_translate — Alias of CairoMatrix::initTranslate
    • cairo_matrix_invert — Description
    • cairo_matrix_multiply — Description
    • cairo_matrix_rotate — Description
    • cairo_matrix_transform_distance — Description
    • cairo_matrix_transform_point — Description
    • cairo_matrix_translate — Description
    • cairo_pattern_add_color_stop_rgb — Description
    • cairo_pattern_add_color_stop_rgba — Description
    • cairo_pattern_create_for_surface — Description
    • cairo_pattern_create_linear — Description
    • cairo_pattern_create_radial — Description
    • cairo_pattern_create_rgb — Description
    • cairo_pattern_create_rgba — Description
    • cairo_pattern_get_color_stop_count — Description
    • cairo_pattern_get_color_stop_rgba — Description
    • cairo_pattern_get_extend — Description
    • cairo_pattern_get_filter — Description
    • cairo_pattern_get_linear_points — Description
    • cairo_pattern_get_matrix — Description
    • cairo_pattern_get_radial_circles — Description
    • cairo_pattern_get_rgba — Description
    • cairo_pattern_get_surface — Description
    • cairo_pattern_get_type — Description
    • cairo_pattern_set_extend — Description
    • cairo_pattern_set_filter — Description
    • cairo_pattern_set_matrix — Description
    • cairo_pattern_status — Description
    • cairo_pdf_surface_create — Description
    • cairo_pdf_surface_set_size — Description
    • cairo_ps_get_levels — Description
    • cairo_ps_level_to_string — Description
    • cairo_ps_surface_create — Description
    • cairo_ps_surface_dsc_begin_page_setup — Description
    • cairo_ps_surface_dsc_begin_setup — Description
    • cairo_ps_surface_dsc_comment — Description
    • cairo_ps_surface_get_eps — Description
    • cairo_ps_surface_restrict_to_level — Description
    • cairo_ps_surface_set_eps — Description
    • cairo_ps_surface_set_size — Description
    • cairo_scaled_font_create — Description
    • cairo_scaled_font_extents — Description
    • cairo_scaled_font_get_ctm — Description
    • cairo_scaled_font_get_font_face — Description
    • cairo_scaled_font_get_font_matrix — Description
    • cairo_scaled_font_get_font_options — Description
    • cairo_scaled_font_get_scale_matrix — Description
    • cairo_scaled_font_get_type — Description
    • cairo_scaled_font_glyph_extents — Description
    • cairo_scaled_font_status — Description
    • cairo_scaled_font_text_extents — Description
    • cairo_surface_copy_page — Description
    • cairo_surface_create_similar — Description
    • cairo_surface_finish — Description
    • cairo_surface_flush — Description
    • cairo_surface_get_content — Description
    • cairo_surface_get_device_offset — Description
    • cairo_surface_get_font_options — Description
    • cairo_surface_get_type — Description
    • cairo_surface_mark_dirty_rectangle — Description
    • cairo_surface_mark_dirty — Description
    • cairo_surface_set_device_offset — Description
    • cairo_surface_set_fallback_resolution — Description
    • cairo_surface_show_page — Description
    • cairo_surface_status — Description
    • cairo_surface_write_to_png — Description
    • cairo_svg_surface_create — Description
    • cairo_svg_surface_restrict_to_version — Description
    • cairo_svg_version_to_string — Description
  • Cairo — The Cairo class
    • Cairo::availableFonts — Retrieves the availables font types
    • Cairo::availableSurfaces — Retrieves all available surfaces
    • Cairo::statusToString — Retrieves the current status as string
    • Cairo::version — Retrives cairo's library version
    • Cairo::versionString — Retrieves cairo version as string
  • CairoContext — The CairoContext class
    • CairoContext::appendPath — Appends a path to current path
    • CairoContext::arc — Adds a circular arc
    • CairoContext::arcNegative — Adds a negative arc
    • CairoContext::clip — Establishes a new clip region
    • CairoContext::clipExtents — Computes the area inside the current clip
    • CairoContext::clipPreserve — Establishes a new clip region from the current clip
    • CairoContext::clipRectangleList — Retrieves the current clip as a list of rectangles
    • CairoContext::closePath — Closes the current path
    • CairoContext::__construct — Creates a new CairoContext
    • CairoContext::copyPage — Emits the current page
    • CairoContext::copyPath — Creates a copy of the current path
    • CairoContext::copyPathFlat — Gets a flattened copy of the current path
    • CairoContext::curveTo — Adds a curve
    • CairoContext::deviceToUser — Transform a coordinate
    • CairoContext::deviceToUserDistance — Transform a distance
    • CairoContext::fill — Fills the current path
    • CairoContext::fillExtents — Computes the filled area
    • CairoContext::fillPreserve — Fills and preserve the current path
    • CairoContext::fontExtents — Get the font extents
    • CairoContext::getAntialias — Retrives the current antialias mode
    • CairoContext::getCurrentPoint — The getCurrentPoint purpose
    • CairoContext::getDash — The getDash purpose
    • CairoContext::getDashCount — The getDashCount purpose
    • CairoContext::getFillRule — The getFillRule purpose
    • CairoContext::getFontFace — The getFontFace purpose
    • CairoContext::getFontMatrix — The getFontMatrix purpose
    • CairoContext::getFontOptions — The getFontOptions purpose
    • CairoContext::getGroupTarget — The getGroupTarget purpose
    • CairoContext::getLineCap — The getLineCap purpose
    • CairoContext::getLineJoin — The getLineJoin purpose
    • CairoContext::getLineWidth — The getLineWidth purpose
    • CairoContext::getMatrix — The getMatrix purpose
    • CairoContext::getMiterLimit — The getMiterLimit purpose
    • CairoContext::getOperator — The getOperator purpose
    • CairoContext::getScaledFont — The getScaledFont purpose
    • CairoContext::getSource — The getSource purpose
    • CairoContext::getTarget — The getTarget purpose
    • CairoContext::getTolerance — The getTolerance purpose
    • CairoContext::glyphPath — The glyphPath purpose
    • CairoContext::hasCurrentPoint — The hasCurrentPoint purpose
    • CairoContext::identityMatrix — The identityMatrix purpose
    • CairoContext::inFill — The inFill purpose
    • CairoContext::inStroke — The inStroke purpose
    • CairoContext::lineTo — The lineTo purpose
    • CairoContext::mask — The mask purpose
    • CairoContext::maskSurface — The maskSurface purpose
    • CairoContext::moveTo — The moveTo purpose
    • CairoContext::newPath — The newPath purpose
    • CairoContext::newSubPath — The newSubPath purpose
    • CairoContext::paint — The paint purpose
    • CairoContext::paintWithAlpha — The paintWithAlpha purpose
    • CairoContext::pathExtents — The pathExtents purpose
    • CairoContext::popGroup — The popGroup purpose
    • CairoContext::popGroupToSource — The popGroupToSource purpose
    • CairoContext::pushGroup — The pushGroup purpose
    • CairoContext::pushGroupWithContent — The pushGroupWithContent purpose
    • CairoContext::rectangle — The rectangle purpose
    • CairoContext::relCurveTo — The relCurveTo purpose
    • CairoContext::relLineTo — The relLineTo purpose
    • CairoContext::relMoveTo — The relMoveTo purpose
    • CairoContext::resetClip — The resetClip purpose
    • CairoContext::restore — The restore purpose
    • CairoContext::rotate — The rotate purpose
    • CairoContext::save — The save purpose
    • CairoContext::scale — The scale purpose
    • CairoContext::selectFontFace — The selectFontFace purpose
    • CairoContext::setAntialias — The setAntialias purpose
    • CairoContext::setDash — The setDash purpose
    • CairoContext::setFillRule — The setFillRule purpose
    • CairoContext::setFontFace — The setFontFace purpose
    • CairoContext::setFontMatrix — The setFontMatrix purpose
    • CairoContext::setFontOptions — The setFontOptions purpose
    • CairoContext::setFontSize — The setFontSize purpose
    • CairoContext::setLineCap — The setLineCap purpose
    • CairoContext::setLineJoin — The setLineJoin purpose
    • CairoContext::setLineWidth — The setLineWidth purpose
    • CairoContext::setMatrix — The setMatrix purpose
    • CairoContext::setMiterLimit — The setMiterLimit purpose
    • CairoContext::setOperator — The setOperator purpose
    • CairoContext::setScaledFont — The setScaledFont purpose
    • CairoContext::setSource — The setSource purpose
    • CairoContext::setSourceRGB — The setSourceRGB purpose
    • CairoContext::setSourceRGBA — The setSourceRGBA purpose
    • CairoContext::setSourceSurface — The setSourceSurface purpose
    • CairoContext::setTolerance — The setTolerance purpose
    • CairoContext::showPage — The showPage purpose
    • CairoContext::showText — The showText purpose
    • CairoContext::status — The status purpose
    • CairoContext::stroke — The stroke purpose
    • CairoContext::strokeExtents — The strokeExtents purpose
    • CairoContext::strokePreserve — The strokePreserve purpose
    • CairoContext::textExtents — The textExtents purpose
    • CairoContext::textPath — The textPath purpose
    • CairoContext::transform — The transform purpose
    • CairoContext::translate — The translate purpose
    • CairoContext::userToDevice — The userToDevice purpose
    • CairoContext::userToDeviceDistance — The userToDeviceDistance purpose
  • CairoException — The CairoException class
  • CairoStatus — The CairoStatus class
  • CairoSurface — The CairoSurface class
    • CairoSurface::__construct — The __construct purpose
    • CairoSurface::copyPage — The copyPage purpose
    • CairoSurface::createSimilar — The createSimilar purpose
    • CairoSurface::finish — The finish purpose
    • CairoSurface::flush — The flush purpose
    • CairoSurface::getContent — The getContent purpose
    • CairoSurface::getDeviceOffset — The getDeviceOffset purpose
    • CairoSurface::getFontOptions — The getFontOptions purpose
    • CairoSurface::getType — The getType purpose
    • CairoSurface::markDirty — The markDirty purpose
    • CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose
    • CairoSurface::setDeviceOffset — The setDeviceOffset purpose
    • CairoSurface::setFallbackResolution — The setFallbackResolution purpose
    • CairoSurface::showPage — The showPage purpose
    • CairoSurface::status — The status purpose
    • CairoSurface::writeToPng — The writeToPng purpose
  • CairoSvgSurface — Svg Surface Backend
    • CairoSvgSurface::__construct — The __construct purpose
    • CairoSvgSurface::getVersions — Used to retrieve a list of supported SVG versions
    • CairoSvgSurface::restrictToVersion — The restrictToVersion purpose
    • CairoSvgSurface::versionToString — The versionToString purpose
  • CairoImageSurface — The CairoImageSurface class
    • CairoImageSurface::__construct — Creates a new CairoImageSurface
    • CairoImageSurface::createForData — The createForData purpose
    • CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file
    • CairoImageSurface::getData — Gets the image data as string
    • CairoImageSurface::getFormat — Get the image format
    • CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface
    • CairoImageSurface::getStride — The getStride purpose
    • CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface
  • CairoPdfSurface — The CairoPdfSurface class
    • CairoPdfSurface::__construct — The __construct purpose
    • CairoPdfSurface::setSize — The setSize purpose
  • CairoPsSurface — The CairoPsSurface class
    • CairoPsSurface::__construct — The __construct purpose
    • CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose
    • CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose
    • CairoPsSurface::dscComment — The dscComment purpose
    • CairoPsSurface::getEps — The getEps purpose
    • CairoPsSurface::getLevels — The getLevels purpose
    • CairoPsSurface::levelToString — The levelToString purpose
    • CairoPsSurface::restrictToLevel — The restrictToLevel purpose
    • CairoPsSurface::setEps — The setEps purpose
    • CairoPsSurface::setSize — The setSize purpose
  • CairoSurfaceType — The CairoSurfaceType class
  • CairoFontFace — The CairoFontFace class
    • CairoFontFace::__construct — Creates a new CairoFontFace object
    • CairoFontFace::getType — Retrieves the font face type
    • CairoFontFace::status — Check for CairoFontFace errors
  • CairoFontOptions — The CairoFontOptions class
    • CairoFontOptions::__construct — The __construct purpose
    • CairoFontOptions::equal — The equal purpose
    • CairoFontOptions::getAntialias — The getAntialias purpose
    • CairoFontOptions::getHintMetrics — The getHintMetrics purpose
    • CairoFontOptions::getHintStyle — The getHintStyle purpose
    • CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose
    • CairoFontOptions::hash — The hash purpose
    • CairoFontOptions::merge — The merge purpose
    • CairoFontOptions::setAntialias — The setAntialias purpose
    • CairoFontOptions::setHintMetrics — The setHintMetrics purpose
    • CairoFontOptions::setHintStyle — The setHintStyle purpose
    • CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose
    • CairoFontOptions::status — The status purpose
  • CairoFontSlant — The CairoFontSlant class
  • CairoFontType — The CairoFontType class
  • CairoFontWeight — The CairoFontWeight class
  • CairoScaledFont — The CairoScaledFont class
    • CairoScaledFont::__construct — The __construct purpose
    • CairoScaledFont::extents — The extents purpose
    • CairoScaledFont::getCtm — The getCtm purpose
    • CairoScaledFont::getFontFace — The getFontFace purpose
    • CairoScaledFont::getFontMatrix — The getFontMatrix purpose
    • CairoScaledFont::getFontOptions — The getFontOptions purpose
    • CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose
    • CairoScaledFont::getType — The getType purpose
    • CairoScaledFont::glyphExtents — The glyphExtents purpose
    • CairoScaledFont::status — The status purpose
    • CairoScaledFont::textExtents — The textExtents purpose
  • CairoToyFontFace — The CairoToyFontFace class
  • CairoPatternType — The CairoPatternType class
  • CairoPattern — The CairoPattern class
    • CairoPattern::__construct — The __construct purpose
    • CairoPattern::getMatrix — The getMatrix purpose
    • CairoPattern::getType — The getType purpose
    • CairoPattern::setMatrix — The setMatrix purpose
    • CairoPattern::status — The status purpose
  • CairoGradientPattern — The CairoGradientPattern class
    • CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose
    • CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose
    • CairoGradientPattern::getColorStopCount — The getColorStopCount purpose
    • CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose
    • CairoGradientPattern::getExtend — The getExtend purpose
    • CairoGradientPattern::setExtend — The setExtend purpose
  • CairoSolidPattern — The CairoSolidPattern class
    • CairoSolidPattern::__construct — The __construct purpose
    • CairoSolidPattern::getRgba — The getRgba purpose
  • CairoSurfacePattern — The CairoSurfacePattern class
    • CairoSurfacePattern::__construct — The __construct purpose
    • CairoSurfacePattern::getExtend — The getExtend purpose
    • CairoSurfacePattern::getFilter — The getFilter purpose
    • CairoSurfacePattern::getSurface — The getSurface purpose
    • CairoSurfacePattern::setExtend — The setExtend purpose
    • CairoSurfacePattern::setFilter — The setFilter purpose
  • CairoLinearGradient — The CairoLinearGradient class
    • CairoLinearGradient::__construct — The __construct purpose
    • CairoLinearGradient::getPoints — The getPoints purpose
  • CairoRadialGradient — The CairoRadialGradient class
    • CairoRadialGradient::__construct — The __construct purpose
    • CairoRadialGradient::getCircles — The getCircles purpose
  • CairoAntialias — The CairoAntialias class
  • CairoContent — The CairoContent class
  • CairoExtend — The CairoExtend class
  • CairoFormat — The CairoFormat class
    • CairoFormat::strideForWidth — Provides an appropiate stride to use
  • CairoFillRule — The CairoFillRule class
  • CairoFilter — The CairoFilter class
  • CairoHintMetrics — The CairoHintMetrics class
  • CairoHintStyle — The CairoHintStyle class
  • CairoLineCap — The CairoLineCap class
  • CairoLineJoin — The CairoLineJoin class
  • CairoMatrix — The CairoMatrix class
    • CairoMatrix::__construct — Creates a new CairoMatrix object
    • CairoMatrix::initIdentity — Creates a new identity matrix
    • CairoMatrix::initRotate — Creates a new rotated matrix
    • CairoMatrix::initScale — Creates a new scaling matrix
    • CairoMatrix::initTranslate — Creates a new translation matrix
    • CairoMatrix::invert — The invert purpose
    • CairoMatrix::multiply — The multiply purpose
    • CairoMatrix::rotate — The rotate purpose
    • CairoMatrix::scale — Applies scaling to a matrix
    • CairoMatrix::transformDistance — The transformDistance purpose
    • CairoMatrix::transformPoint — The transformPoint purpose
    • CairoMatrix::translate — The translate purpose
  • CairoOperator — The CairoOperator class
  • CairoPath — The CairoPath class
  • CairoPsLevel — The CairoPsLevel class
  • CairoSubpixelOrder — The CairoSubpixelOrder class
  • CairoSvgVersion — The CairoSvgVersion class
GmagickPixel::setcolorvalue
Introduction
Image Processing and Generation


Calendar

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Calendar Functions
    • cal_days_in_month — Return the number of days in a month for a given year and calendar
    • cal_from_jd — Converts from Julian Day Count to a supported calendar
    • cal_info — Returns information about a particular calendar
    • cal_to_jd — Converts from a supported calendar to Julian Day Count
    • easter_date — Get Unix timestamp for midnight on Easter of a given year
    • easter_days — Get number of days after March 21 on which Easter falls for a given year
    • FrenchToJD — Converts a date from the French Republican Calendar to a Julian Day Count
    • GregorianToJD — Converts a Gregorian date to Julian Day Count
    • JDDayOfWeek — Returns the day of the week
    • JDMonthName — Returns a month name
    • JDToFrench — Converts a Julian Day Count to the French Republican Calendar
    • JDToGregorian — Converts Julian Day Count to Gregorian date
    • jdtojewish — Converts a Julian day count to a Jewish calendar date
    • JDToJulian — Converts a Julian Day Count to a Julian Calendar Date
    • jdtounix — Convert Julian Day to Unix timestamp
    • JewishToJD — Converts a date in the Jewish Calendar to Julian Day Count
    • JulianToJD — Converts a Julian Calendar date to Julian Day Count
    • unixtojd — Convert Unix timestamp to Julian Day
Date and Time Related Extensions
Introduction
Date and Time Related Extensions


Cracklib

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Crack Functions
    • crack_check — Performs an obscure check with the given password
    • crack_closedict — Closes an open CrackLib dictionary
    • crack_getlastmessage — Returns the message from the last obscure check
    • crack_opendict — Opens a new CrackLib dictionary
Cryptography Extensions
Introduction
Cryptography Extensions


Cyrus IMAP administration

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Cyrus Functions
    • cyrus_authenticate — Authenticate against a Cyrus IMAP server
    • cyrus_bind — Bind callbacks to a Cyrus IMAP connection
    • cyrus_close — Close connection to a Cyrus IMAP server
    • cyrus_connect — Connect to a Cyrus IMAP server
    • cyrus_query — Send a query to a Cyrus IMAP server
    • cyrus_unbind — Unbind ...
Mail Related Extensions
Introduction
Mail Related Extensions


Date and Time

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • List of Supported Timezones
    • Africa
    • America
    • Antarctica
    • Arctic
    • Asia
    • Atlantic
    • Australia
    • Europe
    • Indian
    • Pacific
    • Others
  • DateTime — The DateTime class
    • DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
    • DateTime::__construct — Returns new DateTime object
    • DateTime::createFromFormat — Returns new DateTime object formatted according to the specified format
    • DateTime::diff — Returns the difference between two DateTime objects
    • DateTime::format — Returns date formatted according to given format
    • DateTime::getLastErrors — Returns the warnings and errors
    • DateTime::getOffset — Returns the timezone offset
    • DateTime::getTimestamp — Gets the Unix timestamp
    • DateTime::getTimezone — Return time zone relative to given DateTime
    • DateTime::modify — Alters the timestamp
    • DateTime::__set_state — The __set_state handler
    • DateTime::setDate — Sets the date
    • DateTime::setISODate — Sets the ISO date
    • DateTime::setTime — Sets the time
    • DateTime::setTimestamp — Sets the date and time based on an Unix timestamp
    • DateTime::setTimezone — Sets the time zone for the DateTime object
    • DateTime::sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
    • DateTime::__wakeup — The __wakeup handler
  • DateTimeZone — The DateTimeZone class
    • DateTimeZone::__construct — Creates new DateTimeZone object
    • DateTimeZone::getLocation — Returns location information for a timezone
    • DateTimeZone::getName — Returns the name of the timezone
    • DateTimeZone::getOffset — Returns the timezone offset from GMT
    • DateTimeZone::getTransitions — Returns all transitions for the timezone
    • DateTimeZone::listAbbreviations — Returns associative array containing dst, offset and the timezone name
    • DateTimeZone::listIdentifiers — Returns numerically index array with all timezone identifiers
  • DateInterval — The DateInterval class
    • DateInterval::__construct — Creates new DateInterval object
    • DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
    • DateInterval::format — Formats the interval
  • DatePeriod — The DatePeriod class
    • DatePeriod::__construct — Creates new DatePeriod object
  • Date/Time Functions
    • checkdate — Validate a Gregorian date
    • date_add — Alias of DateTime::add
    • date_create_from_format — Alias of DateTime::createFromFormat
    • date_create — Returns new DateTime object
    • date_date_set — Alias of DateTime::setDate
    • date_default_timezone_get — Gets the default timezone used by all date/time functions in a script
    • date_default_timezone_set — Sets the default timezone used by all date/time functions in a script
    • date_diff — Alias of DateTime::diff
    • date_format — Alias of DateTime::format
    • date_get_last_errors — Alias of DateTime::getLastErrors
    • date_interval_create_from_date_string — Alias of DateInterval::createFromDateString
    • date_interval_format — Alias of DateInterval::format
    • date_isodate_set — Alias of DateTime::setISODate
    • date_modify — Alias of DateTime::modify
    • date_offset_get — Alias of DateTime::getOffset
    • date_parse_from_format — Get info about given date
    • date_parse — Returns associative array with detailed info about given date
    • date_sub — Alias of DateTime::sub
    • date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
    • date_sunrise — Returns time of sunrise for a given day and location
    • date_sunset — Returns time of sunset for a given day and location
    • date_time_set — Alias of DateTime::setTime
    • date_timestamp_get — Alias of DateTime::getTimestamp
    • date_timestamp_set — Alias of DateTime::setTimestamp
    • date_timezone_get — Alias of DateTime::getTimezone
    • date_timezone_set — Alias of DateTime::setTimezone
    • date — Format a local time/date
    • getdate — Get date/time information
    • gettimeofday — Get current time
    • gmdate — Format a GMT/UTC date/time
    • gmmktime — Get Unix timestamp for a GMT date
    • gmstrftime — Format a GMT/UTC time/date according to locale settings
    • idate — Format a local time/date as integer
    • localtime — Get the local time
    • microtime — Return current Unix timestamp with microseconds
    • mktime — Get Unix timestamp for a date
    • strftime — Format a local time/date according to locale settings
    • strptime — Parse a time/date generated with strftime
    • strtotime — Parse about any English textual datetime description into a Unix timestamp
    • time — Return current Unix timestamp
    • timezone_abbreviations_list — Alias of DateTimeZone::listAbbreviations
    • timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers
    • timezone_location_get — Alias of DateTimeZone::getLocation
    • timezone_name_from_abbr — Returns the timezone name from abbreviation
    • timezone_name_get — Alias of DateTimeZone::getName
    • timezone_offset_get — Alias of DateTimeZone::getOffset
    • timezone_open — Returns new DateTimeZone object
    • timezone_transitions_get — Alias of DateTimeZone::getTransitions
    • timezone_version_get — Gets the version of the timezonedb
unixtojd
Introduction
Date and Time Related Extensions


Database (dbm-style) Abstraction Layer

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • DBA Functions
    • dba_close — Close a DBA database
    • dba_delete — Delete DBA entry specified by key
    • dba_exists — Check whether key exists
    • dba_fetch — Fetch data specified by key
    • dba_firstkey — Fetch first key
    • dba_handlers — List all the handlers available
    • dba_insert — Insert entry
    • dba_key_split — Splits a key in string representation into array representation
    • dba_list — List all open database files
    • dba_nextkey — Fetch next key
    • dba_open — Open database
    • dba_optimize — Optimize database
    • dba_popen — Open database persistently
    • dba_replace — Replace or insert entry
    • dba_sync — Synchronize database
Abstraction Layers
Introduction
Abstraction Layers


dBase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • dBase Functions
    • dbase_add_record — Adds a record to a database
    • dbase_close — Closes a database
    • dbase_create — Creates a database
    • dbase_delete_record — Deletes a record from a database
    • dbase_get_header_info — Gets the header info of a database
    • dbase_get_record_with_names — Gets a record from a database as an associative array
    • dbase_get_record — Gets a record from a database as an indexed array
    • dbase_numfields — Gets the number of fields of a database
    • dbase_numrecords — Gets the number of records in a database
    • dbase_open — Opens a database
    • dbase_pack — Packs a database
    • dbase_replace_record — Replaces a record in a database
Vendor Specific Database Extensions
Introduction
Vendor Specific Database Extensions


DB++

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • db++ error codes
  • DB++ Functions
    • dbplus_add — Add a tuple to a relation
    • dbplus_aql — Perform AQL query
    • dbplus_chdir — Get/Set database virtual current directory
    • dbplus_close — Close a relation
    • dbplus_curr — Get current tuple from relation
    • dbplus_errcode — Get error string for given errorcode or last error
    • dbplus_errno — Get error code for last operation
    • dbplus_find — Set a constraint on a relation
    • dbplus_first — Get first tuple from relation
    • dbplus_flush — Flush all changes made on a relation
    • dbplus_freealllocks — Free all locks held by this client
    • dbplus_freelock — Release write lock on tuple
    • dbplus_freerlocks — Free all tuple locks on given relation
    • dbplus_getlock — Get a write lock on a tuple
    • dbplus_getunique — Get an id number unique to a relation
    • dbplus_info — Get information about a relation
    • dbplus_last — Get last tuple from relation
    • dbplus_lockrel — Request write lock on relation
    • dbplus_next — Get next tuple from relation
    • dbplus_open — Open relation file
    • dbplus_prev — Get previous tuple from relation
    • dbplus_rchperm — Change relation permissions
    • dbplus_rcreate — Creates a new DB++ relation
    • dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices
    • dbplus_rcrtlike — Creates an empty copy of a relation with default indices
    • dbplus_resolve — Resolve host information for relation
    • dbplus_restorepos — Restore position
    • dbplus_rkeys — Specify new primary key for a relation
    • dbplus_ropen — Open relation file local
    • dbplus_rquery — Perform local (raw) AQL query
    • dbplus_rrename — Rename a relation
    • dbplus_rsecindex — Create a new secondary index for a relation
    • dbplus_runlink — Remove relation from filesystem
    • dbplus_rzap — Remove all tuples from relation
    • dbplus_savepos — Save position
    • dbplus_setindex — Set index
    • dbplus_setindexbynumber — Set index by number
    • dbplus_sql — Perform SQL query
    • dbplus_tcl — Execute TCL code on server side
    • dbplus_tremove — Remove tuple and return new current tuple
    • dbplus_undo — Undo
    • dbplus_undoprepare — Prepare undo
    • dbplus_unlockrel — Give up write lock on relation
    • dbplus_unselect — Remove a constraint from relation
    • dbplus_update — Update specified tuple in relation
    • dbplus_xlockrel — Request exclusive lock on relation
    • dbplus_xunlockrel — Free exclusive lock on relation
dbase_replace_record
Introduction
Vendor Specific Database Extensions


dbx

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • dbx Functions
    • dbx_close — Close an open connection/database
    • dbx_compare — Compare two rows for sorting purposes
    • dbx_connect — Open a connection/database
    • dbx_error — Report the error message of the latest function call in the module
    • dbx_escape_string — Escape a string so it can safely be used in an sql-statement
    • dbx_fetch_row — Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
    • dbx_query — Send a query and fetch all results (if any)
    • dbx_sort — Sort a result from a dbx_query by a custom sort function
dba_sync
Introduction
Abstraction Layers


Direct IO

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Direct IO Functions
    • dio_close — Closes the file descriptor given by fd
    • dio_fcntl — Performs a c library fcntl on fd
    • dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.
    • dio_read — Reads bytes from a file descriptor
    • dio_seek — Seeks to pos on fd from whence
    • dio_stat — Gets stat information about the file descriptor fd
    • dio_tcsetattr — Sets terminal attributes and baud rate for a serial port
    • dio_truncate — Truncates file descriptor fd to offset bytes
    • dio_write — Writes data to fd with optional truncation at length
File System Related Extensions
Introduction
File System Related Extensions


Directories

  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Directory Functions
    • chdir — Change directory
    • chroot — Change the root directory
    • dir — Return an instance of the Directory class
    • closedir — Close directory handle
    • getcwd — Gets the current working directory
    • opendir — Open directory handle
    • readdir — Read entry from directory handle
    • rewinddir — Rewind directory handle
    • scandir — List files and directories inside the specified path
dio_write
Installing/Configuring
File System Related Extensions


Enchant spelling library

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Enchant Functions
    • enchant_broker_describe — Enumerates the Enchant providers
    • enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
    • enchant_broker_free_dict — Free a dictionary resource
    • enchant_broker_free — Free the broker resource and its dictionnaries
    • enchant_broker_get_error — Returns the last error of the broker
    • enchant_broker_init — create a new broker object capable of requesting
    • enchant_broker_list_dicts — Returns a list of available dictionaries
    • enchant_broker_request_dict — create a new dictionary using a tag
    • enchant_broker_request_pwl_dict — creates a dictionary using a PWL file
    • enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language
    • enchant_dict_add_to_personal — add a word to personal word list
    • enchant_dict_add_to_session — add 'word' to this spell-checking session
    • enchant_dict_check — Check whether a word is correctly spelled or not
    • enchant_dict_describe — Describes an individual dictionary
    • enchant_dict_get_error — Returns the last error of the current spelling-session
    • enchant_dict_is_in_session — whether or not 'word' exists in this spelling-session
    • enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions
    • enchant_dict_store_replacement — Add a correction for a word
    • enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met
Human Language and Character Encoding Support
Introduction
Human Language and Character Encoding Support


Error Handling and Logging

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Error Handling Functions
    • debug_backtrace — Generates a backtrace
    • debug_print_backtrace — Prints a backtrace
    • error_get_last — Get the last occurred error
    • error_log — Send an error message somewhere
    • error_reporting — Sets which PHP errors are reported
    • restore_error_handler — Restores the previous error handler function
    • restore_exception_handler — Restores the previously defined exception handler function
    • set_error_handler — Sets a user-defined error handler function
    • set_exception_handler — Sets a user-defined exception handler function
    • trigger_error — Generates a user-level error/warning/notice message
    • user_error — Alias of trigger_error
bcompiler_write_included_filename
Introduction
Affecting PHP's Behaviour


System program execution

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Program execution Functions
    • escapeshellarg — Escape a string to be used as a shell argument
    • escapeshellcmd — Escape shell metacharacters
    • exec — Execute an external program
    • passthru — Execute an external program and display raw output
    • proc_close — Close a process opened by proc_open and return the exit code of that process
    • proc_get_status — Get information about a process opened by proc_open
    • proc_nice — Change the priority of the current process
    • proc_open — Execute a command and open file pointers for input/output
    • proc_terminate — Kills a process opened by proc_open
    • shell_exec — Execute command via shell and return the complete output as a string
    • system — Execute an external program and display the output
Process Control Extensions
Introduction
Process Control Extensions


Exchangeable image information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Exif Functions
    • exif_imagetype — Determine the type of an image
    • exif_read_data — Reads the EXIF headers from JPEG or TIFF
    • exif_tagname — Get the header name for an index
    • exif_thumbnail — Retrieve the embedded thumbnail of a TIFF or JPEG image
    • read_exif_data — Alias of exif_read_data
Image Processing and Generation
Introduction
Image Processing and Generation


Expect

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Expect Usage Examples
  • Expect Functions
    • expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
    • expect_popen — Execute command via Bourne shell, and open the PTY stream to the process
system
Introduction
Process Control Extensions


FrontBase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • FrontBase Functions
    • fbsql_affected_rows — Get number of affected rows in previous FrontBase operation
    • fbsql_autocommit — Enable or disable autocommit
    • fbsql_blob_size — Get the size of a BLOB
    • fbsql_change_user — Change logged in user of the active connection
    • fbsql_clob_size — Get the size of a CLOB
    • fbsql_close — Close FrontBase connection
    • fbsql_commit — Commits a transaction to the database
    • fbsql_connect — Open a connection to a FrontBase Server
    • fbsql_create_blob — Create a BLOB
    • fbsql_create_clob — Create a CLOB
    • fbsql_create_db — Create a FrontBase database
    • fbsql_data_seek — Move internal result pointer
    • fbsql_database_password — Sets or retrieves the password for a FrontBase database
    • fbsql_database — Get or set the database name used with a connection
    • fbsql_db_query — Send a FrontBase query
    • fbsql_db_status — Get the status for a given database
    • fbsql_drop_db — Drop (delete) a FrontBase database
    • fbsql_errno — Returns the error number from previous operation
    • fbsql_error — Returns the error message from previous operation
    • fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • fbsql_fetch_assoc — Fetch a result row as an associative array
    • fbsql_fetch_field — Get column information from a result and return as an object
    • fbsql_fetch_lengths — Get the length of each output in a result
    • fbsql_fetch_object — Fetch a result row as an object
    • fbsql_fetch_row — Get a result row as an enumerated array
    • fbsql_field_flags — Get the flags associated with the specified field in a result
    • fbsql_field_len — Returns the length of the specified field
    • fbsql_field_name — Get the name of the specified field in a result
    • fbsql_field_seek — Set result pointer to a specified field offset
    • fbsql_field_table — Get name of the table the specified field is in
    • fbsql_field_type — Get the type of the specified field in a result
    • fbsql_free_result — Free result memory
    • fbsql_get_autostart_info — Description
    • fbsql_hostname — Get or set the host name used with a connection
    • fbsql_insert_id — Get the id generated from the previous INSERT operation
    • fbsql_list_dbs — List databases available on a FrontBase server
    • fbsql_list_fields — List FrontBase result fields
    • fbsql_list_tables — List tables in a FrontBase database
    • fbsql_next_result — Move the internal result pointer to the next result
    • fbsql_num_fields — Get number of fields in result
    • fbsql_num_rows — Get number of rows in result
    • fbsql_password — Get or set the user password used with a connection
    • fbsql_pconnect — Open a persistent connection to a FrontBase Server
    • fbsql_query — Send a FrontBase query
    • fbsql_read_blob — Read a BLOB from the database
    • fbsql_read_clob — Read a CLOB from the database
    • fbsql_result — Get result data
    • fbsql_rollback — Rollback a transaction to the database
    • fbsql_rows_fetched — Get the number of rows affected by the last statement
    • fbsql_select_db — Select a FrontBase database
    • fbsql_set_characterset — Change input/output character set
    • fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set
    • fbsql_set_password — Change the password for a given user
    • fbsql_set_transaction — Set the transaction locking and isolation
    • fbsql_start_db — Start a database on local or remote server
    • fbsql_stop_db — Stop a database on local or remote server
    • fbsql_table_name — Get table name of field
    • fbsql_tablename — Alias of of fbsql_table_name
    • fbsql_username — Get or set the username for the connection
    • fbsql_warnings — Enable or disable FrontBase warnings
dbplus_xunlockrel
Introduction
Vendor Specific Database Extensions


Forms Data Format

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • FDF Functions
    • fdf_add_doc_javascript — Adds javascript code to the FDF document
    • fdf_add_template — Adds a template into the FDF document
    • fdf_close — Close an FDF document
    • fdf_create — Create a new FDF document
    • fdf_enum_values — Call a user defined function for each document value
    • fdf_errno — Return error code for last fdf operation
    • fdf_error — Return error description for FDF error code
    • fdf_get_ap — Get the appearance of a field
    • fdf_get_attachment — Extracts uploaded file embedded in the FDF
    • fdf_get_encoding — Get the value of the /Encoding key
    • fdf_get_file — Get the value of the /F key
    • fdf_get_flags — Gets the flags of a field
    • fdf_get_opt — Gets a value from the opt array of a field
    • fdf_get_status — Get the value of the /STATUS key
    • fdf_get_value — Get the value of a field
    • fdf_get_version — Gets version number for FDF API or file
    • fdf_header — Sets FDF-specific output headers
    • fdf_next_field_name — Get the next field name
    • fdf_open_string — Read a FDF document from a string
    • fdf_open — Open a FDF document
    • fdf_remove_item — Sets target frame for form
    • fdf_save_string — Returns the FDF document as a string
    • fdf_save — Save a FDF document
    • fdf_set_ap — Set the appearance of a field
    • fdf_set_encoding — Sets FDF character encoding
    • fdf_set_file — Set PDF document to display FDF data in
    • fdf_set_flags — Sets a flag of a field
    • fdf_set_javascript_action — Sets an javascript action of a field
    • fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF
    • fdf_set_opt — Sets an option of a field
    • fdf_set_status — Set the value of the /STATUS key
    • fdf_set_submit_form_action — Sets a submit form action of a field
    • fdf_set_target_frame — Set target frame for form display
    • fdf_set_value — Set the value of a field
    • fdf_set_version — Sets version number for a FDF file
Non-Text MIME Output
Introduction
Non-Text MIME Output


File Information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Fileinfo Functions
    • finfo_buffer — Return information about a string buffer
    • finfo_close — Close fileinfo resource
    • finfo_file — Return information about a file
    • finfo_open — Create a new fileinfo resource
    • finfo_set_flags — Set libmagic configuration options
    • mime_content_type — Detect MIME Content-type for a file (deprecated)
scandir
Introduction
File System Related Extensions


filePro

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • filePro Functions
    • filepro_fieldcount — Find out how many fields are in a filePro database
    • filepro_fieldname — Gets the name of a field
    • filepro_fieldtype — Gets the type of a field
    • filepro_fieldwidth — Gets the width of a field
    • filepro_retrieve — Retrieves data from a filePro database
    • filepro_rowcount — Find out how many rows are in a filePro database
    • filepro — Read and verify the map file
fbsql_warnings
Introduction
Vendor Specific Database Extensions


Filesystem

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Filesystem Functions
    • basename — Returns filename component of path
    • chgrp — Changes file group
    • chmod — Changes file mode
    • chown — Changes file owner
    • clearstatcache — Clears file status cache
    • copy — Copies file
    • delete — See unlink or unset
    • dirname — Returns directory name component of path
    • disk_free_space — Returns available space in directory
    • disk_total_space — Returns the total size of a directory
    • diskfreespace — Alias of disk_free_space
    • fclose — Closes an open file pointer
    • feof — Tests for end-of-file on a file pointer
    • fflush — Flushes the output to a file
    • fgetc — Gets character from file pointer
    • fgetcsv — Gets line from file pointer and parse for CSV fields
    • fgets — Gets line from file pointer
    • fgetss — Gets line from file pointer and strip HTML tags
    • file_exists — Checks whether a file or directory exists
    • file_get_contents — Reads entire file into a string
    • file_put_contents — Write a string to a file
    • file — Reads entire file into an array
    • fileatime — Gets last access time of file
    • filectime — Gets inode change time of file
    • filegroup — Gets file group
    • fileinode — Gets file inode
    • filemtime — Gets file modification time
    • fileowner — Gets file owner
    • fileperms — Gets file permissions
    • filesize — Gets file size
    • filetype — Gets file type
    • flock — Portable advisory file locking
    • fnmatch — Match filename against a pattern
    • fopen — Opens file or URL
    • fpassthru — Output all remaining data on a file pointer
    • fputcsv — Format line as CSV and write to file pointer
    • fputs — Alias of fwrite
    • fread — Binary-safe file read
    • fscanf — Parses input from a file according to a format
    • fseek — Seeks on a file pointer
    • fstat — Gets information about a file using an open file pointer
    • ftell — Returns the current position of the file read/write pointer
    • ftruncate — Truncates a file to a given length
    • fwrite — Binary-safe file write
    • glob — Find pathnames matching a pattern
    • is_dir — Tells whether the filename is a directory
    • is_executable — Tells whether the filename is executable
    • is_file — Tells whether the filename is a regular file
    • is_link — Tells whether the filename is a symbolic link
    • is_readable — Tells whether a file exists and is readable
    • is_uploaded_file — Tells whether the file was uploaded via HTTP POST
    • is_writable — Tells whether the filename is writable
    • is_writeable — Alias of is_writable
    • lchgrp — Changes group ownership of symlink
    • lchown — Changes user ownership of symlink
    • link — Create a hard link
    • linkinfo — Gets information about a link
    • lstat — Gives information about a file or symbolic link
    • mkdir — Makes directory
    • move_uploaded_file — Moves an uploaded file to a new location
    • parse_ini_file — Parse a configuration file
    • parse_ini_string — Parse a configuration string
    • pathinfo — Returns information about a file path
    • pclose — Closes process file pointer
    • popen — Opens process file pointer
    • readfile — Outputs a file
    • readlink — Returns the target of a symbolic link
    • realpath_cache_get — Get realpath cache entries
    • realpath_cache_size — Get realpath cache size
    • realpath — Returns canonicalized absolute pathname
    • rename — Renames a file or directory
    • rewind — Rewind the position of a file pointer
    • rmdir — Removes directory
    • set_file_buffer — Alias of stream_set_write_buffer
    • stat — Gives information about a file
    • symlink — Creates a symbolic link
    • tempnam — Create file with unique file name
    • tmpfile — Creates a temporary file
    • touch — Sets access and modification time of file
    • umask — Changes the current umask
    • unlink — Deletes a file
mime_content_type
Introduction
File System Related Extensions


FriBiDi

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • FriBiDi Functions
    • fribidi_log2vis — Convert a logical string to a visual one
enchant_dict_suggest
Introduction
Human Language and Character Encoding Support


Geo IP Location

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • GeoIP Functions
    • geoip_continent_code_by_name — Get the two letter continent code
    • geoip_country_code_by_name — Get the two letter country code
    • geoip_country_code3_by_name — Get the three letter country code
    • geoip_country_name_by_name — Get the full country name
    • geoip_database_info — Get GeoIP Database information
    • geoip_db_avail — Determine if GeoIP Database is available
    • geoip_db_filename — Returns the filename of the corresponding GeoIP Database
    • geoip_db_get_all_info — Returns detailed information about all GeoIP database types
    • geoip_id_by_name — Get the Internet connection speed
    • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
    • geoip_org_by_name — Get the organization name
    • geoip_record_by_name — Returns the detailed City information found in the GeoIP Database
    • geoip_region_by_name — Get the country code and region
    • geoip_region_name_by_code — Returns the region name for some country and region code combo
    • geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo
Other Basic Extensions
Introduction
Other Basic Extensions


Gettext

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Gettext Functions
    • bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
    • bindtextdomain — Sets the path for a domain
    • dcgettext — Overrides the domain for a single lookup
    • dcngettext — Plural version of dcgettext
    • dgettext — Override the current domain
    • dngettext — Plural version of dgettext
    • gettext — Lookup a message in the current domain
    • ngettext — Plural version of gettext
    • textdomain — Sets the default domain
fribidi_log2vis
Introduction
Human Language and Character Encoding Support


Gmagick

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Examples
  • Gmagick — The Gmagick class
    • Gmagick::addimage — Adds new image to Gmagick object image list
    • Gmagick::addnoiseimage — Adds random noise to the image
    • Gmagick::annotateimage — Annotates an image with text
    • Gmagick::blurimage — Adds blur filter to image
    • Gmagick::borderimage — Surrounds the image with a border
    • Gmagick::charcoalimage — Simulates a charcoal drawing
    • Gmagick::chopimage — Removes a region of an image and trims
    • Gmagick::clear — Clears all resources associated to Gmagick object
    • Gmagick::commentimage — Adds a comment to your image
    • Gmagick::compositeimage — Composite one image onto another
    • Gmagick::__construct — The Gmagick constructor
    • Gmagick::cropimage — Extracts a region of the image
    • Gmagick::cropthumbnailimage — Creates a crop thumbnail
    • Gmagick::current — The current purpose
    • Gmagick::cyclecolormapimage — Displaces an image's colormap
    • Gmagick::deconstructimages — Returns certain pixel differences between images
    • Gmagick::despeckleimage — The despeckleimage purpose
    • Gmagick::destroy — The destroy purpose
    • Gmagick::drawimage — Renders the GmagickDraw object on the current image
    • Gmagick::edgeimage — Enhance edges within the image
    • Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect
    • Gmagick::enhanceimage — Improves the quality of a noisy image
    • Gmagick::equalizeimage — Equalizes the image histogram
    • Gmagick::flipimage — Creates a vertical mirror image
    • Gmagick::flopimage — The flopimage purpose
    • Gmagick::frameimage — Adds a simulated three-dimensional border
    • Gmagick::gammaimage — Gamma-corrects an image
    • Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string
    • Gmagick::getfilename — The filename associated with an image sequence
    • Gmagick::getimagebackgroundcolor — Returns the image background color
    • Gmagick::getimageblueprimary — Returns the chromaticy blue primary point
    • Gmagick::getimagebordercolor — Returns the image border color
    • Gmagick::getimagechanneldepth — Gets the depth for a particular image channel
    • Gmagick::getimagecolors — Returns the color of the specified colormap index
    • Gmagick::getimagecolorspace — Gets the image colorspace
    • Gmagick::getimagecompose — Returns the composite operator associated with the image
    • Gmagick::getimagedelay — Gets the image delay
    • Gmagick::getimagedepth — Gets the depth of the image
    • Gmagick::getimagedispose — Gets the image disposal method
    • Gmagick::getimageextrema — Gets the extrema for the image
    • Gmagick::getimagefilename — Returns the filename of a particular image in a sequence
    • Gmagick::getimageformat — Returns the format of a particular image in a sequence
    • Gmagick::getimagegamma — Gets the image gamma
    • Gmagick::getimagegreenprimary — Returns the chromaticy green primary point
    • Gmagick::getimageheight — Returns the image height
    • Gmagick::getimagehistogram — Gets the image histogram
    • Gmagick::getimageindex — Gets the index of the current active image
    • Gmagick::getimageinterlacescheme — Gets the image interlace scheme
    • Gmagick::getimageiterations — Gets the image iterations
    • Gmagick::getimagematte — Return if the image has a matte channel
    • Gmagick::getimagemattecolor — Returns the image matte color
    • Gmagick::getimageprofile — Returns the named image profile.
    • Gmagick::getimageredprimary — Returns the chromaticity red primary point
    • Gmagick::getimagerenderingintent — Gets the image rendering intent
    • Gmagick::getimageresolution — Gets the image X and Y resolution
    • Gmagick::getimagescene — Gets the image scene
    • Gmagick::getimagesignature — Generates an SHA-256 message digest
    • Gmagick::getimagetype — Gets the potential image type.
    • Gmagick::getimageunits — Gets the image units of resolution
    • Gmagick::getimagewhitepoint — Returns the chromaticity white point
    • Gmagick::getimagewidth — Returns the width of the image
    • Gmagick::getpackagename — Returns the GraphicsMagick package name.
    • Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string.
    • Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string.
    • Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor.
    • Gmagick::getsize — Returns the size associated with the Gmagick object
    • Gmagick::getversion — Returns the GraphicsMagick API version
    • Gmagick::hasnextimage — Checks if the object has more images
    • Gmagick::haspreviousimage — Checks if the object has a previous image
    • Gmagick::implodeimage — Creates a new image as a copy
    • Gmagick::labelimage — Adds a label to an image.
    • Gmagick::levelimage — Adjusts the levels of an image
    • Gmagick::magnifyimage — Scales an image proportionally 2x
    • Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image.
    • Gmagick::medianfilterimage — Applies a digital filter
    • Gmagick::minifyimage — Scales an image proportionally to half its size
    • Gmagick::modulateimage — Control the brightness, saturation, and hue
    • Gmagick::motionblurimage — Simulates motion blur
    • Gmagick::newimage — Creates a new image
    • Gmagick::nextimage — Moves to the next image
    • Gmagick::normalizeimage — Enhances the contrast of a color image
    • Gmagick::oilpaintimage — Simulates an oil painting
    • Gmagick::previousimage — Move to the previous image in the object
    • Gmagick::profileimage — Adds or removes a profile from an image
    • Gmagick::quantizeimage — Analyzes the colors within a reference image
    • Gmagick::quantizeimages — The quantizeimages purpose
    • Gmagick::queryfontmetrics — Returns an array representing the font metrics
    • Gmagick::queryfonts — Returns the configured fonts
    • Gmagick::queryformats — Returns formats supported by Gmagick.
    • Gmagick::radialblurimage — Radial blurs an image
    • Gmagick::raiseimage — Creates a simulated 3d button-like effect
    • Gmagick::read — Reads image from filename
    • Gmagick::readimage — Reads image from filename
    • Gmagick::readimageblob — Reads image from a binary string
    • Gmagick::readimagefile — The readimagefile purpose
    • Gmagick::reducenoiseimage — Smooths the contours of an image
    • Gmagick::removeimage — Removes an image from the image list
    • Gmagick::removeimageprofile — Removes the named image profile and returns it
    • Gmagick::resampleimage — Resample image to desired resolution
    • Gmagick::resizeimage — Scales an image
    • Gmagick::rollimage — Offsets an image
    • Gmagick::rotateimage — Rotates an image
    • Gmagick::scaleimage — Scales the size of an image
    • Gmagick::separateimagechannel — Separates a channel from the image
    • Gmagick::setfilename — Sets the filename before you read or write the image
    • Gmagick::setimagebackgroundcolor — Sets the image background color.
    • Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point.
    • Gmagick::setimagebordercolor — Sets the image border color.
    • Gmagick::setimagechanneldepth — Sets the depth of a particular image channel
    • Gmagick::setimagecolorspace — Sets the image colorspace
    • Gmagick::setimagecompose — Sets the image composite operator
    • Gmagick::setimagedelay — Sets the image delay
    • Gmagick::setimagedepth — Sets the image depth
    • Gmagick::setimagedispose — Sets the image disposal method
    • Gmagick::setimagefilename — Sets the filename of a particular image in a sequence
    • Gmagick::setimageformat — Sets the format of a particular image
    • Gmagick::setimagegamma — Sets the image gamma
    • Gmagick::setimagegreenprimary — TSets the image chromaticity green primary point.
    • Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter
    • Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image.
    • Gmagick::setimageiterations — Sets the image iterations.
    • Gmagick::setimageprofile — Adds a named profile to the Gmagick object
    • Gmagick::setimageredprimary — Sets the image chromaticity red primary point.
    • Gmagick::setimagerenderingintent — Sets the image rendering intent
    • Gmagick::setimageresolution — Sets the image resolution
    • Gmagick::setimagescene — Sets the image scene
    • Gmagick::setimagetype — Sets the image type
    • Gmagick::setimageunits — Sets the image units of resolution.
    • Gmagick::setimagewhitepoint — Sets the image chromaticity white point.
    • Gmagick::setsamplingfactors — Sets the image sampling factors.
    • Gmagick::setsize — Sets the size of the Gmagick object
    • Gmagick::shearimage — Creating a parallelogram
    • Gmagick::solarizeimage — Applies a solarizing effect to the image
    • Gmagick::spreadimage — Randomly displaces each pixel in a block
    • Gmagick::stripimage — Strips an image of all profiles and comments
    • Gmagick::swirlimage — Swirls the pixels about the center of the image
    • Gmagick::thumbnailimage — Changes the size of an image
    • Gmagick::trimimage — Remove edges from the image
    • Gmagick::write — Writes an image to the specified filename
    • Gmagick::writeimage — Writes an image to the specified filename
  • GmagickDraw — The GmagickDraw class
    • GmagickDraw::annotate — Draws text on the image
    • GmagickDraw::arc — Draws an arc
    • GmagickDraw::bezier — Draws a bezier curve
    • GmagickDraw::ellipse — Draws an ellipse on the image
    • GmagickDraw::getfillcolor — Returns the fill color
    • GmagickDraw::getfillopacity — Returns the opacity used when drawing
    • GmagickDraw::getfont — Returns the font
    • GmagickDraw::getfontsize — Returns the font pointsize
    • GmagickDraw::getfontstyle — Returns the font style
    • GmagickDraw::getfontweight — Returns the font weight
    • GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines
    • GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines
    • GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines
    • GmagickDraw::gettextdecoration — Returns the text decoration
    • GmagickDraw::gettextencoding — Returns the code set used for text annotations
    • GmagickDraw::line — The line purpose
    • GmagickDraw::point — Draws a point
    • GmagickDraw::polygon — Draws a polygon
    • GmagickDraw::polyline — Draws a polyline
    • GmagickDraw::rectangle — Draws a rectangle
    • GmagickDraw::rotate — Applies the specified rotation to the current coordinate space
    • GmagickDraw::roundrectangle — Draws a rounded rectangle
    • GmagickDraw::scale — Adjusts the scaling factor
    • GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects.
    • GmagickDraw::setfillopacity — The setfillopacity purpose
    • GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text.
    • GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text.
    • GmagickDraw::setfontstyle — Sets the font style to use when annotating with text
    • GmagickDraw::setfontweight — Sets the font weight
    • GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines.
    • GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines.
    • GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines.
    • GmagickDraw::settextdecoration — Specifies a decoration
    • GmagickDraw::settextencoding — Specifies specifies the text code set
  • GmagickPixel — The GmagickPixel class
    • GmagickPixel::__construct — The GmagickPixel constructor
    • GmagickPixel::getcolor — Returns the color
    • GmagickPixel::getcolorcount — Returns the color count associated with this color
    • GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel
    • GmagickPixel::setcolor — Sets the color
    • GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels
ImagickPixelIterator::syncIterator
Introduction
Image Processing and Generation


GNU Multiple Precision

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • GMP Functions
    • gmp_abs — Absolute value
    • gmp_add — Add numbers
    • gmp_and — Bitwise AND
    • gmp_clrbit — Clear bit
    • gmp_cmp — Compare numbers
    • gmp_com — Calculates one's complement
    • gmp_div_q — Divide numbers
    • gmp_div_qr — Divide numbers and get quotient and remainder
    • gmp_div_r — Remainder of the division of numbers
    • gmp_div — Alias of gmp_div_q
    • gmp_divexact — Exact division of numbers
    • gmp_fact — Factorial
    • gmp_gcd — Calculate GCD
    • gmp_gcdext — Calculate GCD and multipliers
    • gmp_hamdist — Hamming distance
    • gmp_init — Create GMP number
    • gmp_intval — Convert GMP number to integer
    • gmp_invert — Inverse by modulo
    • gmp_jacobi — Jacobi symbol
    • gmp_legendre — Legendre symbol
    • gmp_mod — Modulo operation
    • gmp_mul — Multiply numbers
    • gmp_neg — Negate number
    • gmp_nextprime — Find next prime number
    • gmp_or — Bitwise OR
    • gmp_perfect_square — Perfect square check
    • gmp_popcount — Population count
    • gmp_pow — Raise number into power
    • gmp_powm — Raise number into power with modulo
    • gmp_prob_prime — Check if number is "probably prime"
    • gmp_random — Random number
    • gmp_scan0 — Scan for 0
    • gmp_scan1 — Scan for 1
    • gmp_setbit — Set bit
    • gmp_sign — Sign of number
    • gmp_sqrt — Calculate square root
    • gmp_sqrtrem — Square root with remainder
    • gmp_strval — Convert GMP number to string
    • gmp_sub — Subtract numbers
    • gmp_testbit — Tests if a bit is set
    • gmp_xor — Bitwise XOR
bcsub
Introduction
Mathematical Extensions


GNU Privacy Guard

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Clearsign text
  • GnuPG Functions
    • gnupg_adddecryptkey — Add a key for decryption
    • gnupg_addencryptkey — Add a key for encryption
    • gnupg_addsignkey — Add a key for signing
    • gnupg_cleardecryptkeys — Removes all keys which were set for decryption before
    • gnupg_clearencryptkeys — Removes all keys which were set for encryption before
    • gnupg_clearsignkeys — Removes all keys which were set for signing before
    • gnupg_decrypt — Decrypts a given text
    • gnupg_decryptverify — Decrypts and verifies a given text
    • gnupg_encrypt — Encrypts a given text
    • gnupg_encryptsign — Encrypts and signs a given text
    • gnupg_export — Exports a key
    • gnupg_geterror — Returns the errortext, if a function fails
    • gnupg_getprotocol — Returns the currently active protocol for all operations
    • gnupg_import — Imports a key
    • gnupg_init — Initialize a connection
    • gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern
    • gnupg_setarmor — Toggle armored output
    • gnupg_seterrormode — Sets the mode for error_reporting
    • gnupg_setsignmode — Sets the mode for signing
    • gnupg_sign — Signs a given text
    • gnupg_verify — Verifies a signed text
fdf_set_version
Introduction
Non-Text MIME Output


Haru PDF

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic PECL/haru example
  • Builtin Fonts And Encodings
    • Builtin Fonts
    • Builtin Encodings
  • HaruException — The HaruException class
  • HaruDoc — The HaruDoc class
    • HaruDoc::addPage — Add new page to the document
    • HaruDoc::addPageLabel — Set the numbering style for the specified range of pages
    • HaruDoc::__construct — Construct new HaruDoc instance
    • HaruDoc::createOutline — Create a HaruOutline instance
    • HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document
    • HaruDoc::getCurrentPage — Return current page of the document
    • HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding
    • HaruDoc::getFont — Get HaruFont instance
    • HaruDoc::getInfoAttr — Get current value of the specified document attribute
    • HaruDoc::getPageLayout — Get current page layout
    • HaruDoc::getPageMode — Get current page mode
    • HaruDoc::getStreamSize — Get the size of the temporary stream
    • HaruDoc::insertPage — Insert new page just before the specified page
    • HaruDoc::loadJPEG — Load a JPEG image
    • HaruDoc::loadPNG — Load PNG image and return HaruImage instance
    • HaruDoc::loadRaw — Load a RAW image
    • HaruDoc::loadTTC — Load the font with the specified index from TTC file
    • HaruDoc::loadTTF — Load TTF font file
    • HaruDoc::loadType1 — Load Type1 font
    • HaruDoc::output — Write the document data to the output buffer
    • HaruDoc::readFromStream — Read data from the temporary stream
    • HaruDoc::resetError — Reset error state of the document handle
    • HaruDoc::resetStream — Rewind the temporary stream
    • HaruDoc::save — Save the document into the specified file
    • HaruDoc::saveToStream — Save the document into a temporary stream
    • HaruDoc::setCompressionMode — Set compression mode for the document
    • HaruDoc::setCurrentEncoder — Set the current encoder for the document
    • HaruDoc::setEncryptionMode — Set encryption mode for the document
    • HaruDoc::setInfoAttr — Set the info attribute of the document
    • HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document
    • HaruDoc::setOpenAction — Define which page is shown when the document is opened
    • HaruDoc::setPageLayout — Set how pages should be displayed
    • HaruDoc::setPageMode — Set how the document should be displayed
    • HaruDoc::setPagesConfiguration — Set the number of pages per set of pages
    • HaruDoc::setPassword — Set owner and user passwords for the document
    • HaruDoc::setPermission — Set permissions for the document
    • HaruDoc::useCNSEncodings — Enable Chinese simplified encodings
    • HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts
    • HaruDoc::useCNTEncodings — Enable Chinese traditional encodings
    • HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts
    • HaruDoc::useJPEncodings — Enable Japanese encodings
    • HaruDoc::useJPFonts — Enable builtin Japanese fonts
    • HaruDoc::useKREncodings — Enable Korean encodings
    • HaruDoc::useKRFonts — Enable builtin Korean fonts
  • HaruPage — The HaruPage class
    • HaruPage::arc — Append an arc to the current path
    • HaruPage::beginText — Begin a text object and set the current text position to (0,0)
    • HaruPage::circle — Append a circle to the current path
    • HaruPage::closePath — Append a straight line from the current point to the start point of the path
    • HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix
    • HaruPage::createDestination — Create new HaruDestination instance
    • HaruPage::createLinkAnnotation — Create new HaruAnnotation instance
    • HaruPage::createTextAnnotation — Create new HaruAnnotation instance
    • HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance
    • HaruPage::curveTo2 — Append a Bezier curve to the current path
    • HaruPage::curveTo3 — Append a Bezier curve to the current path
    • HaruPage::curveTo — Append a Bezier curve to the current path
    • HaruPage::drawImage — Show image at the page
    • HaruPage::ellipse — Append an ellipse to the current path
    • HaruPage::endPath — End current path object without filling and painting operations
    • HaruPage::endText — End current text object
    • HaruPage::eofill — Fill current path using even-odd rule
    • HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path
    • HaruPage::fill — Fill current path using nonzero winding number rule
    • HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path
    • HaruPage::getCharSpace — Get the current value of character spacing
    • HaruPage::getCMYKFill — Get the current filling color
    • HaruPage::getCMYKStroke — Get the current stroking color
    • HaruPage::getCurrentFont — Get the currently used font
    • HaruPage::getCurrentFontSize — Get the current font size
    • HaruPage::getCurrentPos — Get the current position for path painting
    • HaruPage::getCurrentTextPos — Get the current position for text printing
    • HaruPage::getDash — Get the current dash pattern
    • HaruPage::getFillingColorSpace — Get the current filling color space
    • HaruPage::getFlatness — Get the flatness of the page
    • HaruPage::getGMode — Get the current graphics mode
    • HaruPage::getGrayFill — Get the current filling color
    • HaruPage::getGrayStroke — Get the current stroking color
    • HaruPage::getHeight — Get the height of the page
    • HaruPage::getHorizontalScaling — Get the current value of horizontal scaling
    • HaruPage::getLineCap — Get the current line cap style
    • HaruPage::getLineJoin — Get the current line join style
    • HaruPage::getLineWidth — Get the current line width
    • HaruPage::getMiterLimit — Get the value of miter limit
    • HaruPage::getRGBFill — Get the current filling color
    • HaruPage::getRGBStroke — Get the current stroking color
    • HaruPage::getStrokingColorSpace — Get the current stroking color space
    • HaruPage::getTextLeading — Get the current value of line spacing
    • HaruPage::getTextMatrix — Get the current text transformation matrix of the page
    • HaruPage::getTextRenderingMode — Get the current text rendering mode
    • HaruPage::getTextRise — Get the current value of text rising
    • HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing
    • HaruPage::getTransMatrix — Get the current transformation matrix of the page
    • HaruPage::getWidth — Get the width of the page
    • HaruPage::getWordSpace — Get the current value of word spacing
    • HaruPage::lineTo — Draw a line from the current point to the specified point
    • HaruPage::measureText — Calculate the number of characters which can be included within the specified width
    • HaruPage::moveTextPos — Move text position to the specified offset
    • HaruPage::moveTo — Set starting point for new drawing path
    • HaruPage::moveToNextLine — Move text position to the start of the next line
    • HaruPage::rectangle — Append a rectangle to the current path
    • HaruPage::setCharSpace — Set character spacing for the page
    • HaruPage::setCMYKFill — Set filling color for the page
    • HaruPage::setCMYKStroke — Set stroking color for the page
    • HaruPage::setDash — Set the dash pattern for the page
    • HaruPage::setFlatness — Set flatness for the page
    • HaruPage::setFontAndSize — Set font and fontsize for the page
    • HaruPage::setGrayFill — Set filling color for the page
    • HaruPage::setGrayStroke — Sets stroking color for the page
    • HaruPage::setHeight — Set height of the page
    • HaruPage::setHorizontalScaling — Set horizontal scaling for the page
    • HaruPage::setLineCap — Set the shape to be used at the ends of lines
    • HaruPage::setLineJoin — Set line join style for the page
    • HaruPage::setLineWidth — Set line width for the page
    • HaruPage::setMiterLimit — Set the current value of the miter limit of the page
    • HaruPage::setRGBFill — Set filling color for the page
    • HaruPage::setRGBStroke — Set stroking color for the page
    • HaruPage::setRotate — Set rotation angle of the page
    • HaruPage::setSize — Set size and direction of the page
    • HaruPage::setSlideShow — Set transition style for the page
    • HaruPage::setTextLeading — Set text leading (line spacing) for the page
    • HaruPage::setTextMatrix — Set the current text transformation matrix of the page
    • HaruPage::setTextRenderingMode — Set text rendering mode for the page
    • HaruPage::setTextRise — Set the current value of text rising
    • HaruPage::setWidth — Set width of the page
    • HaruPage::setWordSpace — Set word spacing for the page
    • HaruPage::showText — Print text at the current position of the page
    • HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text
    • HaruPage::stroke — Paint current path
    • HaruPage::textOut — Print the text on the specified position
    • HaruPage::textRect — Print the text inside the specified region
  • HaruFont — The HaruFont class
    • HaruFont::getAscent — Get the vertical ascent of the font
    • HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters
    • HaruFont::getDescent — Get the vertical descent of the font
    • HaruFont::getEncodingName — Get the name of the encoding
    • HaruFont::getFontName — Get the name of the font
    • HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces
    • HaruFont::getUnicodeWidth — Get the width of the character in the font
    • HaruFont::getXHeight — Get the distance from the baseline of lowercase letters
    • HaruFont::measureText — Calculate the number of characters which can be included within the specified width
  • HaruImage — The HaruImage class
    • HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image
    • HaruImage::getColorSpace — Get the name of the color space
    • HaruImage::getHeight — Get the height of the image
    • HaruImage::getSize — Get size of the image
    • HaruImage::getWidth — Get the width of the image
    • HaruImage::setColorMask — Set the color mask of the image
    • HaruImage::setMaskImage — Set the image mask
  • HaruEncoder — The HaruEncoder class
    • HaruEncoder::getByteType — Get the type of the byte in the text
    • HaruEncoder::getType — Get the type of the encoder
    • HaruEncoder::getUnicode — Convert the specified character to unicode
    • HaruEncoder::getWritingMode — Get the writing mode of the encoder
  • HaruOutline — The HaruOutline class
    • HaruOutline::setDestination — Set the destination for the outline
    • HaruOutline::setOpened — Set the initial state of the outline
  • HaruAnnotation — The HaruAnnotation class
    • HaruAnnotation::setBorderStyle — Set the border style of the annotation
    • HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation
    • HaruAnnotation::setIcon — Set the icon style of the annotation
    • HaruAnnotation::setOpened — Set the initial state of the annotation
  • HaruDestination — The HaruDestination class
    • HaruDestination::setFit — Set the appearance of the page to fit the window
    • HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window
    • HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box
    • HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box
    • HaruDestination::setFitH — Set the appearance of the page to fit the window width
    • HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle
    • HaruDestination::setFitV — Set the appearance of the page to fit the window height
    • HaruDestination::setXYZ — Set the appearance of the page
gnupg_verify
Introduction
Non-Text MIME Output


HASH Message Digest Framework

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Hash Functions
    • hash_algos — Return a list of registered hashing algorithms
    • hash_copy — Copy hashing context
    • hash_file — Generate a hash value using the contents of a given file
    • hash_final — Finalize an incremental hash and return resulting digest
    • hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file
    • hash_hmac — Generate a keyed hash value using the HMAC method
    • hash_init — Initialize an incremental hashing context
    • hash_update_file — Pump data into an active hashing context from a file
    • hash_update_stream — Pump data into an active hashing context from an open stream
    • hash_update — Pump data into an active hashing context
    • hash — Generate a hash value (message digest)
crack_opendict
Introduction
Cryptography Extensions


htaccess-like support for all SAPIs

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
user_error
Introduction
Affecting PHP's Behaviour


Internationalization

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • i18n Functions
    • locale_get_default — Get the default Locale
    • locale_set_default — Set the default Locale
textdomain
Introduction
Human Language and Character Encoding Support


Firebird/InterBase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Firebird/InterBase Functions
    • ibase_add_user — Add a user to a security database (only for IB6 or later)
    • ibase_affected_rows — Return the number of rows that were affected by the previous query
    • ibase_backup — Initiates a backup task in the service manager and returns immediately
    • ibase_blob_add — Add data into a newly created blob
    • ibase_blob_cancel — Cancel creating blob
    • ibase_blob_close — Close blob
    • ibase_blob_create — Create a new blob for adding data
    • ibase_blob_echo — Output blob contents to browser
    • ibase_blob_get — Get len bytes data from open blob
    • ibase_blob_import — Create blob, copy file in it, and close it
    • ibase_blob_info — Return blob length and other useful info
    • ibase_blob_open — Open blob for retrieving data parts
    • ibase_close — Close a connection to an InterBase database
    • ibase_commit_ret — Commit a transaction without closing it
    • ibase_commit — Commit a transaction
    • ibase_connect — Open a connection to an InterBase database
    • ibase_db_info — Request statistics about a database
    • ibase_delete_user — Delete a user from a security database (only for IB6 or later)
    • ibase_drop_db — Drops a database
    • ibase_errcode — Return an error code
    • ibase_errmsg — Return error messages
    • ibase_execute — Execute a previously prepared query
    • ibase_fetch_assoc — Fetch a result row from a query as an associative array
    • ibase_fetch_object — Get an object from a InterBase database
    • ibase_fetch_row — Fetch a row from an InterBase database
    • ibase_field_info — Get information about a field
    • ibase_free_event_handler — Cancels a registered event handler
    • ibase_free_query — Free memory allocated by a prepared query
    • ibase_free_result — Free a result set
    • ibase_gen_id — Increments the named generator and returns its new value
    • ibase_maintain_db — Execute a maintenance command on the database server
    • ibase_modify_user — Modify a user to a security database (only for IB6 or later)
    • ibase_name_result — Assigns a name to a result set
    • ibase_num_fields — Get the number of fields in a result set
    • ibase_num_params — Return the number of parameters in a prepared query
    • ibase_param_info — Return information about a parameter in a prepared query
    • ibase_pconnect — Open a persistent connection to an InterBase database
    • ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
    • ibase_query — Execute a query on an InterBase database
    • ibase_restore — Initiates a restore task in the service manager and returns immediately
    • ibase_rollback_ret — Roll back a transaction without closing it
    • ibase_rollback — Roll back a transaction
    • ibase_server_info — Request information about a database server
    • ibase_service_attach — Connect to the service manager
    • ibase_service_detach — Disconnect from the service manager
    • ibase_set_event_handler — Register a callback function to be called when events are posted
    • ibase_timefmt — Sets the format of timestamp, date and time type columns returned from queries
    • ibase_trans — Begin a transaction
    • ibase_wait_event — Wait for an event to be posted by the database
filepro
Introduction
Vendor Specific Database Extensions


IBM DB2, Cloudscape and Apache Derby

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • IBM DB2 Functions
    • db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection
    • db2_bind_param — Binds a PHP variable to an SQL statement parameter
    • db2_client_info — Returns an object with properties that describe the DB2 database client
    • db2_close — Closes a database connection
    • db2_column_privileges — Returns a result set listing the columns and associated privileges for a table
    • db2_columns — Returns a result set listing the columns and associated metadata for a table
    • db2_commit — Commits a transaction
    • db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt
    • db2_conn_errormsg — Returns the last connection error message and SQLCODE value
    • db2_connect — Returns a connection to a database
    • db2_cursor_type — Returns the cursor type used by a statement resource
    • db2_escape_string — Used to escape certain characters
    • db2_exec — Executes an SQL statement directly
    • db2_execute — Executes a prepared SQL statement
    • db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set
    • db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set
    • db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set
    • db2_fetch_object — Returns an object with properties representing columns in the fetched row
    • db2_fetch_row — Sets the result set pointer to the next row or requested row
    • db2_field_display_size — Returns the maximum number of bytes required to display a column
    • db2_field_name — Returns the name of the column in the result set
    • db2_field_num — Returns the position of the named column in a result set
    • db2_field_precision — Returns the precision of the indicated column in a result set
    • db2_field_scale — Returns the scale of the indicated column in a result set
    • db2_field_type — Returns the data type of the indicated column in a result set
    • db2_field_width — Returns the width of the current value of the indicated column in a result set
    • db2_foreign_keys — Returns a result set listing the foreign keys for a table
    • db2_free_result — Frees resources associated with a result set
    • db2_free_stmt — Frees resources associated with the indicated statement resource
    • db2_get_option — Retrieves an option value for a statement resource or a connection resource
    • db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection
    • db2_lob_read — Gets a user defined size of LOB files with each invocation
    • db2_next_result — Requests the next result set from a stored procedure
    • db2_num_fields — Returns the number of fields contained in a result set
    • db2_num_rows — Returns the number of rows affected by an SQL statement
    • db2_pclose — Closes a persistent database connection
    • db2_pconnect — Returns a persistent connection to a database
    • db2_prepare — Prepares an SQL statement to be executed
    • db2_primary_keys — Returns a result set listing primary keys for a table
    • db2_procedure_columns — Returns a result set listing stored procedure parameters
    • db2_procedures — Returns a result set listing the stored procedures registered in a database
    • db2_result — Returns a single column from a row in the result set
    • db2_rollback — Rolls back a transaction
    • db2_server_info — Returns an object with properties that describe the DB2 database server
    • db2_set_option — Set options for connection or statement resources
    • db2_special_columns — Returns a result set listing the unique row identifier columns for a table
    • db2_statistics — Returns a result set listing the index and statistics for a table
    • db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
    • db2_stmt_errormsg — Returns a string containing the last SQL statement error message
    • db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
    • db2_tables — Returns a result set listing the tables and associated metadata in a database
ifxus_write_slob
Introduction
Vendor Specific Database Extensions


iconv

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • iconv Functions
    • iconv_get_encoding — Retrieve internal configuration variables of iconv extension
    • iconv_mime_decode_headers — Decodes multiple MIME header fields at once
    • iconv_mime_decode — Decodes a MIME header field
    • iconv_mime_encode — Composes a MIME header field
    • iconv_set_encoding — Set current setting for character encoding conversion
    • iconv_strlen — Returns the character count of string
    • iconv_strpos — Finds position of first occurrence of a needle within a haystack
    • iconv_strrpos — Finds the last occurrence of a needle within a haystack
    • iconv_substr — Cut out part of a string
    • iconv — Convert string to requested character encoding
    • ob_iconv_handler — Convert character encoding as output buffer handler
locale_set_default
Introduction
Human Language and Character Encoding Support


ID3 Tags

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • ID3 Functions
    • id3_get_frame_long_name — Get the long name of an ID3v2 frame
    • id3_get_frame_short_name — Get the short name of an ID3v2 frame
    • id3_get_genre_id — Get the id for a genre
    • id3_get_genre_list — Get all possible genre values
    • id3_get_genre_name — Get the name for a genre id
    • id3_get_tag — Get all information stored in an ID3 tag
    • id3_get_version — Get version of an ID3 tag
    • id3_remove_tag — Remove an existing ID3 tag
    • id3_set_tag — Update information stored in an ID3 tag
Audio Formats Manipulation
Introduction
Audio Formats Manipulation


Informix

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Informix Functions
    • ifx_affected_rows — Get number of rows affected by a query
    • ifx_blobinfile_mode — Set the default blob mode for all select queries
    • ifx_byteasvarchar — Set the default byte mode
    • ifx_close — Close Informix connection
    • ifx_connect — Open Informix server connection
    • ifx_copy_blob — Duplicates the given blob object
    • ifx_create_blob — Creates an blob object
    • ifx_create_char — Creates an char object
    • ifx_do — Execute a previously prepared SQL-statement
    • ifx_error — Returns error code of last Informix call
    • ifx_errormsg — Returns error message of last Informix call
    • ifx_fetch_row — Get row as an associative array
    • ifx_fieldproperties — List of SQL fieldproperties
    • ifx_fieldtypes — List of Informix SQL fields
    • ifx_free_blob — Deletes the blob object
    • ifx_free_char — Deletes the char object
    • ifx_free_result — Releases resources for the query
    • ifx_get_blob — Return the content of a blob object
    • ifx_get_char — Return the content of the char object
    • ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query
    • ifx_htmltbl_result — Formats all rows of a query into a HTML table
    • ifx_nullformat — Sets the default return value on a fetch row
    • ifx_num_fields — Returns the number of columns in the query
    • ifx_num_rows — Count the rows already fetched from a query
    • ifx_pconnect — Open persistent Informix connection
    • ifx_prepare — Prepare an SQL-statement for execution
    • ifx_query — Send Informix query
    • ifx_textasvarchar — Set the default text mode
    • ifx_update_blob — Updates the content of the blob object
    • ifx_update_char — Updates the content of the char object
    • ifxus_close_slob — Deletes the slob object
    • ifxus_create_slob — Creates an slob object and opens it
    • ifxus_free_slob — Deletes the slob object
    • ifxus_open_slob — Opens an slob object
    • ifxus_read_slob — Reads nbytes of the slob object
    • ifxus_seek_slob — Sets the current file or seek position
    • ifxus_tell_slob — Returns the current file or seek position
    • ifxus_write_slob — Writes a string into the slob object
ibase_wait_event
Introduction
Vendor Specific Database Extensions


Image Processing and GD

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • PNG creation with PHP
    • Adding watermarks to images using alpha channels
    • Using imagecopymerge to create a translucent watermark
  • GD and Image Functions
    • gd_info — Retrieve information about the currently installed GD library
    • getimagesize — Get the size of an image
    • image_type_to_extension — Get file extension for image type
    • image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
    • image2wbmp — Output image to browser or file
    • imagealphablending — Set the blending mode for an image
    • imageantialias — Should antialias functions be used or not
    • imagearc — Draws an arc
    • imagechar — Draw a character horizontally
    • imagecharup — Draw a character vertically
    • imagecolorallocate — Allocate a color for an image
    • imagecolorallocatealpha — Allocate a color for an image
    • imagecolorat — Get the index of the color of a pixel
    • imagecolorclosest — Get the index of the closest color to the specified color
    • imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha
    • imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness
    • imagecolordeallocate — De-allocate a color for an image
    • imagecolorexact — Get the index of the specified color
    • imagecolorexactalpha — Get the index of the specified color + alpha
    • imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version
    • imagecolorresolve — Get the index of the specified color or its closest possible alternative
    • imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative
    • imagecolorset — Set the color for the specified palette index
    • imagecolorsforindex — Get the colors for an index
    • imagecolorstotal — Find out the number of colors in an image's palette
    • imagecolortransparent — Define a color as transparent
    • imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset
    • imagecopy — Copy part of an image
    • imagecopymerge — Copy and merge part of an image
    • imagecopymergegray — Copy and merge part of an image with gray scale
    • imagecopyresampled — Copy and resize part of an image with resampling
    • imagecopyresized — Copy and resize part of an image
    • imagecreate — Create a new palette based image
    • imagecreatefromgd2 — Create a new image from GD2 file or URL
    • imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL
    • imagecreatefromgd — Create a new image from GD file or URL
    • imagecreatefromgif — Create a new image from file or URL
    • imagecreatefromjpeg — Create a new image from file or URL
    • imagecreatefrompng — Create a new image from file or URL
    • imagecreatefromstring — Create a new image from the image stream in the string
    • imagecreatefromwbmp — Create a new image from file or URL
    • imagecreatefromxbm — Create a new image from file or URL
    • imagecreatefromxpm — Create a new image from file or URL
    • imagecreatetruecolor — Create a new true color image
    • imagedashedline — Draw a dashed line
    • imagedestroy — Destroy an image
    • imageellipse — Draw an ellipse
    • imagefill — Flood fill
    • imagefilledarc — Draw a partial arc and fill it
    • imagefilledellipse — Draw a filled ellipse
    • imagefilledpolygon — Draw a filled polygon
    • imagefilledrectangle — Draw a filled rectangle
    • imagefilltoborder — Flood fill to specific color
    • imagefilter — Applies a filter to an image
    • imagefontheight — Get font height
    • imagefontwidth — Get font width
    • imageftbbox — Give the bounding box of a text using fonts via freetype2
    • imagefttext — Write text to the image using fonts using FreeType 2
    • imagegammacorrect — Apply a gamma correction to a GD image
    • imagegd2 — Output GD2 image to browser or file
    • imagegd — Output GD image to browser or file
    • imagegif — Output image to browser or file
    • imagegrabscreen — Captures the whole screen
    • imagegrabwindow — Captures a window
    • imageinterlace — Enable or disable interlace
    • imageistruecolor — Finds whether an image is a truecolor image
    • imagejpeg — Output image to browser or file
    • imagelayereffect — Set the alpha blending flag to use the bundled libgd layering effects
    • imageline — Draw a line
    • imageloadfont — Load a new font
    • imagepalettecopy — Copy the palette from one image to another
    • imagepng — Output a PNG image to either the browser or a file
    • imagepolygon — Draws a polygon
    • imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts
    • imagepsencodefont — Change the character encoding vector of a font
    • imagepsextendfont — Extend or condense a font
    • imagepsfreefont — Free memory used by a PostScript Type 1 font
    • imagepsloadfont — Load a PostScript Type 1 font from file
    • imagepsslantfont — Slant a font
    • imagepstext — Draws a text over an image using PostScript Type1 fonts
    • imagerectangle — Draw a rectangle
    • imagerotate — Rotate an image with a given angle
    • imagesavealpha — Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images
    • imagesetbrush — Set the brush image for line drawing
    • imagesetpixel — Set a single pixel
    • imagesetstyle — Set the style for line drawing
    • imagesetthickness — Set the thickness for line drawing
    • imagesettile — Set the tile image for filling
    • imagestring — Draw a string horizontally
    • imagestringup — Draw a string vertically
    • imagesx — Get image width
    • imagesy — Get image height
    • imagetruecolortopalette — Convert a true color image to a palette image
    • imagettfbbox — Give the bounding box of a text using TrueType fonts
    • imagettftext — Write text to the image using TrueType fonts
    • imagetypes — Return the image types supported by this PHP build
    • imagewbmp — Output image to browser or file
    • imagexbm — Output XBM image to browser or file
    • iptcembed — Embeds binary IPTC data into a JPEG image
    • iptcparse — Parse a binary IPTC block into single tags.
    • jpeg2wbmp — Convert JPEG image file to WBMP image file
    • png2wbmp — Convert PNG image file to WBMP image file
read_exif_data
Introduction
Image Processing and Generation


Image Processing (ImageMagick)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Examples
  • The Imagick class
    • Imagick::adaptiveBlurImage — Adds adaptive blur filter to image
    • Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation
    • Imagick::adaptiveSharpenImage — Adaptively sharpen the image
    • Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity
    • Imagick::addImage — Adds new image to Imagick object image list
    • Imagick::addNoiseImage — Adds random noise to the image
    • Imagick::affineTransformImage — Transforms an image
    • Imagick::animateImages — Animates an image or images
    • Imagick::annotateImage — Annotates an image with text
    • Imagick::appendImages — Append a set of images
    • Imagick::averageImages — Average a set of images
    • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
    • Imagick::blurImage — Adds blur filter to image
    • Imagick::borderImage — Surrounds the image with a border
    • Imagick::charcoalImage — Simulates a charcoal drawing
    • Imagick::chopImage — Removes a region of an image and trims
    • Imagick::clear — Clears all resources associated to Imagick object
    • Imagick::clipImage — Clips along the first path from the 8BIM profile
    • Imagick::clipPathImage — Clips along the named paths from the 8BIM profile
    • Imagick::clone — Makes an exact copy of the Imagick object
    • Imagick::clutImage — Replaces colors in the image
    • Imagick::coalesceImages — Composites a set of images
    • Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target
    • Imagick::colorizeImage — Blends the fill color with the image
    • Imagick::combineImages — Combines one or more images into a single image
    • Imagick::commentImage — Adds a comment to your image
    • Imagick::compareImageChannels — Returns the difference in one or more images
    • Imagick::compareImageLayers — Returns the maximum bounding region between images
    • Imagick::compareImages — Compares an image to a reconstructed image
    • Imagick::compositeImage — Composite one image onto another
    • Imagick::__construct — The Imagick constructor
    • Imagick::contrastImage — Change the contrast of the image
    • Imagick::contrastStretchImage — Enhances the contrast of a color image
    • Imagick::convolveImage — Applies a custom convolution kernel to the image
    • Imagick::cropImage — Extracts a region of the image
    • Imagick::cropThumbnailImage — Creates a crop thumbnail
    • Imagick::current — Returns a reference to the current Imagick object
    • Imagick::cycleColormapImage — Displaces an image's colormap
    • Imagick::decipherImage — Deciphers an image
    • Imagick::deconstructImages — Returns certain pixel differences between images
    • Imagick::deskewImage — Removes skew from the image
    • Imagick::despeckleImage — Reduces the speckle noise in an image
    • Imagick::destroy — Destroys the Imagick object
    • Imagick::displayImage — Displays an image
    • Imagick::displayImages — Displays an image or image sequence
    • Imagick::distortImage — Distorts an image using various distortion methods
    • Imagick::drawImage — Renders the ImagickDraw object on the current image
    • Imagick::edgeImage — Enhance edges within the image
    • Imagick::embossImage — Returns a grayscale image with a three-dimensional effect
    • Imagick::encipherImage — Enciphers an image
    • Imagick::enhanceImage — Improves the quality of a noisy image
    • Imagick::equalizeImage — Equalizes the image histogram
    • Imagick::evaluateImage — Applies an expression to an image
    • Imagick::exportImagePixels — Exports raw image pixels
    • Imagick::extentImage — Set image size
    • Imagick::flattenImages — Merges a sequence of images
    • Imagick::flipImage — Creates a vertical mirror image
    • Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target
    • Imagick::flopImage — Creates a horizontal mirror image
    • Imagick::frameImage — Adds a simulated three-dimensional border
    • Imagick::functionImage — Applies a function on the image
    • Imagick::fxImage — Evaluate expression for each pixel in the image
    • Imagick::gammaImage — Gamma-corrects an image
    • Imagick::gaussianBlurImage — Blurs an image
    • Imagick::getCompression — Gets the object compression type
    • Imagick::getCompressionQuality — Gets the object compression quality
    • Imagick::getCopyright — Returns the ImageMagick API copyright as a string
    • Imagick::getFilename — The filename associated with an image sequence
    • Imagick::getFont — Gets font
    • Imagick::getFormat — Returns the format of the Imagick object
    • Imagick::getGravity — Gets the gravity
    • Imagick::getHomeURL — Returns the ImageMagick home URL
    • Imagick::getImage — Returns a new Imagick object
    • Imagick::getImageAlphaChannel — Gets the image alpha channel
    • Imagick::getImageBackgroundColor — Returns the image background color
    • Imagick::getImageBlob — Returns the image sequence as a blob
    • Imagick::getImageBluePrimary — Returns the chromaticy blue primary point
    • Imagick::getImageBorderColor — Returns the image border color
    • Imagick::getImageChannelDepth — Gets the depth for a particular image channel
    • Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image
    • Imagick::getImageChannelDistortions — Gets channel distortions
    • Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
    • Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose
    • Imagick::getImageChannelMean — Gets the mean and standard deviation
    • Imagick::getImageChannelRange — Gets channel range
    • Imagick::getImageChannelStatistics — Returns statistics for each channel in the image
    • Imagick::getImageClipMask — Gets image clip mask
    • Imagick::getImageColormapColor — Returns the color of the specified colormap index
    • Imagick::getImageColors — Gets the number of unique colors in the image
    • Imagick::getImageColorspace — Gets the image colorspace
    • Imagick::getImageCompose — Returns the composite operator associated with the image
    • Imagick::getImageCompression — Gets the current image's compression type
    • Imagick::getImageCompressionQuality — Gets the current image's compression quality
    • Imagick::getImageDelay — Gets the image delay
    • Imagick::getImageDepth — Gets the image depth
    • Imagick::getImageDispose — Gets the image disposal method
    • Imagick::getImageDistortion — Compares an image to a reconstructed image
    • Imagick::getImageExtrema — Gets the extrema for the image
    • Imagick::getImageFilename — Returns the filename of a particular image in a sequence
    • Imagick::getImageFormat — Returns the format of a particular image in a sequence
    • Imagick::getImageGamma — Gets the image gamma
    • Imagick::getImageGeometry — Gets the width and height as an associative array
    • Imagick::getImageGravity — Gets the image gravity
    • Imagick::getImageGreenPrimary — Returns the chromaticy green primary point
    • Imagick::getImageHeight — Returns the image height
    • Imagick::getImageHistogram — Gets the image histogram
    • Imagick::getImageIndex — Gets the index of the current active image
    • Imagick::getImageInterlaceScheme — Gets the image interlace scheme
    • Imagick::getImageInterpolateMethod — Returns the interpolation method
    • Imagick::getImageIterations — Gets the image iterations
    • Imagick::getImageLength — Returns the image length in bytes
    • Imagick::getImageMagickLicense — Returns a string containing the ImageMagick license
    • Imagick::getImageMatte — Return if the image has a matte channel
    • Imagick::getImageMatteColor — Returns the image matte color
    • Imagick::getImageOrientation — Gets the image orientation
    • Imagick::getImagePage — Returns the page geometry
    • Imagick::getImagePixelColor — Returns the color of the specified pixel
    • Imagick::getImageProfile — Returns the named image profile
    • Imagick::getImageProfiles — Returns the image profiles
    • Imagick::getImageProperties — Returns the image properties
    • Imagick::getImageProperty — Returns the named image property
    • Imagick::getImageRedPrimary — Returns the chromaticity red primary point
    • Imagick::getImageRegion — Extracts a region of the image
    • Imagick::getImageRenderingIntent — Gets the image rendering intent
    • Imagick::getImageResolution — Gets the image X and Y resolution
    • Imagick::getImagesBlob — Returns all image sequences as a blob
    • Imagick::getImageScene — Gets the image scene
    • Imagick::getImageSignature — Generates an SHA-256 message digest
    • Imagick::getImageSize — Returns the image length in bytes
    • Imagick::getImageTicksPerSecond — Gets the image ticks-per-second
    • Imagick::getImageTotalInkDensity — Gets the image total ink density
    • Imagick::getImageType — Gets the potential image type
    • Imagick::getImageUnits — Gets the image units of resolution
    • Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method
    • Imagick::getImageWhitePoint — Returns the chromaticity white point
    • Imagick::getImageWidth — Returns the image width
    • Imagick::getInterlaceScheme — Gets the object interlace scheme
    • Imagick::getIteratorIndex — Gets the index of the current active image
    • Imagick::getNumberImages — Returns the number of images in the object
    • Imagick::getOption — Returns a value associated with the specified key
    • Imagick::getPackageName — Returns the ImageMagick package name
    • Imagick::getPage — Returns the page geometry
    • Imagick::getPixelIterator — Returns a MagickPixelIterator
    • Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section
    • Imagick::getPointSize — Gets point size
    • Imagick::getQuantumDepth — Gets the quantum depth
    • Imagick::getQuantumRange — Returns the Imagick quantum range
    • Imagick::getReleaseDate — Returns the ImageMagick release date
    • Imagick::getResource — Returns the specified resource's memory usage
    • Imagick::getResourceLimit — Returns the specified resource limit
    • Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor
    • Imagick::getSize — Returns the size associated with the Imagick object
    • Imagick::getSizeOffset — Returns the size offset
    • Imagick::getVersion — Returns the ImageMagick API version
    • Imagick::haldClutImage — Replaces colors in the image
    • Imagick::hasNextImage — Checks if the object has more images
    • Imagick::hasPreviousImage — Checks if the object has a previous image
    • Imagick::identifyImage — Identifies an image and fetches attributes
    • Imagick::implodeImage — Creates a new image as a copy
    • Imagick::importImagePixels — Imports image pixels
    • Imagick::labelImage — Adds a label to an image
    • Imagick::levelImage — Adjusts the levels of an image
    • Imagick::linearStretchImage — Stretches with saturation the image intensity
    • Imagick::liquidRescaleImage — Animates an image or images
    • Imagick::magnifyImage — Scales an image proportionally 2x
    • Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image.
    • Imagick::matteFloodfillImage — Changes the transparency value of a color
    • Imagick::medianFilterImage — Applies a digital filter
    • Imagick::mergeImageLayers — Merges image layers
    • Imagick::minifyImage — Scales an image proportionally to half its size
    • Imagick::modulateImage — Control the brightness, saturation, and hue
    • Imagick::montageImage — Creates a composite image
    • Imagick::morphImages — Method morphs a set of images
    • Imagick::mosaicImages — Forms a mosaic from images
    • Imagick::motionBlurImage — Simulates motion blur
    • Imagick::negateImage — Negates the colors in the reference image
    • Imagick::newImage — Creates a new image
    • Imagick::newPseudoImage — Creates a new image
    • Imagick::nextImage — Moves to the next image
    • Imagick::normalizeImage — Enhances the contrast of a color image
    • Imagick::oilPaintImage — Simulates an oil painting
    • Imagick::opaquePaintImage — Changes the color value of any pixel that matches target
    • Imagick::optimizeImageLayers — Removes repeated portions of images to optimize
    • Imagick::orderedPosterizeImage — Performs an ordered dither
    • Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target
    • Imagick::paintOpaqueImage — Change any pixel that matches color
    • Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill
    • Imagick::pingImage — Fetch basic attributes about the image
    • Imagick::pingImageBlob — Quickly fetch attributes
    • Imagick::pingImageFile — Get basic image attributes in a lightweight manner
    • Imagick::polaroidImage — Simulates a Polaroid picture
    • Imagick::posterizeImage — Reduces the image to a limited number of color level
    • Imagick::previewImages — Quickly pin-point appropriate parameters for image processing
    • Imagick::previousImage — Move to the previous image in the object
    • Imagick::profileImage — Adds or removes a profile from an image
    • Imagick::quantizeImage — Analyzes the colors within a reference image
    • Imagick::quantizeImages — Analyzes the colors within a sequence of images
    • Imagick::queryFontMetrics — Returns an array representing the font metrics
    • Imagick::queryFonts — Returns the configured fonts
    • Imagick::queryFormats — Returns formats supported by Imagick
    • Imagick::radialBlurImage — Radial blurs an image
    • Imagick::raiseImage — Creates a simulated 3d button-like effect
    • Imagick::randomThresholdImage — Creates a high-contrast, two-color image
    • Imagick::readImage — Reads image from filename
    • Imagick::readImageBlob — Reads image from a binary string
    • Imagick::readImageFile — Reads image from open filehandle
    • Imagick::recolorImage — Recolors image
    • Imagick::reduceNoiseImage — Smooths the contours of an image
    • Imagick::remapImage — Remaps image colors
    • Imagick::removeImage — Removes an image from the image list
    • Imagick::removeImageProfile — Removes the named image profile and returns it
    • Imagick::render — Renders all preceding drawing commands
    • Imagick::resampleImage — Resample image to desired resolution
    • Imagick::resetImagePage — Reset image page
    • Imagick::resizeImage — Scales an image
    • Imagick::rollImage — Offsets an image
    • Imagick::rotateImage — Rotates an image
    • Imagick::roundCorners — Rounds image corners
    • Imagick::sampleImage — Scales an image with pixel sampling
    • Imagick::scaleImage — Scales the size of an image
    • Imagick::segmentImage — Segments an image
    • Imagick::separateImageChannel — Separates a channel from the image
    • Imagick::sepiaToneImage — Sepia tones an image
    • Imagick::setBackgroundColor — Sets the object's default background color
    • Imagick::setCompression — Sets the object's default compression type
    • Imagick::setCompressionQuality — Sets the object's default compression quality
    • Imagick::setFilename — Sets the filename before you read or write the image
    • Imagick::setFirstIterator — Sets the Imagick iterator to the first image
    • Imagick::setFont — Sets font
    • Imagick::setFormat — Sets the format of the Imagick object
    • Imagick::setGravity — Sets the gravity
    • Imagick::setImage — Replaces image in the object
    • Imagick::setImageAlphaChannel — Sets image alpha channel
    • Imagick::setImageBackgroundColor — Sets the image background color
    • Imagick::setImageBias — Sets the image bias for any method that convolves an image
    • Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point
    • Imagick::setImageBorderColor — Sets the image border color
    • Imagick::setImageChannelDepth — Sets the depth of a particular image channel
    • Imagick::setImageClipMask — Sets image clip mask
    • Imagick::setImageColormapColor — Sets the color of the specified colormap index
    • Imagick::setImageColorspace — Sets the image colorspace
    • Imagick::setImageCompose — Sets the image composite operator
    • Imagick::setImageCompression — Sets the image compression
    • Imagick::setImageCompressionQuality — Sets the image compression quality
    • Imagick::setImageDelay — Sets the image delay
    • Imagick::setImageDepth — Sets the image depth
    • Imagick::setImageDispose — Sets the image disposal method
    • Imagick::setImageExtent — Sets the image size
    • Imagick::setImageFilename — Sets the filename of a particular image
    • Imagick::setImageFormat — Sets the format of a particular image
    • Imagick::setImageGamma — Sets the image gamma
    • Imagick::setImageGravity — Sets the image gravity
    • Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point
    • Imagick::setImageIndex — Set the iterator position
    • Imagick::setImageInterlaceScheme — Sets the image compression
    • Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method
    • Imagick::setImageIterations — Sets the image iterations
    • Imagick::setImageMatte — Sets the image matte channel
    • Imagick::setImageMatteColor — Sets the image matte color
    • Imagick::setImageOpacity — Sets the image opacity level
    • Imagick::setImageOrientation — Sets the image orientation
    • Imagick::setImagePage — Sets the page geometry of the image
    • Imagick::setImageProfile — Adds a named profile to the Imagick object
    • Imagick::setImageProperty — Sets an image property
    • Imagick::setImageRedPrimary — Sets the image chromaticity red primary point
    • Imagick::setImageRenderingIntent — Sets the image rendering intent
    • Imagick::setImageResolution — Sets the image resolution
    • Imagick::setImageScene — Sets the image scene
    • Imagick::setImageTicksPerSecond — Sets the image ticks-per-second
    • Imagick::setImageType — Sets the image type
    • Imagick::setImageUnits — Sets the image units of resolution
    • Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method
    • Imagick::setImageWhitePoint — Sets the image chromaticity white point
    • Imagick::setInterlaceScheme — Sets the image compression
    • Imagick::setIteratorIndex — Set the iterator position
    • Imagick::setLastIterator — Sets the Imagick iterator to the last image
    • Imagick::setOption — Set an option
    • Imagick::setPage — Sets the page geometry of the Imagick object
    • Imagick::setPointSize — Sets point size
    • Imagick::setResolution — Sets the image resolution
    • Imagick::setResourceLimit — Sets the limit for a particular resource in megabytes
    • Imagick::setSamplingFactors — Sets the image sampling factors
    • Imagick::setSize — Sets the size of the Imagick object
    • Imagick::setSizeOffset — Sets the size and offset of the Imagick object
    • Imagick::setType — Sets the image type attribute
    • Imagick::shadeImage — Creates a 3D effect
    • Imagick::shadowImage — Simulates an image shadow
    • Imagick::sharpenImage — Sharpens an image
    • Imagick::shaveImage — Shaves pixels from the image edges
    • Imagick::shearImage — Creating a parallelogram
    • Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
    • Imagick::sketchImage — Simulates a pencil sketch
    • Imagick::solarizeImage — Applies a solarizing effect to the image
    • Imagick::sparseColorImage — Interpolates colors
    • Imagick::spliceImage — Splices a solid color into the image
    • Imagick::spreadImage — Randomly displaces each pixel in a block
    • Imagick::steganoImage — Hides a digital watermark within the image
    • Imagick::stereoImage — Composites two images
    • Imagick::stripImage — Strips an image of all profiles and comments
    • Imagick::swirlImage — Swirls the pixels about the center of the image
    • Imagick::textureImage — Repeatedly tiles the texture image
    • Imagick::thresholdImage — Changes the value of individual pixels based on a threshold
    • Imagick::thumbnailImage — Changes the size of an image
    • Imagick::tintImage — Applies a color vector to each pixel in the image
    • Imagick::transformImage — Convenience method for setting crop size and the image geometry
    • Imagick::transparentPaintImage — Paints pixels transparent
    • Imagick::transposeImage — Creates a vertical mirror image
    • Imagick::transverseImage — Creates a horizontal mirror image
    • Imagick::trimImage — Remove edges from the image
    • Imagick::uniqueImageColors — Discards all but one of any pixel color
    • Imagick::unsharpMaskImage — Sharpens an image
    • Imagick::valid — Checks if the current item is valid
    • Imagick::vignetteImage — Adds vignette filter to the image
    • Imagick::waveImage — Applies wave filter to the image
    • Imagick::whiteThresholdImage — Force all pixels above the threshold into white
    • Imagick::writeImage — Writes an image to the specified filename
    • Imagick::writeImageFile — Writes an image to a filehandle
    • Imagick::writeImages — Writes an image or image sequence
    • Imagick::writeImagesFile — Writes frames to a filehandle
  • The ImagickDraw class
    • ImagickDraw::affine — Adjusts the current affine transformation matrix
    • ImagickDraw::annotation — Draws text on the image
    • ImagickDraw::arc — Draws an arc
    • ImagickDraw::bezier — Draws a bezier curve
    • ImagickDraw::circle — Draws a circle
    • ImagickDraw::clear — Clears the ImagickDraw
    • ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object
    • ImagickDraw::color — Draws color on image
    • ImagickDraw::comment — Adds a comment
    • ImagickDraw::composite — Composites an image onto the current image
    • ImagickDraw::__construct — The ImagickDraw constructor
    • ImagickDraw::destroy — Frees all associated resources
    • ImagickDraw::ellipse — Draws an ellipse on the image
    • ImagickDraw::getClipPath — Obtains the current clipping path ID
    • ImagickDraw::getClipRule — Returns the current polygon fill rule
    • ImagickDraw::getClipUnits — Returns the interpretation of clip path units
    • ImagickDraw::getFillColor — Returns the fill color
    • ImagickDraw::getFillOpacity — Returns the opacity used when drawing
    • ImagickDraw::getFillRule — Returns the fill rule
    • ImagickDraw::getFont — Returns the font
    • ImagickDraw::getFontFamily — Returns the font family
    • ImagickDraw::getFontSize — Returns the font pointsize
    • ImagickDraw::getFontStyle — Returns the font style
    • ImagickDraw::getFontWeight — Returns the font weight
    • ImagickDraw::getGravity — Returns the text placement gravity
    • ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting
    • ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines
    • ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash
    • ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit
    • ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines
    • ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines
    • ImagickDraw::getTextAlignment — Returns the text alignment
    • ImagickDraw::getTextAntialias — Returns the current text antialias setting
    • ImagickDraw::getTextDecoration — Returns the text decoration
    • ImagickDraw::getTextEncoding — Returns the code set used for text annotations
    • ImagickDraw::getTextUnderColor — Returns the text under color
    • ImagickDraw::getVectorGraphics — Returns a string containing vector graphics
    • ImagickDraw::line — Draws a line
    • ImagickDraw::matte — Paints on the image's opacity channel
    • ImagickDraw::pathClose — Adds a path element to the current path
    • ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve
    • ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc
    • ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc
    • ImagickDraw::pathFinish — Terminates the current path
    • ImagickDraw::pathLineToAbsolute — Draws a line path
    • ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path
    • ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line
    • ImagickDraw::pathLineToRelative — Draws a line path
    • ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line
    • ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path
    • ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
    • ImagickDraw::pathMoveToRelative — Starts a new sub-path
    • ImagickDraw::pathStart — Declares the start of a path drawing list
    • ImagickDraw::point — Draws a point
    • ImagickDraw::polygon — Draws a polygon
    • ImagickDraw::polyline — Draws a polyline
    • ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
    • ImagickDraw::popClipPath — Terminates a clip path definition
    • ImagickDraw::popDefs — Terminates a definition list
    • ImagickDraw::popPattern — Terminates a pattern definition
    • ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack
    • ImagickDraw::pushClipPath — Starts a clip path definition
    • ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing
    • ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
    • ImagickDraw::rectangle — Draws a rectangle
    • ImagickDraw::render — Renders all preceding drawing commands onto the image
    • ImagickDraw::rotate — Applies the specified rotation to the current coordinate space
    • ImagickDraw::roundRectangle — Draws a rounded rectangle
    • ImagickDraw::scale — Adjusts the scaling factor
    • ImagickDraw::setClipPath — Associates a named clipping path with the image
    • ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path
    • ImagickDraw::setClipUnits — Sets the interpretation of clip path units
    • ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects
    • ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
    • ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons
    • ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text
    • ImagickDraw::setFontFamily — Sets the font family to use when annotating with text
    • ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text
    • ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text
    • ImagickDraw::setFontStyle — Sets the font style to use when annotating with text
    • ImagickDraw::setFontWeight — Sets the font weight
    • ImagickDraw::setGravity — Sets the text placement gravity
    • ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased
    • ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines
    • ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
    • ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::setStrokeMiterLimit — Specifies the miter limit
    • ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines
    • ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines
    • ImagickDraw::setTextAlignment — Specifies a text alignment
    • ImagickDraw::setTextAntialias — Controls whether text is antialiased
    • ImagickDraw::setTextDecoration — Specifies a decoration
    • ImagickDraw::setTextEncoding — Specifies specifies the text code set
    • ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle
    • ImagickDraw::setVectorGraphics — Sets the vector graphics
    • ImagickDraw::setViewbox — Sets the overall canvas size
    • ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction
    • ImagickDraw::skewY — Skews the current coordinate system in the vertical direction
    • ImagickDraw::translate — Applies a translation to the current coordinate system
  • The ImagickPixel class
    • ImagickPixel::clear — Clears resources associated with this object
    • ImagickPixel::__construct — The ImagickPixel constructor
    • ImagickPixel::destroy — Deallocates resources associated with this object
    • ImagickPixel::getColor — Returns the color
    • ImagickPixel::getColorAsString — Returns the color as a string
    • ImagickPixel::getColorCount — Returns the color count associated with this color
    • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
    • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::isSimilar — Check the distance between this color and another
    • ImagickPixel::setColor — Sets the color
    • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
    • ImagickPixel::setHSL — Sets the normalized HSL color
  • The ImagickPixelIterator class
    • ImagickPixelIterator::clear — Clear resources associated with a PixelIterator
    • ImagickPixelIterator::__construct — The ImagickPixelIterator constructor
    • ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects
    • ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row
    • ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator
    • ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row
    • ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator
    • ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator
    • ImagickPixelIterator::resetIterator — Resets the pixel iterator
    • ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row
    • ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row
    • ImagickPixelIterator::setIteratorRow — Set the pixel iterator row
    • ImagickPixelIterator::syncIterator — Syncs the pixel iterator
png2wbmp
Introduction
Image Processing and Generation


IMAP, POP3 and NNTP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • IMAP Functions
    • imap_8bit — Convert an 8bit string to a quoted-printable string
    • imap_alerts — Returns all IMAP alert messages that have occurred
    • imap_append — Append a string message to a specified mailbox
    • imap_base64 — Decode BASE64 encoded text
    • imap_binary — Convert an 8bit string to a base64 string
    • imap_body — Read the message body
    • imap_bodystruct — Read the structure of a specified body section of a specific message
    • imap_check — Check current mailbox
    • imap_clearflag_full — Clears flags on messages
    • imap_close — Close an IMAP stream
    • imap_createmailbox — Create a new mailbox
    • imap_delete — Mark a message for deletion from current mailbox
    • imap_deletemailbox — Delete a mailbox
    • imap_errors — Returns all of the IMAP errors that have occured
    • imap_expunge — Delete all messages marked for deletion
    • imap_fetch_overview — Read an overview of the information in the headers of the given message
    • imap_fetchbody — Fetch a particular section of the body of the message
    • imap_fetchheader — Returns header for a message
    • imap_fetchstructure — Read the structure of a particular message
    • imap_gc — Clears IMAP cache
    • imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
    • imap_get_quotaroot — Retrieve the quota settings per user
    • imap_getacl — Gets the ACL for a given mailbox
    • imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
    • imap_getsubscribed — List all the subscribed mailboxes
    • imap_header — Alias of imap_headerinfo
    • imap_headerinfo — Read the header of the message
    • imap_headers — Returns headers for all messages in a mailbox
    • imap_last_error — Gets the last IMAP error that occurred during this page request
    • imap_list — Read the list of mailboxes
    • imap_listmailbox — Alias of imap_list
    • imap_listscan — Returns the list of mailboxes that matches the given text
    • imap_listsubscribed — Alias of imap_lsub
    • imap_lsub — List all the subscribed mailboxes
    • imap_mail_compose — Create a MIME message based on given envelope and body sections
    • imap_mail_copy — Copy specified messages to a mailbox
    • imap_mail_move — Move specified messages to a mailbox
    • imap_mail — Send an email message
    • imap_mailboxmsginfo — Get information about the current mailbox
    • imap_mime_header_decode — Decode MIME header elements
    • imap_msgno — Gets the message sequence number for the given UID
    • imap_num_msg — Gets the number of messages in the current mailbox
    • imap_num_recent — Gets the number of recent messages in current mailbox
    • imap_open — Open an IMAP stream to a mailbox
    • imap_ping — Check if the IMAP stream is still active
    • imap_qprint — Convert a quoted-printable string to an 8 bit string
    • imap_renamemailbox — Rename an old mailbox to new mailbox
    • imap_reopen — Reopen IMAP stream to new mailbox
    • imap_rfc822_parse_adrlist — Parses an address string
    • imap_rfc822_parse_headers — Parse mail headers from a string
    • imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info
    • imap_savebody — Save a specific body section to a file
    • imap_scanmailbox — Alias of imap_listscan
    • imap_search — This function returns an array of messages matching the given search criteria
    • imap_set_quota — Sets a quota for a given mailbox
    • imap_setacl — Sets the ACL for a giving mailbox
    • imap_setflag_full — Sets flags on messages
    • imap_sort — Gets and sort messages
    • imap_status — Returns status information on a mailbox
    • imap_subscribe — Subscribe to a mailbox
    • imap_thread — Returns a tree of threaded message
    • imap_timeout — Set or fetch imap timeout
    • imap_uid — This function returns the UID for the given message sequence number
    • imap_undelete — Unmark the message which is marked deleted
    • imap_unsubscribe — Unsubscribe from a mailbox
    • imap_utf7_decode — Decodes a modified UTF-7 encoded string
    • imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text
    • imap_utf8 — Converts MIME-encoded text to UTF-8
cyrus_unbind
Introduction
Mail Related Extensions


Inclusion hierarchy viewer

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Example that implements inclued into an application
  • inclued Functions
    • inclued_get_data — Get the inclued data
Resource Types
Introduction
Affecting PHP's Behaviour


PHP Options and Information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • PHP Options/Info Functions
    • assert_options — Set/get the various assert flags
    • assert — Checks if assertion is FALSE
    • dl — Loads a PHP extension at runtime
    • extension_loaded — Find out whether an extension is loaded
    • gc_collect_cycles — Forces collection of any existing garbage cycles
    • gc_disable — Deactivates the circular reference collector
    • gc_enable — Activates the circular reference collector
    • gc_enabled — Returns status of the circular reference collector
    • get_cfg_var — Gets the value of a PHP configuration option
    • get_current_user — Gets the name of the owner of the current PHP script
    • get_defined_constants — Returns an associative array with the names of all the constants and their values
    • get_extension_funcs — Returns an array with the names of the functions of a module
    • get_include_path — Gets the current include_path configuration option
    • get_included_files — Returns an array with the names of included or required files
    • get_loaded_extensions — Returns an array with the names of all modules compiled and loaded
    • get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc
    • get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime
    • get_required_files — Alias of get_included_files
    • getenv — Gets the value of an environment variable
    • getlastmod — Gets time of last page modification
    • getmygid — Get PHP script owner's GID
    • getmyinode — Gets the inode of the current script
    • getmypid — Gets PHP's process ID
    • getmyuid — Gets PHP script owner's UID
    • getopt — Gets options from the command line argument list
    • getrusage — Gets the current resource usages
    • ini_alter — Alias of ini_set
    • ini_get_all — Gets all configuration options
    • ini_get — Gets the value of a configuration option
    • ini_restore — Restores the value of a configuration option
    • ini_set — Sets the value of a configuration option
    • magic_quotes_runtime — Alias of set_magic_quotes_runtime
    • main — Dummy for main
    • memory_get_peak_usage — Returns the peak of memory allocated by PHP
    • memory_get_usage — Returns the amount of memory allocated to PHP
    • php_ini_loaded_file — Retrieve a path to the loaded php.ini file
    • php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir
    • php_logo_guid — Gets the logo guid
    • php_sapi_name — Returns the type of interface between web server and PHP
    • php_uname — Returns information about the operating system PHP is running on
    • phpcredits — Prints out the credits for PHP
    • phpinfo — Outputs lots of PHP information
    • phpversion — Gets the current PHP version
    • putenv — Sets the value of an environment variable
    • restore_include_path — Restores the value of the include_path configuration option
    • set_include_path — Sets the include_path configuration option
    • set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime
    • set_time_limit — Limits the maximum execution time
    • sys_get_temp_dir — Returns directory path used for temporary files
    • version_compare — Compares two "PHP-standardized" version number strings
    • zend_logo_guid — Gets the Zend guid
    • zend_thread_id — Returns a unique identifier for the current thread
    • zend_version — Gets the version of the current Zend engine
inclued_get_data
Introduction
Affecting PHP's Behaviour


Ingres DBMS, EDBC, and Enterprise Access Gateways

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Simple Ingres Example
  • Ingres Functions
    • ingres_autocommit_state — Test if the connection is using autocommit
    • ingres_autocommit — Switch autocommit on or off
    • ingres_charset — Returns the installation character set
    • ingres_close — Close an Ingres database connection
    • ingres_commit — Commit a transaction
    • ingres_connect — Open a connection to an Ingres database
    • ingres_cursor — Get a cursor name for a given result resource
    • ingres_errno — Get the last Ingres error number generated
    • ingres_error — Get a meaningful error message for the last error generated
    • ingres_errsqlstate — Get the last SQLSTATE error code generated
    • ingres_escape_string — Escape special characters for use in a query
    • ingres_execute — Execute a prepared query
    • ingres_fetch_array — Fetch a row of result into an array
    • ingres_fetch_assoc — Fetch a row of result into an associative array
    • ingres_fetch_object — Fetch a row of result into an object
    • ingres_fetch_proc_return — Get the return value from a procedure call
    • ingres_fetch_row — Fetch a row of result into an enumerated array
    • ingres_field_length — Get the length of a field
    • ingres_field_name — Get the name of a field in a query result
    • ingres_field_nullable — Test if a field is nullable
    • ingres_field_precision — Get the precision of a field
    • ingres_field_scale — Get the scale of a field
    • ingres_field_type — Get the type of a field in a query result
    • ingres_free_result — Free the resources associated with a result identifier
    • ingres_next_error — Get the next Ingres error
    • ingres_num_fields — Get the number of fields returned by the last query
    • ingres_num_rows — Get the number of rows affected or returned by a query
    • ingres_pconnect — Open a persistent connection to an Ingres database
    • ingres_prepare — Prepare a query for later execution
    • ingres_query — Send an SQL query to Ingres
    • ingres_result_seek — Set the row position before fetching data
    • ingres_rollback — Roll back a transaction
    • ingres_set_environment — Set environment features controlling output options
    • ingres_unbuffered_query — Send an unbuffered SQL query to Ingres
db2_tables
Introduction
Vendor Specific Database Extensions


Inotify

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installing/Configuring
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Inotify Functions
    • inotify_add_watch — Add a watch to an initialized inotify instance
    • inotify_init — Initialize an inotify instance
    • inotify_queue_len — Return a number upper than zero if there are pending events
    • inotify_read — Read events from an inotify instance
    • inotify_rm_watch — Remove an existing watch from an inotify instance
unlink
Introduction
File System Related Extensions


Internationalization Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage of this extension
  • Collator — The Collator class
    • Collator::asort — Sort array maintaining index association
    • Collator::compare — Compare two Unicode strings
    • Collator::__construct — Create a collator
    • Collator::create — Create a collator
    • Collator::getAttribute — Get collation attribute value
    • Collator::getErrorCode — Get collator's last error code
    • Collator::getErrorMessage — Get text for collator's last error code
    • Collator::getLocale — Get the locale name of the collator
    • Collator::getSortKey — Get sorting key for a string
    • Collator::getStrength — Get current collation strength
    • Collator::setAttribute — Set collation attribute
    • Collator::setStrength — Set collation strength
    • Collator::sortWithSortKeys — Sort array using specified collator and sort keys
    • Collator::sort — Sort array using specified collator
  • NumberFormatter — The NumberFormatter class
    • NumberFormatter::create — Create a number formatter
    • NumberFormatter::formatCurrency — Format a currency value
    • NumberFormatter::format — Format a number
    • NumberFormatter::getAttribute — Get an attribute
    • NumberFormatter::getErrorCode — Get formatter's last error code.
    • NumberFormatter::getErrorMessage — Get formatter's last error message.
    • NumberFormatter::getLocale — Get formatter locale
    • NumberFormatter::getPattern — Get formatter pattern
    • NumberFormatter::getSymbol — Get a symbol value
    • NumberFormatter::getTextAttribute — Get a text attribute
    • NumberFormatter::parseCurrency — Parse a currency number
    • NumberFormatter::parse — Parse a number
    • NumberFormatter::setAttribute — Set an attribute
    • NumberFormatter::setPattern — Set formatter pattern
    • NumberFormatter::setSymbol — Set a symbol value
    • NumberFormatter::setTextAttribute — Set a text attribute
  • Locale — The Locale class
    • Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
    • Locale::composeLocale — Returns a correctly ordered and delimited locale ID
    • Locale::filterMatches — Checks if a language tag filter matches with locale
    • Locale::getAllVariants — Gets the variants for the input locale
    • Locale::getDefault — Gets the default locale value from the INTL global 'default_locale'
    • Locale::getDisplayLanguage — Returns an appropriately localized display name for language of the inputlocale
    • Locale::getDisplayName — Returns an appropriately localized display name for the input locale
    • Locale::getDisplayRegion — Returns an appropriately localized display name for region of the input locale
    • Locale::getDisplayScript — Returns an appropriately localized display name for script of the input locale
    • Locale::getDisplayVariant — Returns an appropriately localized display name for variants of the input locale
    • Locale::getKeywords — Gets the keywords for the input locale
    • Locale::getPrimaryLanguage — Gets the primary language for the input locale
    • Locale::getRegion — Gets the region for the input locale
    • Locale::getScript — Gets the script for the input locale
    • Locale::lookup — Searches the language tag list for the best match to the language
    • Locale::parseLocale — Returns a key-value array of locale ID subtag elements.
    • Locale::setDefault — sets the default runtime locale
  • Normalizer — The Normalizer class
    • Normalizer::isNormalized — Checks if the provided string is already in the specified normalization form.
    • Normalizer::normalize — Normalizes the input provided and returns the normalized string
  • MessageFormatter — The MessageFormatter class
    • MessageFormatter::create — Constructs a new Message Formatter
    • MessageFormatter::formatMessage — Quick format message
    • MessageFormatter::format — Format the message
    • MessageFormatter::getErrorCode — Get the error code from last operation
    • MessageFormatter::getErrorMessage — Get the error text from the last operation
    • MessageFormatter::getLocale — Get the locale for which the formatter was created.
    • MessageFormatter::getPattern — Get the pattern used by the formatter
    • MessageFormatter::parseMessage — Quick parse input string
    • MessageFormatter::parse — Parse input string according to pattern
    • MessageFormatter::setPattern — Set the pattern used by the formatter
  • IntlDateFormatter — The IntlDateFormatter class
    • IntlDateFormatter::create — Create a date formatter
    • IntlDateFormatter::format — Format the date/time value as a string
    • IntlDateFormatter::getCalendar — Get the calendar used for the IntlDateFormatter
    • IntlDateFormatter::getDateType — Get the datetype used for the IntlDateFormatter
    • IntlDateFormatter::getErrorCode — Get the error code from last operation
    • IntlDateFormatter::getErrorMessage — Get the error text from the last operation.
    • IntlDateFormatter::getLocale — Get the locale used by formatter
    • IntlDateFormatter::getPattern — Get the pattern used for the IntlDateFormatter
    • IntlDateFormatter::getTimeType — Get the timetype used for the IntlDateFormatter
    • IntlDateFormatter::getTimeZoneId — Get the timezone-id used for the IntlDateFormatter
    • IntlDateFormatter::isLenient — Get the lenient used for the IntlDateFormatter
    • IntlDateFormatter::localtime — Parse string to a field-based time value
    • IntlDateFormatter::parse — Parse string to a timestamp value
    • IntlDateFormatter::setCalendar — sets the calendar used to the appropriate calendar, which must be
    • IntlDateFormatter::setLenient — Set the leniency of the parser
    • IntlDateFormatter::setPattern — Set the pattern used for the IntlDateFormatter
    • IntlDateFormatter::setTimeZoneId — Sets the time zone to use
  • ResourceBundle — The ResourceBundle class
    • ResourceBundle::count — Get number of elements in the bundle
    • ResourceBundle::create — Create a resource bundle
    • ResourceBundle::getErrorCode — Get bundle's last error code.
    • ResourceBundle::getErrorMessage — Get bundle's last error message.
    • ResourceBundle::get — Get data from the bundle
    • ResourceBundle::getLocales — Get supported locales
  • Grapheme Functions
    • grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
    • grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string
    • grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
    • grapheme_strlen — Get string length in grapheme units
    • grapheme_strpos — Find position (in grapheme units) of first occurrence of a string
    • grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string
    • grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string
    • grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack.
    • grapheme_substr — Return part of a string
  • IDN Functions
    • idn_to_ascii — Convert domain name to IDNA ASCII form.
    • idn_to_unicode — Alias of idn_to_utf8
    • idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.
  • intl Functions
    • intl_error_name — Get symbolic name for a given error code
    • intl_get_error_code — Get the last error code
    • intl_get_error_message — Get description of the last error
    • intl_is_failure — Check whether the given error code indicates failure
ob_iconv_handler
Introduction
Human Language and Character Encoding Support


JavaScript Object Notation

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • JSON Functions
    • json_decode — Decodes a JSON string
    • json_encode — Returns the JSON representation of a value
    • json_last_error — Returns the last error occurred
geoip_time_zone_by_country_and_region
Introduction
Other Basic Extensions


Kerberos V

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Constants for Attribute Flags
    • Constants for Options
  • Examples
    • KADM5 extension overview example
  • KADM5 Functions
    • kadm5_chpass_principal — Changes the principal's password
    • kadm5_create_principal — Creates a kerberos principal with the given parameters
    • kadm5_delete_principal — Deletes a kerberos principal
    • kadm5_destroy — Closes the connection to the admin server and releases all related resources
    • kadm5_flush — Flush all changes to the Kerberos database
    • kadm5_get_policies — Gets all policies from the Kerberos database
    • kadm5_get_principal — Gets the principal's entries from the Kerberos database
    • kadm5_get_principals — Gets all principals from the Kerberos database
    • kadm5_init_with_password — Opens a connection to the KADM5 library
    • kadm5_modify_principal — Modifies a kerberos principal with the given parameters
Authentication Services
Introduction
Authentication Services


KTaglib

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
  • Predefined Constants
  • KTaglib_MPEG_File — The KTagLib_MPEG_File class
    • KTaglib_MPEG_File::__construct — Opens a new file
    • KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties
    • KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag
    • KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object
  • KTaglib_MPEG_AudioProperties — The KTaglib_MPEG_AudioProperties class
    • KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file
    • KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file
    • KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file
    • KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::isOriginal — Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns the length of a MPEG file
  • KTaglib_Tag — The KTaglib_Tag class
    • KTaglib_Tag::getAlbum — Returns the title string from a ID3 tag
    • KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag
    • KTaglib_Tag::getComment — Returns the comment from a ID3 tag
    • KTaglib_Tag::getGenre — Returns the genre from a ID3 tag
    • KTaglib_Tag::getTitle — Returns the title string from a ID3 tag
    • KTaglib_Tag::getTrack — Returns the track number from a ID3 tag
    • KTaglib_Tag::getYear — Returns the year from a ID3 tag
    • KTaglib_Tag::isEmpty — Returns true if the tag is empty
  • KTaglib_ID3v2_Tag — The KTagLib_ID3v2_Tag class
    • KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag
    • KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag
  • KTaglib_ID3v2_Frame — The KTagLib_ID3v2_Frame class
    • KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes
    • KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame
  • KTaglib_ID3v2_AttachedPictureFrame — The KTaglib_ID3v2_AttachedPictureFrame class
    • KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame
    • KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image
    • KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file
    • KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image
    • KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image
id3_set_tag
Introduction
Audio Formats Manipulation


Libevent

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Libevent Functions
    • event_add — Add an event to the set of monitored events
    • event_base_free — Destroy event base
    • event_base_loop — Handle events
    • event_base_loopbreak — Abort event loop
    • event_base_loopexit — Exit loop after a time
    • event_base_new — Create and initialize new event base
    • event_base_priority_init — Set the number of event priority levels
    • event_base_set — Associate event base with an event
    • event_buffer_base_set — Associate buffered event with an event base
    • event_buffer_disable — Disable a buffered event
    • event_buffer_enable — Enable a buffered event
    • event_buffer_fd_set — Change a buffered event file descriptor
    • event_buffer_free — Destroy buffered event
    • event_buffer_new — Create new buffered event
    • event_buffer_priority_set — Assign a priority to a buffered event
    • event_buffer_read — Read data from a buffered event
    • event_buffer_timeout_set — Set read and write timeouts for a buffered event
    • event_buffer_watermark_set — Set the watermarks for read and write events
    • event_buffer_write — Write data to a buffered event
    • event_del — Remove an event from the set of monitored events
    • event_free — Free event resource
    • event_new — Create new event
    • event_set — Prepare an event
expect_popen
Introduction
Process Control Extensions


LZF

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • LZF Functions
    • lzf_compress — LZF compression
    • lzf_decompress — LZF decompression
    • lzf_optimized_for — Determines what LZF extension was optimized for
bzwrite
Introduction
Compression and Archive Extensions


Mail

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mail Functions
    • ezmlm_hash — Calculate the hash value needed by EZMLM
    • mail — Send mail
imap_utf8
Introduction
Mail Related Extensions


Mailparse

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mailparse Functions
    • mailparse_determine_best_xfer_encoding — Gets the best way of encoding
    • mailparse_msg_create — Create a mime mail resource
    • mailparse_msg_extract_part_file — Extracts/decodes a message section
    • mailparse_msg_extract_part — Extracts/decodes a message section
    • mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding
    • mailparse_msg_free — Frees a MIME resource
    • mailparse_msg_get_part_data — Returns an associative array of info about the message
    • mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
    • mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
    • mailparse_msg_parse_file — Parses a file
    • mailparse_msg_parse — Incrementally parse data into buffer
    • mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses
    • mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp
    • mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file
mail
Introduction
Mail Related Extensions


Mathematical Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Math Functions
    • abs — Absolute value
    • acos — Arc cosine
    • acosh — Inverse hyperbolic cosine
    • asin — Arc sine
    • asinh — Inverse hyperbolic sine
    • atan2 — Arc tangent of two variables
    • atan — Arc tangent
    • atanh — Inverse hyperbolic tangent
    • base_convert — Convert a number between arbitrary bases
    • bindec — Binary to decimal
    • ceil — Round fractions up
    • cos — Cosine
    • cosh — Hyperbolic cosine
    • decbin — Decimal to binary
    • dechex — Decimal to hexadecimal
    • decoct — Decimal to octal
    • deg2rad — Converts the number in degrees to the radian equivalent
    • exp — Calculates the exponent of e
    • expm1 — Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
    • floor — Round fractions down
    • fmod — Returns the floating point remainder (modulo) of the division of the arguments
    • getrandmax — Show largest possible random value
    • hexdec — Hexadecimal to decimal
    • hypot — Calculate the length of the hypotenuse of a right-angle triangle
    • is_finite — Finds whether a value is a legal finite number
    • is_infinite — Finds whether a value is infinite
    • is_nan — Finds whether a value is not a number
    • lcg_value — Combined linear congruential generator
    • log10 — Base-10 logarithm
    • log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
    • log — Natural logarithm
    • max — Find highest value
    • min — Find lowest value
    • mt_getrandmax — Show largest possible random value
    • mt_rand — Generate a better random value
    • mt_srand — Seed the better random number generator
    • octdec — Octal to decimal
    • pi — Get value of pi
    • pow — Exponential expression
    • rad2deg — Converts the radian number to the equivalent number in degrees
    • rand — Generate a random integer
    • round — Rounds a float
    • sin — Sine
    • sinh — Hyperbolic sine
    • sqrt — Square root
    • srand — Seed the random number generator
    • tan — Tangent
    • tanh — Hyperbolic tangent
gmp_xor
Introduction
Mathematical Extensions


MaxDB

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • MaxDB extension overview example
  • MaxDB Functions
    • maxdb_affected_rows — Gets the number of affected rows in a previous MaxDB operation
    • maxdb_autocommit — Turns on or off auto-commiting database modifications
    • maxdb_bind_param — Alias of maxdb_stmt_bind_param
    • maxdb_bind_result — Alias of maxdb_stmt_bind_result
    • maxdb_change_user — Changes the user of the specified database connection
    • maxdb_character_set_name — Returns the default character set for the database connection
    • maxdb_client_encoding — Alias of maxdb_character_set_name
    • maxdb_close_long_data — Alias of maxdb_stmt_close_long_data
    • maxdb_close — Closes a previously opened database connection
    • maxdb_commit — Commits the current transaction
    • maxdb_connect_errno — Returns the error code from last connect call
    • maxdb_connect_error — Returns a string description of the last connect error
    • maxdb_connect — Open a new connection to the MaxDB server
    • maxdb_data_seek — Adjusts the result pointer to an arbitary row in the result
    • maxdb_debug — Performs debugging operations
    • maxdb_disable_reads_from_master — Disable reads from master
    • maxdb_disable_rpl_parse — Disable RPL parse
    • maxdb_dump_debug_info — Dump debugging information into the log
    • maxdb_embedded_connect — Open a connection to an embedded MaxDB server
    • maxdb_enable_reads_from_master — Enable reads from master
    • maxdb_enable_rpl_parse — Enable RPL parse
    • maxdb_errno — Returns the error code for the most recent function call
    • maxdb_error — Returns a string description of the last error
    • maxdb_escape_string — Alias of maxdb_real_escape_string
    • maxdb_execute — Alias of maxdb_stmt_execute
    • maxdb_fetch_array — Fetch a result row as an associative, a numeric array, or both
    • maxdb_fetch_assoc — Fetch a result row as an associative array
    • maxdb_fetch_field_direct — Fetch meta-data for a single field
    • maxdb_fetch_field — Returns the next field in the result set
    • maxdb_fetch_fields — Returns an array of resources representing the fields in a result set
    • maxdb_fetch_lengths — Returns the lengths of the columns of the current row in the result set
    • maxdb_fetch_object — Returns the current row of a result set as an object
    • maxdb_fetch_row — Get a result row as an enumerated array
    • maxdb_fetch — Alias of maxdb_stmt_fetch
    • maxdb_field_count — Returns the number of columns for the most recent query
    • maxdb_field_seek — Set result pointer to a specified field offset
    • maxdb_field_tell — Get current field offset of a result pointer
    • maxdb_free_result — Frees the memory associated with a result
    • maxdb_get_client_info — Returns the MaxDB client version as a string
    • maxdb_get_client_version — Get MaxDB client info
    • maxdb_get_host_info — Returns a string representing the type of connection used
    • maxdb_get_metadata — Alias of maxdb_stmt_result_metadata
    • maxdb_get_proto_info — Returns the version of the MaxDB protocol used
    • maxdb_get_server_info — Returns the version of the MaxDB server
    • maxdb_get_server_version — Returns the version of the MaxDB server as an integer
    • maxdb_info — Retrieves information about the most recently executed query
    • maxdb_init — Initializes MaxDB and returns an resource for use with maxdb_real_connect
    • maxdb_insert_id — Returns the auto generated id used in the last query
    • maxdb_kill — Disconnects from a MaxDB server
    • maxdb_master_query — Enforce execution of a query on the master in a master/slave setup
    • maxdb_more_results — Check if there any more query results from a multi query
    • maxdb_multi_query — Performs a query on the database
    • maxdb_next_result — Prepare next result from multi_query
    • maxdb_num_fields — Get the number of fields in a result
    • maxdb_num_rows — Gets the number of rows in a result
    • maxdb_options — Set options
    • maxdb_param_count — Alias of maxdb_stmt_param_count
    • maxdb_ping — Pings a server connection, or tries to reconnect if the connection has gone down
    • maxdb_prepare — Prepare a SQL statement for execution
    • maxdb_query — Performs a query on the database
    • maxdb_real_connect — Opens a connection to a MaxDB server
    • maxdb_real_escape_string — Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
    • maxdb_real_query — Execute an SQL query
    • maxdb_report — Enables or disables internal report functions
    • maxdb_rollback — Rolls back current transaction
    • maxdb_rpl_parse_enabled — Check if RPL parse is enabled
    • maxdb_rpl_probe — RPL probe
    • maxdb_rpl_query_type — Returns RPL query type
    • maxdb_select_db — Selects the default database for database queries
    • maxdb_send_long_data — Alias of maxdb_stmt_send_long_data
    • maxdb_send_query — Send the query and return
    • maxdb_server_end — Shut down the embedded server
    • maxdb_server_init — Initialize embedded server
    • maxdb_set_opt — Alias of maxdb_options
    • maxdb_sqlstate — Returns the SQLSTATE error from previous MaxDB operation
    • maxdb_ssl_set — Used for establishing secure connections using SSL
    • maxdb_stat — Gets the current system status
    • maxdb_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • maxdb_stmt_bind_param — Binds variables to a prepared statement as parameters
    • maxdb_stmt_bind_result — Binds variables to a prepared statement for result storage
    • maxdb_stmt_close_long_data — Ends a sequence of maxdb_stmt_send_long_data
    • maxdb_stmt_close — Closes a prepared statement
    • maxdb_stmt_data_seek — Seeks to an arbitray row in statement result set
    • maxdb_stmt_errno — Returns the error code for the most recent statement call
    • maxdb_stmt_error — Returns a string description for last statement error
    • maxdb_stmt_execute — Executes a prepared Query
    • maxdb_stmt_fetch — Fetch results from a prepared statement into the bound variables
    • maxdb_stmt_free_result — Frees stored result memory for the given statement handle
    • maxdb_stmt_init — Initializes a statement and returns an resource for use with maxdb_stmt_prepare
    • maxdb_stmt_num_rows — Return the number of rows in statements result set
    • maxdb_stmt_param_count — Returns the number of parameter for the given statement
    • maxdb_stmt_prepare — Prepare a SQL statement for execution
    • maxdb_stmt_reset — Resets a prepared statement
    • maxdb_stmt_result_metadata — Returns result set metadata from a prepared statement
    • maxdb_stmt_send_long_data — Send data in blocks
    • maxdb_stmt_sqlstate — Returns SQLSTATE error from previous statement operation
    • maxdb_stmt_store_result — Transfers a result set from a prepared statement
    • maxdb_store_result — Transfers a result set from the last query
    • maxdb_thread_id — Returns the thread ID for the current connection
    • maxdb_thread_safe — Returns whether thread safety is given or not
    • maxdb_use_result — Initiate a result set retrieval
    • maxdb_warning_count — Returns the number of warnings from the last query for the given link
ingres_unbuffered_query
Introduction
Vendor Specific Database Extensions


Multibyte String

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Summaries of supported encodings
  • Basics of Japanese multi-byte encodings
  • HTTP Input and Output
  • Supported Character Encodings
  • Function Overloading Feature
  • PHP Character Encoding Requirements
  • Multibyte String Functions
    • mb_check_encoding — Check if the string is valid for the specified encoding
    • mb_convert_case — Perform case folding on a string
    • mb_convert_encoding — Convert character encoding
    • mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
    • mb_convert_variables — Convert character code in variable(s)
    • mb_decode_mimeheader — Decode string in MIME header field
    • mb_decode_numericentity — Decode HTML numeric string reference to character
    • mb_detect_encoding — Detect character encoding
    • mb_detect_order — Set/Get character encoding detection order
    • mb_encode_mimeheader — Encode string for MIME header
    • mb_encode_numericentity — Encode character to HTML numeric string reference
    • mb_ereg_match — Regular expression match for multibyte string
    • mb_ereg_replace — Replace regular expression with multibyte support
    • mb_ereg_search_getpos — Returns start point for next regular expression match
    • mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match
    • mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match
    • mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
    • mb_ereg_search_regs — Returns the matched part of a multibyte regular expression
    • mb_ereg_search_setpos — Set start point of next regular expression match
    • mb_ereg_search — Multibyte regular expression match for predefined multibyte string
    • mb_ereg — Regular expression match with multibyte support
    • mb_eregi_replace — Replace regular expression with multibyte support ignoring case
    • mb_eregi — Regular expression match ignoring case with multibyte support
    • mb_get_info — Get internal settings of mbstring
    • mb_http_input — Detect HTTP input character encoding
    • mb_http_output — Set/Get HTTP output character encoding
    • mb_internal_encoding — Set/Get internal character encoding
    • mb_language — Set/Get current language
    • mb_list_encodings — Returns an array of all supported encodings
    • mb_output_handler — Callback function converts character encoding in output buffer
    • mb_parse_str — Parse GET/POST/COOKIE data and set global variable
    • mb_preferred_mime_name — Get MIME charset string
    • mb_regex_encoding — Returns current encoding for multibyte regex as string
    • mb_regex_set_options — Set/Get the default options for mbregex functions
    • mb_send_mail — Send encoded mail
    • mb_split — Split multibyte string using regular expression
    • mb_strcut — Get part of string
    • mb_strimwidth — Get truncated string with specified width
    • mb_stripos — Finds position of first occurrence of a string within another, case insensitive
    • mb_stristr — Finds first occurrence of a string within another, case insensitive
    • mb_strlen — Get string length
    • mb_strpos — Find position of first occurrence of string in a string
    • mb_strrchr — Finds the last occurrence of a character in a string within another
    • mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive
    • mb_strripos — Finds position of last occurrence of a string within another, case insensitive
    • mb_strrpos — Find position of last occurrence of a string in a string
    • mb_strstr — Finds first occurrence of a string within another
    • mb_strtolower — Make a string lowercase
    • mb_strtoupper — Make a string uppercase
    • mb_strwidth — Return width of string
    • mb_substitute_character — Set/Get substitution character
    • mb_substr_count — Count the number of substring occurrences
    • mb_substr — Get part of string
intl_is_failure
Introduction
Human Language and Character Encoding Support


Mcrypt

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mcrypt ciphers
  • Examples
  • Mcrypt Functions
    • mcrypt_cbc — Encrypt/decrypt data in CBC mode
    • mcrypt_cfb — Encrypt/decrypt data in CFB mode
    • mcrypt_create_iv — Create an initialization vector (IV) from a random source
    • mcrypt_decrypt — Decrypts crypttext with given parameters
    • mcrypt_ecb — Deprecated: Encrypt/decrypt data in ECB mode
    • mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm
    • mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm
    • mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm
    • mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode
    • mcrypt_enc_get_modes_name — Returns the name of the opened mode
    • mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
    • mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks
    • mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm
    • mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks
    • mcrypt_enc_self_test — Runs a self test on the opened module
    • mcrypt_encrypt — Encrypts plaintext with given parameters
    • mcrypt_generic_deinit — This function deinitializes an encryption module
    • mcrypt_generic_end — This function terminates encryption
    • mcrypt_generic_init — This function initializes all buffers needed for encryption
    • mcrypt_generic — This function encrypts data
    • mcrypt_get_block_size — Get the block size of the specified cipher
    • mcrypt_get_cipher_name — Get the name of the specified cipher
    • mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination
    • mcrypt_get_key_size — Get the key size of the specified cipher
    • mcrypt_list_algorithms — Get an array of all supported ciphers
    • mcrypt_list_modes — Get an array of all supported modes
    • mcrypt_module_close — Close the mcrypt module
    • mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm
    • mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode
    • mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
    • mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not
    • mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm
    • mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not
    • mcrypt_module_open — Opens the module of the algorithm and the mode to be used
    • mcrypt_module_self_test — This function runs a self test on the specified module
    • mcrypt_ofb — Encrypt/decrypt data in OFB mode
    • mdecrypt_generic — Decrypt data
hash
Introduction
Cryptography Extensions


MCVE (Monetra) Payment

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • MCVE Functions
    • m_checkstatus — Check to see if a transaction has completed
    • m_completeauthorizations — Number of complete authorizations in queue, returning an array of their identifiers
    • m_connect — Establish the connection to MCVE
    • m_connectionerror — Get a textual representation of why a connection failed
    • m_deletetrans — Delete specified transaction from MCVE_CONN structure
    • m_destroyconn — Destroy the connection and MCVE_CONN structure
    • m_destroyengine — Free memory associated with IP/SSL connectivity
    • m_getcell — Get a specific cell from a comma delimited response by column name
    • m_getcellbynum — Get a specific cell from a comma delimited response by column number
    • m_getcommadelimited — Get the RAW comma delimited data returned from MCVE
    • m_getheader — Get the name of the column in a comma-delimited response
    • m_initconn — Create and initialize an MCVE_CONN structure
    • m_initengine — Ready the client for IP/SSL Communication
    • m_iscommadelimited — Checks to see if response is comma delimited
    • m_maxconntimeout — The maximum amount of time the API will attempt a connection to MCVE
    • m_monitor — Perform communication with MCVE (send/receive data) Non-blocking
    • m_numcolumns — Number of columns returned in a comma delimited response
    • m_numrows — Number of rows returned in a comma delimited response
    • m_parsecommadelimited — Parse the comma delimited response so m_getcell, etc will work
    • m_responsekeys — Returns array of strings which represents the keys that can be used for response parameters on this transaction
    • m_responseparam — Get a custom response parameter
    • m_returnstatus — Check to see if the transaction was successful
    • m_setblocking — Set blocking/non-blocking mode for connection
    • m_setdropfile — Set the connection method to Drop-File
    • m_setip — Set the connection method to IP
    • m_setssl_cafile — Set SSL CA (Certificate Authority) file for verification of server certificate
    • m_setssl_files — Set certificate key files and certificates if server requires client certificate verification
    • m_setssl — Set the connection method to SSL
    • m_settimeout — Set maximum transaction time (per trans)
    • m_sslcert_gen_hash — Generate hash for SSL client certificate verification
    • m_transactionssent — Check to see if outgoing buffer is clear
    • m_transinqueue — Number of transactions in client-queue
    • m_transkeyval — Add key/value pair to a transaction. Replaces deprecated transparam()
    • m_transnew — Start a new transaction
    • m_transsend — Finalize and send the transaction
    • m_uwait — Wait x microsecs
    • m_validateidentifier — Whether or not to validate the passed identifier on any transaction it is passed to
    • m_verifyconnection — Set whether or not to PING upon connect to verify connection
    • m_verifysslcert — Set whether or not to verify the server ssl certificate
Credit Card Processing
Introduction
Credit Card Processing


Memtrack

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Creating large array in a function
zend_version
Introduction
Affecting PHP's Behaviour


Mhash

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Mhash Functions
    • mhash_count — Get the highest available hash id
    • mhash_get_block_size — Get the block size of the specified hash
    • mhash_get_hash_name — Get the name of the specified hash
    • mhash_keygen_s2k — Generates a key
    • mhash — Compute hash
mdecrypt_generic
Introduction
Cryptography Extensions


Mimetype

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
inotify_rm_watch
Introduction
File System Related Extensions


Ming (flash)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • SWFAction Examples
    • SWFSPrite basic examples
  • Ming Functions
    • ming_keypress — Returns the action flag for keyPress(char)
    • ming_setcubicthreshold — Set cubic threshold
    • ming_setscale — Set the global scaling factor.
    • ming_setswfcompression — Sets the SWF output compression
    • ming_useconstants — Use constant pool
    • ming_useswfversion — Sets the SWF version
  • SWFAction — The SWFAction class
    • SWFAction->__construct — Creates a new SWFAction
  • SWFBitmap — The SWFBitmap class
    • SWFBitmap->__construct — Loads Bitmap object
    • SWFBitmap->getHeight — Returns the bitmap's height
    • SWFBitmap->getWidth — Returns the bitmap's width
  • SWFButton — The SWFButton class
    • SWFButton->addAction — Adds an action
    • SWFButton->addASound — Associates a sound with a button transition
    • SWFButton->addShape — Adds a shape to a button
    • SWFButton->__construct — Creates a new Button
    • SWFButton->setAction — Sets the action
    • SWFButton->setDown — Alias for addShape(shape, SWFBUTTON_DOWN)
    • SWFButton->setHit — Alias for addShape(shape, SWFBUTTON_HIT)
    • SWFButton->setMenu — enable track as menu button behaviour
    • SWFButton->setOver — Alias for addShape(shape, SWFBUTTON_OVER)
    • SWFButton->setUp — Alias for addShape(shape, SWFBUTTON_UP)
  • SWFDisplayItem — The SWFDisplayItem class
    • SWFDisplayItem->addAction — Adds this SWFAction to the given SWFSprite instance
    • SWFDisplayItem->addColor — Adds the given color to this item's color transform
    • SWFDisplayItem->endMask — Another way of defining a MASK layer
    • SWFDisplayItem->getRot — Description
    • SWFDisplayItem->getX — Description
    • SWFDisplayItem->getXScale — Description
    • SWFDisplayItem->getXSkew — Description
    • SWFDisplayItem->getY — Description
    • SWFDisplayItem->getYScale — Description
    • SWFDisplayItem->getYSkew — Description
    • SWFDisplayItem->move — Moves object in relative coordinates
    • SWFDisplayItem->moveTo — Moves object in global coordinates
    • SWFDisplayItem->multColor — Multiplies the item's color transform
    • SWFDisplayItem->remove — Removes the object from the movie
    • SWFDisplayItem->rotate — Rotates in relative coordinates
    • SWFDisplayItem->rotateTo — Rotates the object in global coordinates
    • SWFDisplayItem->scale — Scales the object in relative coordinates
    • SWFDisplayItem->scaleTo — Scales the object in global coordinates
    • SWFDisplayItem->setDepth — Sets z-order
    • SWFDisplayItem->setMaskLevel — Defines a MASK layer at level
    • SWFDisplayItem->setMatrix — Sets the item's transform matrix
    • SWFDisplayItem->setName — Sets the object's name
    • SWFDisplayItem->setRatio — Sets the object's ratio
    • SWFDisplayItem->skewX — Sets the X-skew
    • SWFDisplayItem->skewXTo — Sets the X-skew
    • SWFDisplayItem->skewY — Sets the Y-skew
    • SWFDisplayItem->skewYTo — Sets the Y-skew
  • SWFFill — The SWFFill class
    • SWFFill->moveTo — Moves fill origin
    • SWFFill->rotateTo — Sets fill's rotation
    • SWFFill->scaleTo — Sets fill's scale
    • SWFFill->skewXTo — Sets fill x-skew
    • SWFFill->skewYTo — Sets fill y-skew
  • SWFFont — The SWFFont class
    • SWFFont->__construct — Loads a font definition
    • SWFFont->getAscent — Returns the ascent of the font, or 0 if not available
    • SWFFont->getDescent — Returns the descent of the font, or 0 if not available
    • SWFFont->getLeading — Returns the leading of the font, or 0 if not available
    • SWFFont->getShape — Returns the glyph shape of a char as a text string
    • SWFFont->getUTF8Width — Calculates the width of the given string in this font at full height
    • SWFFont->getWidth — Returns the string's width
  • SWFFontChar — The SWFFontChar class
    • SWFFontChar->addChars — Adds characters to a font for exporting font
    • SWFFontChar->addUTF8Chars — Adds characters to a font for exporting font
  • SWFGradient — The SWFGradient class
    • SWFGradient->addEntry — Adds an entry to the gradient list
    • SWFGradient->__construct — Creates a gradient object
  • SWFMorph — The SWFMorph class
    • SWFMorph->__construct — Creates a new SWFMorph object
    • SWFMorph->getShape1 — Gets a handle to the starting shape
    • SWFMorph->getShape2 — Gets a handle to the ending shape
  • SWFMovie — The SWFMovie class
    • SWFMovie->add — Adds any type of data to a movie
    • SWFMovie->addExport — Description
    • SWFMovie->addFont — Description
    • SWFMovie->__construct — Creates a new movie object, representing an SWF version 4 movie
    • SWFMovie->importChar — Description
    • SWFMovie->importFont — Description
    • SWFMovie->labelFrame — Labels a frame
    • SWFMovie->nextFrame — Moves to the next frame of the animation
    • SWFMovie->output — Dumps your lovingly prepared movie out
    • SWFMovie->remove — Removes the object instance from the display list
    • SWFMovie->save — Saves the SWF movie in a file
    • SWFMovie->saveToFile — Description
    • SWFMovie->setbackground — Sets the background color
    • SWFMovie->setDimension — Sets the movie's width and height
    • SWFMovie->setFrames — Sets the total number of frames in the animation
    • SWFMovie->setRate — Sets the animation's frame rate
    • SWFMovie->startSound — Description
    • SWFMovie->stopSound — Description
    • SWFMovie->streamMP3 — Streams a MP3 file
    • SWFMovie->writeExports — Description
  • SWFPrebuiltClip — The SWFPrebuiltClip class
    • SWFPrebuiltClip->__construct — Returns a SWFPrebuiltClip object
  • SWFShape — The SWFShape class
    • SWFShape->addFill — Adds a solid fill to the shape
    • SWFShape->__construct — Creates a new shape object
    • SWFShape->drawArc — Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock
    • SWFShape->drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion
    • SWFShape->drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape->drawCubicTo — Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape->drawCurve — Draws a curve (relative)
    • SWFShape->drawCurveTo — Draws a curve
    • SWFShape->drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font
    • SWFShape->drawLine — Draws a line (relative)
    • SWFShape->drawLineTo — Draws a line
    • SWFShape->movePen — Moves the shape's pen (relative)
    • SWFShape->movePenTo — Moves the shape's pen
    • SWFShape->setLeftFill — Sets left rasterizing color
    • SWFShape->setLine — Sets the shape's line style
    • SWFShape->setRightFill — Sets right rasterizing color
  • SWFSound — The SWFSound class
    • SWFSound — Returns a new SWFSound object from given file
  • SWFSoundInstance — The SWFSoundInstance class
    • SWFSoundInstance->loopCount — Description
    • SWFSoundInstance->loopInPoint — Description
    • SWFSoundInstance->loopOutPoint — Description
    • SWFSoundInstance->noMultiple — Description
  • SWFSprite — The SWFSprite class
    • SWFSprite->add — Adds an object to a sprite
    • SWFSprite->__construct — Creates a movie clip (a sprite)
    • SWFSprite->labelFrame — Labels frame
    • SWFSprite->nextFrame — Moves to the next frame of the animation
    • SWFSprite->remove — Removes an object to a sprite
    • SWFSprite->setFrames — Sets the total number of frames in the animation
    • SWFSprite->startSound — Description
    • SWFSprite->stopSound — Description
  • SWFText — The SWFText class
    • SWFText->addString — Draws a string
    • SWFText->addUTF8String — Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color
    • SWFText->__construct — Creates a new SWFText object
    • SWFText->getAscent — Returns the ascent of the current font at its current size, or 0 if not available
    • SWFText->getDescent — Returns the descent of the current font at its current size, or 0 if not available
    • SWFText->getLeading — Returns the leading of the current font at its current size, or 0 if not available
    • SWFText->getUTF8Width — calculates the width of the given string in this text objects current font and size
    • SWFText->getWidth — Computes string's width
    • SWFText->moveTo — Moves the pen
    • SWFText->setColor — Sets the current text color
    • SWFText->setFont — Sets the current font
    • SWFText->setHeight — Sets the current font height
    • SWFText->setSpacing — Sets the current font spacing
  • SWFTextField — The SWFTextField class
    • SWFTextField->addChars — adds characters to a font that will be available within a textfield
    • SWFTextField->addString — Concatenates the given string to the text field
    • SWFTextField->align — Sets the text field alignment
    • SWFTextField->__construct — Creates a text field object
    • SWFTextField->setBounds — Sets the text field width and height
    • SWFTextField->setColor — Sets the color of the text field
    • SWFTextField->setFont — Sets the text field font
    • SWFTextField->setHeight — Sets the font height of this text field font
    • SWFTextField->setIndentation — Sets the indentation of the first line
    • SWFTextField->setLeftMargin — Sets the left margin width of the text field
    • SWFTextField->setLineSpacing — Sets the line spacing of the text field
    • SWFTextField->setMargins — Sets the margins width of the text field
    • SWFTextField->setName — Sets the variable name
    • SWFTextField->setPadding — Sets the padding of this textfield
    • SWFTextField->setRightMargin — Sets the right margin width of the text field
  • SWFVideoStream — The SWFVideoStream class
    • SWFVideoStream->__construct — Returns a SWFVideoStream object
    • SWFVideoStream->getNumFrames — Returns the number of frames in the video
    • SWFVideoStream->setDimension — Sets video dimension
HaruDestination::setXYZ
Introduction
Non-Text MIME Output


Miscellaneous Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Misc. Functions
    • connection_aborted — Check whether client disconnected
    • connection_status — Returns connection status bitfield
    • connection_timeout — Check if the script timed out
    • constant — Returns the value of a constant
    • define — Defines a named constant
    • defined — Checks whether a given named constant exists
    • die — Equivalent to exit
    • eval — Evaluate a string as PHP code
    • exit — Output a message and terminate the current script
    • get_browser — Tells what the user's browser is capable of
    • __halt_compiler — Halts the compiler execution
    • highlight_file — Syntax highlighting of a file
    • highlight_string — Syntax highlighting of a string
    • ignore_user_abort — Set whether a client disconnect should abort script execution
    • pack — Pack data into binary string
    • php_check_syntax — Check the PHP syntax of (and execute) the specified file
    • php_strip_whitespace — Return source with stripped comments and whitespace
    • show_source — Alias of highlight_file
    • sleep — Delay execution
    • sys_getloadavg — Gets system load average
    • time_nanosleep — Delay for a number of seconds and nanoseconds
    • time_sleep_until — Make the script sleep until the specified time
    • uniqid — Generate a unique ID
    • unpack — Unpack data from binary string
    • usleep — Delay execution in microseconds
json_last_error
Introduction
Other Basic Extensions


Mongo

  • Manual
    • Installation
    • Runtime Configuration
    • Tutorial
    • Examples
    • Querying
    • Updates
    • Troubleshooting
  • Core Classes
    • Mongo — The Mongo class
    • MongoDB — The MongoDB class
    • MongoCollection — The MongoCollection class
    • MongoCursor — The MongoCursor class
  • Types
    • MongoId — The MongoId class
    • MongoCode — The MongoCode class
    • MongoDate — The MongoDate class
    • MongoRegex — The MongoRegex class
    • MongoBinData — The MongoBinData class
    • MongoDBRef — The MongoDBRef class
    • MongoMinKey — The MongoMinKey class
    • MongoMaxKey — The MongoMaxKey class
    • MongoTimestamp — The MongoTimestamp class
  • GridFS Classes
    • MongoGridFS — The MongoGridFS class
    • MongoGridFSFile — The MongoGridFSFile class
    • MongoGridFSCursor — The MongoGridFSCursor class
  • Functions
    • Mongo Functions
  • Exceptions
    • MongoException — The MongoException class
    • MongoCursorException — The MongoCursorException class
    • MongoCursorTimeoutException — The MongoCursorTimeoutException class
    • MongoConnectionException — The MongoConnectionException class
    • MongoGridFSException — The MongoGridFSException class
maxdb_warning_count
Manual
Vendor Specific Database Extensions


mSQL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • mSQL usage example
  • mSQL Functions
    • msql_affected_rows — Returns number of affected rows
    • msql_close — Close mSQL connection
    • msql_connect — Open mSQL connection
    • msql_create_db — Create mSQL database
    • msql_createdb — Alias of msql_create_db
    • msql_data_seek — Move internal row pointer
    • msql_db_query — Send mSQL query
    • msql_dbname — Alias of msql_result
    • msql_drop_db — Drop (delete) mSQL database
    • msql_error — Returns error message of last msql call
    • msql_fetch_array — Fetch row as array
    • msql_fetch_field — Get field information
    • msql_fetch_object — Fetch row as object
    • msql_fetch_row — Get row as enumerated array
    • msql_field_flags — Get field flags
    • msql_field_len — Get field length
    • msql_field_name — Get the name of the specified field in a result
    • msql_field_seek — Set field offset
    • msql_field_table — Get table name for field
    • msql_field_type — Get field type
    • msql_fieldflags — Alias of msql_field_flags
    • msql_fieldlen — Alias of msql_field_len
    • msql_fieldname — Alias of msql_field_name
    • msql_fieldtable — Alias of msql_field_table
    • msql_fieldtype — Alias of msql_field_type
    • msql_free_result — Free result memory
    • msql_list_dbs — List mSQL databases on server
    • msql_list_fields — List result fields
    • msql_list_tables — List tables in an mSQL database
    • msql_num_fields — Get number of fields in result
    • msql_num_rows — Get number of rows in result
    • msql_numfields — Alias of msql_num_fields
    • msql_numrows — Alias of msql_num_rows
    • msql_pconnect — Open persistent mSQL connection
    • msql_query — Send mSQL query
    • msql_regcase — Alias of sql_regcase
    • msql_result — Get result data
    • msql_select_db — Select mSQL database
    • msql_tablename — Alias of msql_result
    • msql — Alias of msql_db_query
MongoGridFSException
Introduction
Vendor Specific Database Extensions


Microsoft SQL Server

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mssql Functions
    • mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure
    • mssql_close — Close MS SQL Server connection
    • mssql_connect — Open MS SQL server connection
    • mssql_data_seek — Moves internal row pointer
    • mssql_execute — Executes a stored procedure on a MS SQL server database
    • mssql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • mssql_fetch_assoc — Returns an associative array of the current row in the result
    • mssql_fetch_batch — Returns the next batch of records
    • mssql_fetch_field — Get field information
    • mssql_fetch_object — Fetch row as object
    • mssql_fetch_row — Get row as enumerated array
    • mssql_field_length — Get the length of a field
    • mssql_field_name — Get the name of a field
    • mssql_field_seek — Seeks to the specified field offset
    • mssql_field_type — Gets the type of a field
    • mssql_free_result — Free result memory
    • mssql_free_statement — Free statement memory
    • mssql_get_last_message — Returns the last message from the server
    • mssql_guid_string — Converts a 16 byte binary GUID to a string
    • mssql_init — Initializes a stored procedure or a remote stored procedure
    • mssql_min_error_severity — Sets the minimum error severity
    • mssql_min_message_severity — Sets the minimum message severity
    • mssql_next_result — Move the internal result pointer to the next result
    • mssql_num_fields — Gets the number of fields in result
    • mssql_num_rows — Gets the number of rows in result
    • mssql_pconnect — Open persistent MS SQL connection
    • mssql_query — Send MS SQL query
    • mssql_result — Get result data
    • mssql_rows_affected — Returns the number of records affected by the query
    • mssql_select_db — Select MS SQL database
msql
Introduction
Vendor Specific Database Extensions


MySQL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • MySQL extension overview example
  • MySQL Functions
    • mysql_affected_rows — Get number of affected rows in previous MySQL operation
    • mysql_client_encoding — Returns the name of the character set
    • mysql_close — Close MySQL connection
    • mysql_connect — Open a connection to a MySQL Server
    • mysql_create_db — Create a MySQL database
    • mysql_data_seek — Move internal result pointer
    • mysql_db_name — Get result data
    • mysql_db_query — Send a MySQL query
    • mysql_drop_db — Drop (delete) a MySQL database
    • mysql_errno — Returns the numerical value of the error message from previous MySQL operation
    • mysql_error — Returns the text of the error message from previous MySQL operation
    • mysql_escape_string — Escapes a string for use in a mysql_query
    • mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • mysql_fetch_assoc — Fetch a result row as an associative array
    • mysql_fetch_field — Get column information from a result and return as an object
    • mysql_fetch_lengths — Get the length of each output in a result
    • mysql_fetch_object — Fetch a result row as an object
    • mysql_fetch_row — Get a result row as an enumerated array
    • mysql_field_flags — Get the flags associated with the specified field in a result
    • mysql_field_len — Returns the length of the specified field
    • mysql_field_name — Get the name of the specified field in a result
    • mysql_field_seek — Set result pointer to a specified field offset
    • mysql_field_table — Get name of the table the specified field is in
    • mysql_field_type — Get the type of the specified field in a result
    • mysql_free_result — Free result memory
    • mysql_get_client_info — Get MySQL client info
    • mysql_get_host_info — Get MySQL host info
    • mysql_get_proto_info — Get MySQL protocol info
    • mysql_get_server_info — Get MySQL server info
    • mysql_info — Get information about the most recent query
    • mysql_insert_id — Get the ID generated in the last query
    • mysql_list_dbs — List databases available on a MySQL server
    • mysql_list_fields — List MySQL table fields
    • mysql_list_processes — List MySQL processes
    • mysql_list_tables — List tables in a MySQL database
    • mysql_num_fields — Get number of fields in result
    • mysql_num_rows — Get number of rows in result
    • mysql_pconnect — Open a persistent connection to a MySQL server
    • mysql_ping — Ping a server connection or reconnect if there is no connection
    • mysql_query — Send a MySQL query
    • mysql_real_escape_string — Escapes special characters in a string for use in a SQL statement
    • mysql_result — Get result data
    • mysql_select_db — Select a MySQL database
    • mysql_set_charset — Sets the client character set
    • mysql_stat — Get current system status
    • mysql_tablename — Get table name of field
    • mysql_thread_id — Return the current thread ID
    • mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows.
mssql_select_db
Introduction
Vendor Specific Database Extensions


MySQL Improved Extension

  • Introduction
  • Overview
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • The mysqli Extension and Persistent Connections
  • Predefined Constants
  • The MySQLi Extension Function Summary
  • MySQLi — The MySQLi class
    • mysqli->affected_rows — Gets the number of affected rows in a previous MySQL operation
    • mysqli::autocommit — Turns on or off auto-commiting database modifications
    • mysqli::change_user — Changes the user of the specified database connection
    • mysqli::character_set_name — Returns the default character set for the database connection
    • mysqli->client_info — Returns the MySQL client version as a string
    • mysqli->client_version — Get MySQL client info
    • mysqli::close — Closes a previously opened database connection
    • mysqli::commit — Commits the current transaction
    • mysqli->connect_errno — Returns the error code from last connect call
    • mysqli->connect_error — Returns a string description of the last connect error
    • mysqli::__construct — Open a new connection to the MySQL server
    • mysqli::debug — Performs debugging operations
    • mysqli::dump_debug_info — Dump debugging information into the log
    • mysqli->errno — Returns the error code for the most recent function call
    • mysqli->error — Returns a string description of the last error
    • mysqli->field_count — Returns the number of columns for the most recent query
    • mysqli::get_charset — Returns a character set object
    • mysqli->get_client_info — Returns the MySQL client version as a string
    • mysqli->client_version — Get MySQL client info
    • mysqli::get_connection_stats — Returns statistics about the client connection
    • mysqli->host_info — Returns a string representing the type of connection used
    • mysqli->protocol_version — Returns the version of the MySQL protocol used
    • mysqli->server_info — Returns the version of the MySQL server
    • mysqli->server_version — Returns the version of the MySQL server as an integer
    • mysqli::get_warnings — Get result of SHOW WARNINGS
    • mysqli->info — Retrieves information about the most recently executed query
    • mysqli::init — Initializes MySQLi and returns a resource for use with mysqli_real_connect()
    • mysqli->insert_id — Returns the auto generated id used in the last query
    • mysqli::kill — Asks the server to kill a MySQL thread
    • mysqli::more_results — Check if there are any more query results from a multi query
    • mysqli::multi_query — Performs a query on the database
    • mysqli::next_result — Prepare next result from multi_query
    • mysqli::options — Set options
    • mysqli::ping — Pings a server connection, or tries to reconnect if the connection has gone down
    • mysqli::poll — Poll connections
    • mysqli::prepare — Prepare a SQL statement for execution
    • mysqli::query — Performs a query on the database
    • mysqli::real_connect — Opens a connection to a mysql server
    • mysqli::real_escape_string — Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
    • mysqli::real_query — Execute an SQL query
    • mysqli::reap_async_query — Get result from async query
    • mysqli::rollback — Rolls back current transaction
    • mysqli::select_db — Selects the default database for database queries
    • mysqli::set_charset — Sets the default client character set
    • mysqli::set_local_infile_default — Unsets user defined handler for load local infile command
    • mysqli::set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command
    • mysqli->sqlstate — Returns the SQLSTATE error from previous MySQL operation
    • mysqli::ssl_set — Used for establishing secure connections using SSL
    • mysqli::stat — Gets the current system status
    • mysqli::stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare
    • mysqli::store_result — Transfers a result set from the last query
    • mysqli::thread_id — Returns the thread ID for the current connection
    • mysqli::thread_safe — Returns whether thread safety is given or not
    • mysqli::use_result — Initiate a result set retrieval
    • mysqli::warning_count — Returns the number of warnings from the last query for the given link
  • MySQLi_STMT — The MySQLi_STMT class
    • mysqli_stmt->affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • mysqli_stmt::attr_get — Used to get the current value of a statement attribute
    • mysqli_stmt::attr_set — Used to modify the behavior of a prepared statement
    • mysqli_stmt::bind_param — Binds variables to a prepared statement as parameters
    • mysqli_stmt::bind_result — Binds variables to a prepared statement for result storage
    • mysqli_stmt::close — Closes a prepared statement
    • mysqli_stmt::data_seek — Seeks to an arbitrary row in statement result set
    • mysqli_stmt->errno — Returns the error code for the most recent statement call
    • mysqli_stmt->error — Returns a string description for last statement error
    • mysqli_stmt::execute — Executes a prepared Query
    • mysqli_stmt::fetch — Fetch results from a prepared statement into the bound variables
    • mysqli_stmt->field_count — Returns the number of field in the given statement
    • mysqli_stmt::free_result — Frees stored result memory for the given statement handle
    • mysqli_stmt::get_warnings — Get result of SHOW WARNINGS
    • mysqli_stmt->insert_id — Get the ID generated from the previous INSERT operation
    • mysqli_stmt::num_rows — Return the number of rows in statements result set
    • mysqli_stmt->param_count — Returns the number of parameter for the given statement
    • mysqli_stmt::prepare — Prepare a SQL statement for execution
    • mysqli_stmt::reset — Resets a prepared statement
    • mysqli_stmt::result_metadata — Returns result set metadata from a prepared statement
    • mysqli_stmt::send_long_data — Send data in blocks
    • mysqli_stmt::sqlstate — Returns SQLSTATE error from previous statement operation
    • mysqli_stmt::store_result — Transfers a result set from a prepared statement
  • MySQLi_Result — The MySQLi_Result class
    • mysqli_result->current_field — Get current field offset of a result pointer
    • mysqli_result::data_seek — Adjusts the result pointer to an arbitary row in the result
    • mysqli_result::fetch_all — Fetches all result rows as an associative array, a numeric array, or both
    • mysqli_result::fetch_array — Fetch a result row as an associative, a numeric array, or both
    • mysqli_result::fetch_assoc — Fetch a result row as an associative array
    • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
    • mysqli_result::fetch_field — Returns the next field in the result set
    • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
    • mysqli_result::fetch_object — Returns the current row of a result set as an object
    • mysqli_result::fetch_row — Get a result row as an enumerated array
    • mysqli_result->field_count — Get the number of fields in a result
    • mysqli_result::field_seek — Set result pointer to a specified field offset
    • mysqli_result::free — Frees the memory associated with a result
    • mysqli_result->lengths — Returns the lengths of the columns of the current row in the result set
    • mysqli_result->num_rows — Gets the number of rows in a result
  • MySQLi_Driver — The MySQLi_Driver class
    • mysqli_driver::embedded_server_end — Stop embedded server
    • mysqli_driver::embedded_server_start — Initialize and start embedded server
  • MySQLi_Warning — The MySQLi_Warning class
    • mysqli_warning::__construct — The __construct purpose
    • mysqli_warning::next — The next purpose
  • Aliases and deprecated Mysqli Functions
    • mysqli_bind_param — Alias for mysqli_stmt_bind_param
    • mysqli_bind_result — Alias for mysqli_stmt_bind_result
    • mysqli_client_encoding — Alias of mysqli_character_set_name
    • mysqli_disable_reads_from_master — Disable reads from master
    • mysqli_disable_rpl_parse — Disable RPL parse
    • mysqli_enable_reads_from_master — Enable reads from master
    • mysqli_enable_rpl_parse — Enable RPL parse
    • mysqli_escape_string — Alias of mysqli_real_escape_string
    • mysqli_execute — Alias for mysqli_stmt_execute
    • mysqli_fetch — Alias for mysqli_stmt_fetch
    • mysqli_get_cache_stats — Returns client Zval cache statistics
    • mysqli_get_client_stats — Returns client per-process statistics
    • mysqli_get_metadata — Alias for mysqli_stmt_result_metadata
    • mysqli_master_query — Enforce execution of a query on the master in a master/slave setup
    • mysqli_param_count — Alias for mysqli_stmt_param_count
    • mysqli_report — Enables or disables internal report functions
    • mysqli_rpl_parse_enabled — Check if RPL parse is enabled
    • mysqli_rpl_probe — RPL probe
    • mysqli_rpl_query_type — Returns RPL query type
    • mysqli_send_long_data — Alias for mysqli_stmt_send_long_data
    • mysqli_send_query — Send the query and return
    • mysqli_set_opt — Alias of mysqli_options
    • mysqli_slave_query — Force execution of a query on a slave in a master/slave setup
mysql_unbuffered_query
Introduction
Vendor Specific Database Extensions


MySQL Native Driver

  • Introduction
  • Overview
  • Installation
  • Configuration
  • Persistent Connections
  • Statistics
  • Notes
mysqli_slave_query
Introduction
Vendor Specific Database Extensions


Ncurses Terminal Screen Control

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Error codes
    • Colors
    • Keys
    • Mouse
  • Ncurses Functions
    • ncurses_addch — Add character at current position and advance cursor
    • ncurses_addchnstr — Add attributed string with specified length at current position
    • ncurses_addchstr — Add attributed string at current position
    • ncurses_addnstr — Add string with specified length at current position
    • ncurses_addstr — Output text at current position
    • ncurses_assume_default_colors — Define default colors for color 0
    • ncurses_attroff — Turn off the given attributes
    • ncurses_attron — Turn on the given attributes
    • ncurses_attrset — Set given attributes
    • ncurses_baudrate — Returns baudrate of terminal
    • ncurses_beep — Let the terminal beep
    • ncurses_bkgd — Set background property for terminal screen
    • ncurses_bkgdset — Control screen background
    • ncurses_border — Draw a border around the screen using attributed characters
    • ncurses_bottom_panel — Moves a visible panel to the bottom of the stack
    • ncurses_can_change_color — Checks if terminal color definitions can be changed
    • ncurses_cbreak — Switch of input buffering
    • ncurses_clear — Clear screen
    • ncurses_clrtobot — Clear screen from current position to bottom
    • ncurses_clrtoeol — Clear screen from current position to end of line
    • ncurses_color_content — Retrieves RGB components of a color
    • ncurses_color_set — Set active foreground and background colors
    • ncurses_curs_set — Set cursor state
    • ncurses_def_prog_mode — Saves terminals (program) mode
    • ncurses_def_shell_mode — Saves terminals (shell) mode
    • ncurses_define_key — Define a keycode
    • ncurses_del_panel — Remove panel from the stack and delete it (but not the associated window)
    • ncurses_delay_output — Delay output on terminal using padding characters
    • ncurses_delch — Delete character at current position, move rest of line left
    • ncurses_deleteln — Delete line at current position, move rest of screen up
    • ncurses_delwin — Delete a ncurses window
    • ncurses_doupdate — Write all prepared refreshes to terminal
    • ncurses_echo — Activate keyboard input echo
    • ncurses_echochar — Single character output including refresh
    • ncurses_end — Stop using ncurses, clean up the screen
    • ncurses_erase — Erase terminal screen
    • ncurses_erasechar — Returns current erase character
    • ncurses_filter — Set LINES for iniscr() and newterm() to 1
    • ncurses_flash — Flash terminal screen (visual bell)
    • ncurses_flushinp — Flush keyboard input buffer
    • ncurses_getch — Read a character from keyboard
    • ncurses_getmaxyx — Returns the size of a window
    • ncurses_getmouse — Reads mouse event
    • ncurses_getyx — Returns the current cursor position for a window
    • ncurses_halfdelay — Put terminal into halfdelay mode
    • ncurses_has_colors — Checks if terminal has color capabilities
    • ncurses_has_ic — Check for insert- and delete-capabilities
    • ncurses_has_il — Check for line insert- and delete-capabilities
    • ncurses_has_key — Check for presence of a function key on terminal keyboard
    • ncurses_hide_panel — Remove panel from the stack, making it invisible
    • ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long
    • ncurses_inch — Get character and attribute at current position
    • ncurses_init_color — Define a terminal color
    • ncurses_init_pair — Define a color pair
    • ncurses_init — Initialize ncurses
    • ncurses_insch — Insert character moving rest of line including character at current position
    • ncurses_insdelln — Insert lines before current line scrolling down (negative numbers delete and scroll up)
    • ncurses_insertln — Insert a line, move rest of screen down
    • ncurses_insstr — Insert string at current position, moving rest of line right
    • ncurses_instr — Reads string from terminal screen
    • ncurses_isendwin — Ncurses is in endwin mode, normal screen output may be performed
    • ncurses_keyok — Enable or disable a keycode
    • ncurses_keypad — Turns keypad on or off
    • ncurses_killchar — Returns current line kill character
    • ncurses_longname — Returns terminals description
    • ncurses_meta — Enables/Disable 8-bit meta key information
    • ncurses_mouse_trafo — Transforms coordinates
    • ncurses_mouseinterval — Set timeout for mouse button clicks
    • ncurses_mousemask — Sets mouse options
    • ncurses_move_panel — Moves a panel so that its upper-left corner is at [startx, starty]
    • ncurses_move — Move output position
    • ncurses_mvaddch — Move current position and add character
    • ncurses_mvaddchnstr — Move position and add attributed string with specified length
    • ncurses_mvaddchstr — Move position and add attributed string
    • ncurses_mvaddnstr — Move position and add string with specified length
    • ncurses_mvaddstr — Move position and add string
    • ncurses_mvcur — Move cursor immediately
    • ncurses_mvdelch — Move position and delete character, shift rest of line left
    • ncurses_mvgetch — Move position and get character at new position
    • ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long
    • ncurses_mvinch — Move position and get attributed character at new position
    • ncurses_mvvline — Set new position and draw a vertical line using an attributed character and max. n characters long
    • ncurses_mvwaddstr — Add string at new position in window
    • ncurses_napms — Sleep
    • ncurses_new_panel — Create a new panel and associate it with window
    • ncurses_newpad — Creates a new pad (window)
    • ncurses_newwin — Create a new window
    • ncurses_nl — Translate newline and carriage return / line feed
    • ncurses_nocbreak — Switch terminal to cooked mode
    • ncurses_noecho — Switch off keyboard input echo
    • ncurses_nonl — Do not translate newline and carriage return / line feed
    • ncurses_noqiflush — Do not flush on signal characters
    • ncurses_noraw — Switch terminal out of raw mode
    • ncurses_pair_content — Retrieves foreground and background colors of a color pair
    • ncurses_panel_above — Returns the panel above panel
    • ncurses_panel_below — Returns the panel below panel
    • ncurses_panel_window — Returns the window associated with panel
    • ncurses_pnoutrefresh — Copies a region from a pad into the virtual screen
    • ncurses_prefresh — Copies a region from a pad into the virtual screen
    • ncurses_putp — Apply padding information to the string and output it
    • ncurses_qiflush — Flush on signal characters
    • ncurses_raw — Switch terminal into raw mode
    • ncurses_refresh — Refresh screen
    • ncurses_replace_panel — Replaces the window associated with panel
    • ncurses_reset_prog_mode — Resets the prog mode saved by def_prog_mode
    • ncurses_reset_shell_mode — Resets the shell mode saved by def_shell_mode
    • ncurses_resetty — Restores saved terminal state
    • ncurses_savetty — Saves terminal state
    • ncurses_scr_dump — Dump screen content to file
    • ncurses_scr_init — Initialize screen from file dump
    • ncurses_scr_restore — Restore screen from file dump
    • ncurses_scr_set — Inherit screen from file dump
    • ncurses_scrl — Scroll window content up or down without changing current position
    • ncurses_show_panel — Places an invisible panel on top of the stack, making it visible
    • ncurses_slk_attr — Returns current soft label key attribute
    • ncurses_slk_attroff — Turn off the given attributes for soft function-key labels
    • ncurses_slk_attron — Turn on the given attributes for soft function-key labels
    • ncurses_slk_attrset — Set given attributes for soft function-key labels
    • ncurses_slk_clear — Clears soft labels from screen
    • ncurses_slk_color — Sets color for soft label keys
    • ncurses_slk_init — Initializes soft label key functions
    • ncurses_slk_noutrefresh — Copies soft label keys to virtual screen
    • ncurses_slk_refresh — Copies soft label keys to screen
    • ncurses_slk_restore — Restores soft label keys
    • ncurses_slk_set — Sets function key labels
    • ncurses_slk_touch — Forces output when ncurses_slk_noutrefresh is performed
    • ncurses_standend — Stop using 'standout' attribute
    • ncurses_standout — Start using 'standout' attribute
    • ncurses_start_color — Initializes color functionality
    • ncurses_termattrs — Returns a logical OR of all attribute flags supported by terminal
    • ncurses_termname — Returns terminals (short)-name
    • ncurses_timeout — Set timeout for special key sequences
    • ncurses_top_panel — Moves a visible panel to the top of the stack
    • ncurses_typeahead — Specify different filedescriptor for typeahead checking
    • ncurses_ungetch — Put a character back into the input stream
    • ncurses_ungetmouse — Pushes mouse event to queue
    • ncurses_update_panels — Refreshes the virtual screen to reflect the relations between panels in the stack
    • ncurses_use_default_colors — Assign terminal default colors to color id -1
    • ncurses_use_env — Control use of environment information about terminal size
    • ncurses_use_extended_names — Control use of extended names in terminfo descriptions
    • ncurses_vidattr — Display the string on the terminal in the video attribute mode
    • ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long
    • ncurses_waddch — Adds character at current position in a window and advance cursor
    • ncurses_waddstr — Outputs text at current postion in window
    • ncurses_wattroff — Turns off attributes for a window
    • ncurses_wattron — Turns on attributes for a window
    • ncurses_wattrset — Set the attributes for a window
    • ncurses_wborder — Draws a border around the window using attributed characters
    • ncurses_wclear — Clears window
    • ncurses_wcolor_set — Sets windows color pairings
    • ncurses_werase — Erase window contents
    • ncurses_wgetch — Reads a character from keyboard (window)
    • ncurses_whline — Draws a horizontal line in a window at current position using an attributed character and max. n characters long
    • ncurses_wmouse_trafo — Transforms window/stdscr coordinates
    • ncurses_wmove — Moves windows output position
    • ncurses_wnoutrefresh — Copies window to virtual screen
    • ncurses_wrefresh — Refresh window on terminal screen
    • ncurses_wstandend — End standout mode for a window
    • ncurses_wstandout — Enter standout mode for a window
    • ncurses_wvline — Draws a vertical line in a window at current position using an attributed character and max. n characters long
newt_win_ternary
Introduction
Command Line Specific Extensions


Newt

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Newt form exit reasons
    • Newt colorsets
    • Newt argument flags
    • Newt Flags Sense
    • Newt Components Flags
    • File Descriptor Flags
    • Checkbox Tree Flags
    • Entry Flags
    • Listbox Flags
    • Textbox Flags
    • Form Flags
    • Newt Keys
    • Newt Anchors
    • Grid Flags
  • Examples
    • Basic usage
  • Newt Functions
    • newt_bell — Send a beep to the terminal
    • newt_button_bar — This function returns a grid containing the buttons created.
    • newt_button — Create a new button
    • newt_centered_window — Open a centered window of the specified size
    • newt_checkbox_get_value — Retreives value of checkox resource
    • newt_checkbox_set_flags — Configures checkbox resource
    • newt_checkbox_set_value — Sets the value of the checkbox
    • newt_checkbox_tree_add_item — Adds new item to the checkbox tree
    • newt_checkbox_tree_find_item — Finds an item in the checkbox tree
    • newt_checkbox_tree_get_current — Returns checkbox tree selected item
    • newt_checkbox_tree_get_entry_value — Description
    • newt_checkbox_tree_get_multi_selection — Description
    • newt_checkbox_tree_get_selection — Description
    • newt_checkbox_tree_multi — Description
    • newt_checkbox_tree_set_current — Description
    • newt_checkbox_tree_set_entry_value — Description
    • newt_checkbox_tree_set_entry — Description
    • newt_checkbox_tree_set_width — Description
    • newt_checkbox_tree — Description
    • newt_checkbox — Description
    • newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
    • newt_cls — Description
    • newt_compact_button — Description
    • newt_component_add_callback — Description
    • newt_component_takes_focus — Description
    • newt_create_grid — Description
    • newt_cursor_off — Description
    • newt_cursor_on — Description
    • newt_delay — Description
    • newt_draw_form — Description
    • newt_draw_root_text — Displays the string text at the position indicated
    • newt_entry_get_value — Description
    • newt_entry_set_filter — Description
    • newt_entry_set_flags — Description
    • newt_entry_set — Description
    • newt_entry — Description
    • newt_finished — Uninitializes newt interface
    • newt_form_add_component — Adds a single component to the form
    • newt_form_add_components — Add several components to the form
    • newt_form_add_hot_key — Description
    • newt_form_destroy — Destroys a form
    • newt_form_get_current — Description
    • newt_form_run — Runs a form
    • newt_form_set_background — Description
    • newt_form_set_height — Description
    • newt_form_set_size — Description
    • newt_form_set_timer — Description
    • newt_form_set_width — Description
    • newt_form_watch_fd — Description
    • newt_form — Create a form
    • newt_get_screen_size — Fills in the passed references with the current size of the terminal
    • newt_grid_add_components_to_form — Description
    • newt_grid_basic_window — Description
    • newt_grid_free — Description
    • newt_grid_get_size — Description
    • newt_grid_h_close_stacked — Description
    • newt_grid_h_stacked — Description
    • newt_grid_place — Description
    • newt_grid_set_field — Description
    • newt_grid_simple_window — Description
    • newt_grid_v_close_stacked — Description
    • newt_grid_v_stacked — Description
    • newt_grid_wrapped_window_at — Description
    • newt_grid_wrapped_window — Description
    • newt_init — Initialize newt
    • newt_label_set_text — Description
    • newt_label — Description
    • newt_listbox_append_entry — Description
    • newt_listbox_clear_selection — Description
    • newt_listbox_clear — Description
    • newt_listbox_delete_entry — Description
    • newt_listbox_get_current — Description
    • newt_listbox_get_selection — Description
    • newt_listbox_insert_entry — Description
    • newt_listbox_item_count — Description
    • newt_listbox_select_item — Description
    • newt_listbox_set_current_by_key — Description
    • newt_listbox_set_current — Description
    • newt_listbox_set_data — Description
    • newt_listbox_set_entry — Description
    • newt_listbox_set_width — Description
    • newt_listbox — Description
    • newt_listitem_get_data — Description
    • newt_listitem_set — Description
    • newt_listitem — Description
    • newt_open_window — Open a window of the specified size and position
    • newt_pop_help_line — Replaces the current help line with the one from the stack
    • newt_pop_window — Removes the top window from the display
    • newt_push_help_line — Saves the current help line on a stack, and displays the new line
    • newt_radio_get_current — Description
    • newt_radiobutton — Description
    • newt_redraw_help_line — Description
    • newt_reflow_text — Description
    • newt_refresh — Updates modified portions of the screen
    • newt_resize_screen — Description
    • newt_resume — Resume using the newt interface after calling newt_suspend
    • newt_run_form — Runs a form
    • newt_scale_set — Description
    • newt_scale — Description
    • newt_scrollbar_set — Description
    • newt_set_help_callback — Description
    • newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key
    • newt_suspend — Tells newt to return the terminal to its initial state
    • newt_textbox_get_num_lines — Description
    • newt_textbox_reflowed — Description
    • newt_textbox_set_height — Description
    • newt_textbox_set_text — Description
    • newt_textbox — Description
    • newt_vertical_scrollbar — Description
    • newt_wait_for_key — Doesn't return until a key has been pressed
    • newt_win_choice — Description
    • newt_win_entries — Description
    • newt_win_menu — Description
    • newt_win_message — Description
    • newt_win_messagev — Description
    • newt_win_ternary — Description
Command Line Specific Extensions
Introduction
Command Line Specific Extensions


Oracle OCI8

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Testing
    • Runtime Configuration
  • Predefined Constants
  • Examples
  • Connection Handling
  • Supported Datatypes
  • OCI8 Functions
    • oci_bind_array_by_name — Binds PHP array to Oracle PL/SQL array by name
    • oci_bind_by_name — Binds a PHP variable to an Oracle placeholder
    • oci_cancel — Cancels reading from cursor
    • oci_close — Closes an Oracle connection
    • OCI-Collection->append — Appends element to the collection
    • OCI-Collection->assign — Assigns a value to the collection from another existing collection
    • OCI-Collection->assignElem — Assigns a value to the element of the collection
    • OCI-Collection->free — Frees the resources associated with the collection object
    • OCI-Collection->getElem — Returns value of the element
    • OCI-Collection->max — Returns the maximum number of elements in the collection
    • OCI-Collection->size — Returns size of the collection
    • OCI-Collection->trim — Trims elements from the end of the collection
    • oci_commit — Commits the outstanding database transaction
    • oci_connect — Connect to an Oracle database
    • oci_define_by_name — Associates a PHP variable with a column for query fetches
    • oci_error — Returns the last error found
    • oci_execute — Executes a statement
    • oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array
    • oci_fetch_array — Returns the next row from a query as an associative or numeric array
    • oci_fetch_assoc — Returns the next row from a query as an associative array
    • oci_fetch_object — Returns the next row from a query as an object
    • oci_fetch_row — Returns the next row from a query as a numeric array
    • oci_fetch — Fetches the next row from a query into internal buffers
    • oci_field_is_null — Checks if the field is NULL
    • oci_field_name — Returns the name of a field from the statement
    • oci_field_precision — Tell the precision of a field
    • oci_field_scale — Tell the scale of the field
    • oci_field_size — Returns field's size
    • oci_field_type_raw — Tell the raw Oracle data type of the field
    • oci_field_type — Returns field's data type
    • oci_free_statement — Frees all resources associated with statement or cursor
    • oci_internal_debug — Enables or disables internal debug output
    • OCI-Lob->append — Appends data from the large object to another large object
    • OCI-Lob->close — Closes LOB descriptor
    • oci_lob_copy — Copies large object
    • OCI-Lob->eof — Tests for end-of-file on a large object's descriptor
    • OCI-Lob->erase — Erases a specified portion of the internal LOB data
    • OCI-Lob->export — Exports LOB's contents to a file
    • OCI-Lob->flush — Flushes/writes buffer of the LOB to the server
    • OCI-Lob->free — Frees resources associated with the LOB descriptor
    • OCI-Lob->getBuffering — Returns current state of buffering for the large object
    • OCI-Lob->import — Imports file data to the LOB
    • oci_lob_is_equal — Compares two LOB/FILE locators for equality
    • OCI-Lob->load — Returns large object's contents
    • OCI-Lob->read — Reads part of the large object
    • OCI-Lob->rewind — Moves the internal pointer to the beginning of the large object
    • OCI-Lob->save — Saves data to the large object
    • OCI-Lob->saveFile — Alias of oci_lob_import
    • OCI-Lob->seek — Sets the internal pointer of the large object
    • OCI-Lob->setBuffering — Changes current state of buffering for the large object
    • OCI-Lob->size — Returns size of large object
    • OCI-Lob->tell — Returns current position of internal pointer of large object
    • OCI-Lob->truncate — Truncates large object
    • OCI-Lob->write — Writes data to the large object
    • OCI-Lob->writeTemporary — Writes temporary large object
    • OCI-Lob->writeToFile — Alias of oci_lob_export
    • oci_new_collection — Allocates new collection object
    • oci_new_connect — Connect to the Oracle server using a unique connection
    • oci_new_cursor — Allocates and returns a new cursor (statement handle)
    • oci_new_descriptor — Initializes a new empty LOB or FILE descriptor
    • oci_num_fields — Returns the number of result columns in a statement
    • oci_num_rows — Returns number of rows affected during statement execution
    • oci_parse — Prepares an Oracle statement for execution
    • oci_password_change — Changes password of Oracle's user
    • oci_pconnect — Connect to an Oracle database using a persistent connection
    • oci_result — Returns field's value from the fetched row
    • oci_rollback — Rolls back the outstanding database transaction
    • oci_server_version — Returns server version
    • oci_set_action — Sets the action name
    • oci_set_client_identifier — Sets the client identifier
    • oci_set_client_info — Sets the client information
    • oci_set_edition — Sets the database edition
    • oci_set_module_name — Sets the module name
    • oci_set_prefetch — Sets number of rows to be prefetched by queries
    • oci_statement_type — Returns the type of a statement
  • OCI8 Obsolete Aliases and Functions
    • ocibindbyname — Alias of oci_bind_by_name
    • ocicancel — Alias of oci_cancel
    • ocicloselob — Alias of
    • ocicollappend — Alias of
    • ocicollassign — Alias of
    • ocicollassignelem — Alias of
    • ocicollgetelem — Alias of
    • ocicollmax — Alias of
    • ocicollsize — Alias of
    • ocicolltrim — Alias of
    • ocicolumnisnull — Alias of oci_field_is_null
    • ocicolumnname — Alias of oci_field_name
    • ocicolumnprecision — Alias of oci_field_precision
    • ocicolumnscale — Alias of oci_field_scale
    • ocicolumnsize — Alias of oci_field_size
    • ocicolumntype — Alias of oci_field_type
    • ocicolumntyperaw — Alias of oci_field_type_raw
    • ocicommit — Alias of oci_commit
    • ocidefinebyname — Alias of oci_define_by_name
    • ocierror — Alias of oci_error
    • ociexecute — Alias of oci_execute
    • ocifetch — Alias of oci_fetch
    • ocifetchinto — Fetches the next row into an array (deprecated)
    • ocifetchstatement — Alias of oci_fetch_all
    • ocifreecollection — Alias of
    • ocifreecursor — Alias of oci_free_statement
    • ocifreedesc — Alias of
    • ocifreestatement — Alias of oci_free_statement
    • ociinternaldebug — Alias of oci_internal_debug
    • ociloadlob — Alias of
    • ocilogoff — Alias of oci_close
    • ocilogon — Alias of oci_connect
    • ocinewcollection — Alias of oci_new_collection
    • ocinewcursor — Alias of oci_new_cursor
    • ocinewdescriptor — Alias of oci_new_descriptor
    • ocinlogon — Alias of oci_new_connect
    • ocinumcols — Alias of oci_num_fields
    • ociparse — Alias of oci_parse
    • ociplogon — Alias of oci_pconnect
    • ociresult — Alias of oci_result
    • ocirollback — Alias of oci_rollback
    • ocirowcount — Alias of oci_num_rows
    • ocisavelob — Alias of
    • ocisavelobfile — Alias of
    • ociserverversion — Alias of oci_server_version
    • ocisetprefetch — Alias of oci_set_prefetch
    • ocistatementtype — Alias of oci_statement_type
    • ociwritelobtofile — Alias of
    • ociwritetemporarylob — Alias of
Notes
Introduction
Vendor Specific Database Extensions


OGG/Vorbis

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Context options
  • Examples
    • Examples on using the ogg:// wrapper.
KTaglib_ID3v2_AttachedPictureFrame::setType
Introduction
Audio Formats Manipulation


OpenAL Audio Bindings

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • OpenAL Functions
    • openal_buffer_create — Generate OpenAL buffer
    • openal_buffer_data — Load a buffer with data
    • openal_buffer_destroy — Destroys an OpenAL buffer
    • openal_buffer_get — Retrieve an OpenAL buffer property
    • openal_buffer_loadwav — Load a .wav file into a buffer
    • openal_context_create — Create an audio processing context
    • openal_context_current — Make the specified context current
    • openal_context_destroy — Destroys a context
    • openal_context_process — Process the specified context
    • openal_context_suspend — Suspend the specified context
    • openal_device_close — Close an OpenAL device
    • openal_device_open — Initialize the OpenAL audio layer
    • openal_listener_get — Retrieve a listener property
    • openal_listener_set — Set a listener property
    • openal_source_create — Generate a source resource
    • openal_source_destroy — Destroy a source resource
    • openal_source_get — Retrieve an OpenAL source property
    • openal_source_pause — Pause the source
    • openal_source_play — Start playing the source
    • openal_source_rewind — Rewind the source
    • openal_source_set — Set source property
    • openal_source_stop — Stop playing the source
    • openal_stream — Begin streaming on a source
Examples on using the ogg:// wrapper.
Introduction
Audio Formats Manipulation


OpenSSL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Purpose checking flags
    • Padding flags
    • Key types
    • PKCS7 Flags/Constants
    • Signature Algorithms
    • Ciphers
    • Version constants
    • Server Name Indication constants
  • Key/Certificate parameters
  • Certificate Verification
  • OpenSSL Functions
    • openssl_csr_export_to_file — Exports a CSR to a file
    • openssl_csr_export — Exports a CSR as a string
    • openssl_csr_get_public_key — Returns the public key of a CERT
    • openssl_csr_get_subject — Returns the subject of a CERT
    • openssl_csr_new — Generates a CSR
    • openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate
    • openssl_decrypt — Decrypts data
    • openssl_dh_compute_key — Computes shared secret for public value of remote DH key and local DH key
    • openssl_digest — Computes a digest
    • openssl_encrypt — Encrypts data
    • openssl_error_string — Return openSSL error message
    • openssl_free_key — Free key resource
    • openssl_get_cipher_methods — Gets available cipher methods
    • openssl_get_md_methods — Gets available digest methods
    • openssl_get_privatekey — Alias of openssl_pkey_get_private
    • openssl_get_publickey — Alias of openssl_pkey_get_public
    • openssl_open — Open sealed data
    • openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
    • openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.
    • openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array
    • openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message
    • openssl_pkcs7_encrypt — Encrypt an S/MIME message
    • openssl_pkcs7_sign — Sign an S/MIME message
    • openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message
    • openssl_pkey_export_to_file — Gets an exportable representation of a key into a file
    • openssl_pkey_export — Gets an exportable representation of a key into a string
    • openssl_pkey_free — Frees a private key
    • openssl_pkey_get_details — Returns an array with the key details
    • openssl_pkey_get_private — Get a private key
    • openssl_pkey_get_public — Extract public key from certificate and prepare it for use
    • openssl_pkey_new — Generates a new private key
    • openssl_private_decrypt — Decrypts data with private key
    • openssl_private_encrypt — Encrypts data with private key
    • openssl_public_decrypt — Decrypts data with public key
    • openssl_public_encrypt — Encrypts data with public key
    • openssl_random_pseudo_bytes — Generate a pseudo-random string
    • openssl_seal — Seal (encrypt) data
    • openssl_sign — Generate signature
    • openssl_verify — Verify signature
    • openssl_x509_check_private_key — Checks if a private key corresponds to a certificate
    • openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose
    • openssl_x509_export_to_file — Exports a certificate to file
    • openssl_x509_export — Exports a certificate as a string
    • openssl_x509_free — Free certificate resource
    • openssl_x509_parse — Parse an X509 certificate and return the information as an array
    • openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it
mhash
Introduction
Cryptography Extensions


Output Buffering Control

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Examples
  • Output Control Functions
    • flush — Flush the output buffer
    • ob_clean — Clean (erase) the output buffer
    • ob_end_clean — Clean (erase) the output buffer and turn off output buffering
    • ob_end_flush — Flush (send) the output buffer and turn off output buffering
    • ob_flush — Flush (send) the output buffer
    • ob_get_clean — Get current buffer contents and delete current output buffer
    • ob_get_contents — Return the contents of the output buffer
    • ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering
    • ob_get_length — Return the length of the output buffer
    • ob_get_level — Return the nesting level of the output buffering mechanism
    • ob_get_status — Get status of output buffers
    • ob_gzhandler — ob_start callback function to gzip output buffer
    • ob_implicit_flush — Turn implicit flush on/off
    • ob_list_handlers — List all output handlers in use
    • ob_start — Turn on output buffering
    • output_add_rewrite_var — Add URL rewriter values
    • output_reset_rewrite_vars — Reset URL rewriter values
overload
Introduction
Affecting PHP's Behaviour


Object property and method call overloading

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Overloading a PHP class
  • Object overloading Functions
    • overload — Enable property and method call overloading for a class
Creating large array in a function
Introduction
Affecting PHP's Behaviour


Ovrimos SQL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Connect to Ovrimos SQL Server and select from a system table
  • Ovrimos SQL Functions
    • ovrimos_close — Closes the connection to ovrimos
    • ovrimos_commit — Commits the transaction
    • ovrimos_connect — Connect to the specified database
    • ovrimos_cursor — Returns the name of the cursor
    • ovrimos_exec — Executes an SQL statement
    • ovrimos_execute — Executes a prepared SQL statement
    • ovrimos_fetch_into — Fetches a row from the result set
    • ovrimos_fetch_row — Fetches a row from the result set
    • ovrimos_field_len — Returns the length of the output column
    • ovrimos_field_name — Returns the output column name
    • ovrimos_field_num — Returns the (1-based) index of the output column
    • ovrimos_field_type — Returns the type of the output column
    • ovrimos_free_result — Frees the specified result_id
    • ovrimos_longreadlen — Specifies how many bytes are to be retrieved from long datatypes
    • ovrimos_num_fields — Returns the number of columns
    • ovrimos_num_rows — Returns the number of rows affected by update operations
    • ovrimos_prepare — Prepares an SQL statement
    • ovrimos_result_all — Prints the whole result set as an HTML table
    • ovrimos_result — Retrieves the output column
    • ovrimos_rollback — Rolls back the transaction
ociwritetemporarylob
Introduction
Vendor Specific Database Extensions


Paradox File Access

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Paradox Functions
    • px_close — Closes a paradox database
    • px_create_fp — Create a new paradox database
    • px_date2string — Converts a date into a string.
    • px_delete_record — Deletes record from paradox database
    • px_delete — Deletes resource of paradox database
    • px_get_field — Returns the specification of a single field
    • px_get_info — Return lots of information about a paradox file
    • px_get_parameter — Gets a parameter
    • px_get_record — Returns record of paradox database
    • px_get_schema — Returns the database schema
    • px_get_value — Gets a value
    • px_insert_record — Inserts record into paradox database
    • px_new — Create a new paradox object
    • px_numfields — Returns number of fields in a database
    • px_numrecords — Returns number of records in a database
    • px_open_fp — Open paradox database
    • px_put_record — Stores record into paradox database
    • px_retrieve_record — Returns record of paradox database
    • px_set_blob_file — Sets the file where blobs are read from
    • px_set_parameter — Sets a parameter
    • px_set_tablename — Sets the name of a table (deprecated)
    • px_set_targetencoding — Sets the encoding for character fields (deprecated)
    • px_set_value — Sets a value
    • px_timestamp2string — Converts the timestamp into a string.
    • px_update_record — Updates record in paradox database
ovrimos_rollback
Introduction
Vendor Specific Database Extensions


Parsekit

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Parsekit Functions
    • parsekit_compile_file — Compile a string of PHP code and return the resulting op array
    • parsekit_compile_string — Compile a string of PHP code and return the resulting op array
    • parsekit_func_arginfo — Return information regarding function argument(s)
usleep
Introduction
Other Basic Extensions


Process Control

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Process Control Example
  • PCNTL Functions
    • pcntl_alarm — Set an alarm clock for delivery of a signal
    • pcntl_exec — Executes specified program in current process space
    • pcntl_fork — Forks the currently running process
    • pcntl_getpriority — Get the priority of any process
    • pcntl_setpriority — Change the priority of any process
    • pcntl_signal_dispatch — Calls signal handlers for pending signals
    • pcntl_signal — Installs a signal handler
    • pcntl_sigprocmask — Sets and retrieves blocked signals
    • pcntl_sigtimedwait — Waits for signals, with a timeout
    • pcntl_sigwaitinfo — Waits for signals
    • pcntl_wait — Waits on or returns the status of a forked child
    • pcntl_waitpid — Waits on or returns the status of a forked child
    • pcntl_wexitstatus — Returns the return code of a terminated child
    • pcntl_wifexited — Checks if status code represents a normal exit
    • pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal
    • pcntl_wifstopped — Checks whether the child process is currently stopped
    • pcntl_wstopsig — Returns the signal which caused the child to stop
    • pcntl_wtermsig — Returns the signal which caused the child to terminate
event_set
Introduction
Process Control Extensions


PDF

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic Usage Examples
  • PDF Functions
    • PDF_activate_item — Activate structure element or other content item
    • PDF_add_annotation — Add annotation [deprecated]
    • PDF_add_bookmark — Add bookmark for current page [deprecated]
    • PDF_add_launchlink — Add launch annotation for current page [deprecated]
    • PDF_add_locallink — Add link annotation for current page [deprecated]
    • PDF_add_nameddest — Create named destination
    • PDF_add_note — Set annotation for current page [deprecated]
    • PDF_add_outline — Add bookmark for current page [deprecated]
    • PDF_add_pdflink — Add file link annotation for current page [deprecated]
    • PDF_add_table_cell — Add a cell to a new or existing table
    • PDF_add_textflow — Create Textflow or add text to existing Textflow
    • PDF_add_thumbnail — Add thumbnail for current page
    • PDF_add_weblink — Add weblink for current page [deprecated]
    • PDF_arc — Draw a counterclockwise circular arc segment
    • PDF_arcn — Draw a clockwise circular arc segment
    • PDF_attach_file — Add file attachment for current page [deprecated]
    • PDF_begin_document — Create new PDF file
    • PDF_begin_font — Start a Type 3 font definition
    • PDF_begin_glyph — Start glyph definition for Type 3 font
    • PDF_begin_item — Open structure element or other content item
    • PDF_begin_layer — Start layer
    • PDF_begin_page_ext — Start new page
    • PDF_begin_page — Start new page [deprecated]
    • PDF_begin_pattern — Start pattern definition
    • PDF_begin_template_ext — Start template definition
    • PDF_begin_template — Start template definition [deprecated]
    • PDF_circle — Draw a circle
    • PDF_clip — Clip to current path
    • PDF_close_image — Close image
    • PDF_close_pdi_page — Close the page handle
    • PDF_close_pdi — Close the input PDF document [deprecated]
    • PDF_close — Close pdf resource [deprecated]
    • PDF_closepath_fill_stroke — Close, fill and stroke current path
    • PDF_closepath_stroke — Close and stroke path
    • PDF_closepath — Close current path
    • PDF_concat — Concatenate a matrix to the CTM
    • PDF_continue_text — Output text in next line
    • PDF_create_3dview — Create 3D view
    • PDF_create_action — Create action for objects or events
    • PDF_create_annotation — Create rectangular annotation
    • PDF_create_bookmark — Create bookmark
    • PDF_create_field — Create form field
    • PDF_create_fieldgroup — Create form field group
    • PDF_create_gstate — Create graphics state object
    • PDF_create_pvf — Create PDFlib virtual file
    • PDF_create_textflow — Create textflow object
    • PDF_curveto — Draw Bezier curve
    • PDF_define_layer — Create layer definition
    • PDF_delete_pvf — Delete PDFlib virtual file
    • PDF_delete_table — Delete table object
    • PDF_delete_textflow — Delete textflow object
    • PDF_delete — Delete PDFlib object
    • PDF_encoding_set_char — Add glyph name and/or Unicode value
    • PDF_end_document — Close PDF file
    • PDF_end_font — Terminate Type 3 font definition
    • PDF_end_glyph — Terminate glyph definition for Type 3 font
    • PDF_end_item — Close structure element or other content item
    • PDF_end_layer — Deactivate all active layers
    • PDF_end_page_ext — Finish page
    • PDF_end_page — Finish page
    • PDF_end_pattern — Finish pattern
    • PDF_end_template — Finish template
    • PDF_endpath — End current path
    • PDF_fill_imageblock — Fill image block with variable data
    • PDF_fill_pdfblock — Fill PDF block with variable data
    • PDF_fill_stroke — Fill and stroke path
    • PDF_fill_textblock — Fill text block with variable data
    • PDF_fill — Fill current path
    • PDF_findfont — Prepare font for later use [deprecated]
    • PDF_fit_image — Place image or template
    • PDF_fit_pdi_page — Place imported PDF page
    • PDF_fit_table — Place table on page
    • PDF_fit_textflow — Format textflow in rectangular area
    • PDF_fit_textline — Place single line of text
    • PDF_get_apiname — Get name of unsuccessfull API function
    • PDF_get_buffer — Get PDF output buffer
    • PDF_get_errmsg — Get error text
    • PDF_get_errnum — Get error number
    • PDF_get_font — Get font [deprecated]
    • PDF_get_fontname — Get font name [deprecated]
    • PDF_get_fontsize — Font handling [deprecated]
    • PDF_get_image_height — Get image height [deprecated]
    • PDF_get_image_width — Get image width [deprecated]
    • PDF_get_majorversion — Get major version number [deprecated]
    • PDF_get_minorversion — Get minor version number [deprecated]
    • PDF_get_parameter — Get string parameter
    • PDF_get_pdi_parameter — Get PDI string parameter [deprecated]
    • PDF_get_pdi_value — Get PDI numerical parameter [deprecated]
    • PDF_get_value — Get numerical parameter
    • PDF_info_font — Query detailed information about a loaded font
    • PDF_info_matchbox — Query matchbox information
    • PDF_info_table — Retrieve table information
    • PDF_info_textflow — Query textflow state
    • PDF_info_textline — Perform textline formatting and query metrics
    • PDF_initgraphics — Reset graphic state
    • PDF_lineto — Draw a line
    • PDF_load_3ddata — Load 3D model
    • PDF_load_font — Search and prepare font
    • PDF_load_iccprofile — Search and prepare ICC profile
    • PDF_load_image — Open image file
    • PDF_makespotcolor — Make spot color
    • PDF_moveto — Set current point
    • PDF_new — Create PDFlib object
    • PDF_open_ccitt — Open raw CCITT image [deprecated]
    • PDF_open_file — Create PDF file [deprecated]
    • PDF_open_gif — Open GIF image [deprecated]
    • PDF_open_image_file — Read image from file [deprecated]
    • PDF_open_image — Use image data [deprecated]
    • PDF_open_jpeg — Open JPEG image [deprecated]
    • PDF_open_memory_image — Open image created with PHP's image functions [not supported]
    • PDF_open_pdi_page — Prepare a page
    • PDF_open_pdi — Open PDF file [deprecated]
    • PDF_open_tiff — Open TIFF image [deprecated]
    • PDF_pcos_get_number — Get value of pCOS path with type number or boolean
    • PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string
    • PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean
    • PDF_place_image — Place image on the page [deprecated]
    • PDF_place_pdi_page — Place PDF page [deprecated]
    • PDF_process_pdi — Process imported PDF document
    • PDF_rect — Draw rectangle
    • PDF_restore — Restore graphics state
    • PDF_resume_page — Resume page
    • PDF_rotate — Rotate coordinate system
    • PDF_save — Save graphics state
    • PDF_scale — Scale coordinate system
    • PDF_set_border_color — Set border color of annotations [deprecated]
    • PDF_set_border_dash — Set border dash style of annotations [deprecated]
    • PDF_set_border_style — Set border style of annotations [deprecated]
    • PDF_set_char_spacing — Set character spacing [deprecated]
    • PDF_set_duration — Set duration between pages [deprecated]
    • PDF_set_gstate — Activate graphics state object
    • PDF_set_horiz_scaling — Set horizontal text scaling [deprecated]
    • PDF_set_info_author — Fill the author document info field [deprecated]
    • PDF_set_info_creator — Fill the creator document info field [deprecated]
    • PDF_set_info_keywords — Fill the keywords document info field [deprecated]
    • PDF_set_info_subject — Fill the subject document info field [deprecated]
    • PDF_set_info_title — Fill the title document info field [deprecated]
    • PDF_set_info — Fill document info field
    • PDF_set_layer_dependency — Define relationships among layers
    • PDF_set_leading — Set distance between text lines [deprecated]
    • PDF_set_parameter — Set string parameter
    • PDF_set_text_matrix — Set text matrix [deprecated]
    • PDF_set_text_pos — Set text position
    • PDF_set_text_rendering — Determine text rendering [deprecated]
    • PDF_set_text_rise — Set text rise [deprecated]
    • PDF_set_value — Set numerical parameter
    • PDF_set_word_spacing — Set spacing between words [deprecated]
    • PDF_setcolor — Set fill and stroke color
    • PDF_setdash — Set simple dash pattern
    • PDF_setdashpattern — Set dash pattern
    • PDF_setflat — Set flatness
    • PDF_setfont — Set font
    • PDF_setgray_fill — Set fill color to gray [deprecated]
    • PDF_setgray_stroke — Set stroke color to gray [deprecated]
    • PDF_setgray — Set color to gray [deprecated]
    • PDF_setlinecap — Set linecap parameter
    • PDF_setlinejoin — Set linejoin parameter
    • PDF_setlinewidth — Set line width
    • PDF_setmatrix — Set current transformation matrix
    • PDF_setmiterlimit — Set miter limit
    • PDF_setpolydash — Set complicated dash pattern [deprecated]
    • PDF_setrgbcolor_fill — Set fill rgb color values [deprecated]
    • PDF_setrgbcolor_stroke — Set stroke rgb color values [deprecated]
    • PDF_setrgbcolor — Set fill and stroke rgb color values [deprecated]
    • PDF_shading_pattern — Define shading pattern
    • PDF_shading — Define blend
    • PDF_shfill — Fill area with shading
    • PDF_show_boxed — Output text in a box [deprecated]
    • PDF_show_xy — Output text at given position
    • PDF_show — Output text at current position
    • PDF_skew — Skew the coordinate system
    • PDF_stringwidth — Return width of text
    • PDF_stroke — Stroke path
    • PDF_suspend_page — Suspend page
    • PDF_translate — Set origin of coordinate system
    • PDF_utf16_to_utf8 — Convert string from UTF-16 to UTF-8
    • PDF_utf32_to_utf16 — Convert string from UTF-32 to UTF-16
    • PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16
SWFVideoStream->setDimension
Introduction
Non-Text MIME Output


PHP Data Objects

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Connections and Connection management
  • Transactions and auto-commit
  • Prepared statements and stored procedures
  • Errors and error handling
  • Large Objects (LOBs)
  • PDO — The PDO class
    • PDO::beginTransaction — Initiates a transaction
    • PDO::commit — Commits a transaction
    • PDO::__construct — Creates a PDO instance representing a connection to a database
    • PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
    • PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
    • PDO::exec — Execute an SQL statement and return the number of affected rows
    • PDO::getAttribute — Retrieve a database connection attribute
    • PDO::getAvailableDrivers — Return an array of available PDO drivers
    • PDO::lastInsertId — Returns the ID of the last inserted row or sequence value
    • PDO::prepare — Prepares a statement for execution and returns a statement object
    • PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object
    • PDO::quote — Quotes a string for use in a query.
    • PDO::rollBack — Rolls back a transaction
    • PDO::setAttribute — Set an attribute
  • PDOStatement — The PDOStatement class
    • PDOStatement->bindColumn — Bind a column to a PHP variable
    • PDOStatement->bindParam — Binds a parameter to the specified variable name
    • PDOStatement->bindValue — Binds a value to a parameter
    • PDOStatement->closeCursor — Closes the cursor, enabling the statement to be executed again.
    • PDOStatement->columnCount — Returns the number of columns in the result set
    • PDOStatement->debugDumpParams — Dump a SQL prepared command
    • PDOStatement->errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle
    • PDOStatement->errorInfo — Fetch extended error information associated with the last operation on the statement handle
    • PDOStatement->execute — Executes a prepared statement
    • PDOStatement->fetch — Fetches the next row from a result set
    • PDOStatement->fetchAll — Returns an array containing all of the result set rows
    • PDOStatement->fetchColumn — Returns a single column from the next row of a result set
    • PDOStatement->fetchObject — Fetches the next row and returns it as an object.
    • PDOStatement->getAttribute — Retrieve a statement attribute
    • PDOStatement->getColumnMeta — Returns metadata for a column in a result set
    • PDOStatement->nextRowset — Advances to the next rowset in a multi-rowset statement handle
    • PDOStatement->rowCount — Returns the number of rows affected by the last SQL statement
    • PDOStatement->setAttribute — Set a statement attribute
    • PDOStatement->setFetchMode — Set the default fetch mode for this statement
  • PDOException — The PDOException class
  • PDO Drivers
    • MS SQL Server (PDO) — Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
    • Firebird/Interbase (PDO) — Firebird/Interbase Functions (PDO_FIREBIRD)
    • IBM (PDO) — IBM Functions (PDO_IBM)
    • Informix (PDO) — Informix Functions (PDO_INFORMIX)
    • MySQL (PDO) — MySQL Functions (PDO_MYSQL)
    • Oracle (PDO) — Oracle Functions (PDO_OCI)
    • ODBC and DB2 (PDO) — ODBC and DB2 Functions (PDO_ODBC)
    • PostgreSQL (PDO) — PostgreSQL Functions (PDO_PGSQL)
    • SQLite (PDO) — SQLite Functions (PDO_SQLITE)
    • Driver 4D for PDO — Driver 4D for PDO (PDO_4D)
odbc_tables
Introduction
Abstraction Layers


PostgreSQL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • PostgreSQL extension overview example
  • PostgreSQL Functions
    • pg_affected_rows — Returns number of affected records (tuples)
    • pg_cancel_query — Cancel an asynchronous query
    • pg_client_encoding — Gets the client encoding
    • pg_close — Closes a PostgreSQL connection
    • pg_connect — Open a PostgreSQL connection
    • pg_connection_busy — Get connection is busy or not
    • pg_connection_reset — Reset connection (reconnect)
    • pg_connection_status — Get connection status
    • pg_convert — Convert associative array values into suitable for SQL statement
    • pg_copy_from — Insert records into a table from an array
    • pg_copy_to — Copy a table to an array
    • pg_dbname — Get the database name
    • pg_delete — Deletes records
    • pg_end_copy — Sync with PostgreSQL backend
    • pg_escape_bytea — Escape a string for insertion into a bytea field
    • pg_escape_string — Escape a string for insertion into a text field
    • pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result.
    • pg_fetch_all_columns — Fetches all rows in a particular result column as an array
    • pg_fetch_all — Fetches all rows from a result as an array
    • pg_fetch_array — Fetch a row as an array
    • pg_fetch_assoc — Fetch a row as an associative array
    • pg_fetch_object — Fetch a row as an object
    • pg_fetch_result — Returns values from a result resource
    • pg_fetch_row — Get a row as an enumerated array
    • pg_field_is_null — Test if a field is SQL NULL
    • pg_field_name — Returns the name of a field
    • pg_field_num — Returns the field number of the named field
    • pg_field_prtlen — Returns the printed length
    • pg_field_size — Returns the internal storage size of the named field
    • pg_field_table — Returns the name or oid of the tables field
    • pg_field_type_oid — Returns the type ID (OID) for the corresponding field number
    • pg_field_type — Returns the type name for the corresponding field number
    • pg_free_result — Free result memory
    • pg_get_notify — Gets SQL NOTIFY message
    • pg_get_pid — Gets the backend's process ID
    • pg_get_result — Get asynchronous query result
    • pg_host — Returns the host name associated with the connection
    • pg_insert — Insert array into table
    • pg_last_error — Get the last error message string of a connection
    • pg_last_notice — Returns the last notice message from PostgreSQL server
    • pg_last_oid — Returns the last row's OID
    • pg_lo_close — Close a large object
    • pg_lo_create — Create a large object
    • pg_lo_export — Export a large object to file
    • pg_lo_import — Import a large object from file
    • pg_lo_open — Open a large object
    • pg_lo_read_all — Reads an entire large object and send straight to browser
    • pg_lo_read — Read a large object
    • pg_lo_seek — Seeks position within a large object
    • pg_lo_tell — Returns current seek position a of large object
    • pg_lo_unlink — Delete a large object
    • pg_lo_write — Write to a large object
    • pg_meta_data — Get meta data for table
    • pg_num_fields — Returns the number of fields in a result
    • pg_num_rows — Returns the number of rows in a result
    • pg_options — Get the options associated with the connection
    • pg_parameter_status — Looks up a current parameter setting of the server.
    • pg_pconnect — Open a persistent PostgreSQL connection
    • pg_ping — Ping database connection
    • pg_port — Return the port number associated with the connection
    • pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.
    • pg_put_line — Send a NULL-terminated string to PostgreSQL backend
    • pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
    • pg_query — Execute a query
    • pg_result_error_field — Returns an individual field of an error report.
    • pg_result_error — Get error message associated with result
    • pg_result_seek — Set internal row offset in result resource
    • pg_result_status — Get status of query result
    • pg_select — Select records
    • pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
    • pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion.
    • pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s).
    • pg_send_query — Sends asynchronous query
    • pg_set_client_encoding — Set the client encoding
    • pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error.
    • pg_trace — Enable tracing a PostgreSQL connection
    • pg_transaction_status — Returns the current in-transaction status of the server.
    • pg_tty — Return the TTY name associated with the connection
    • pg_unescape_bytea — Unescape binary for bytea type
    • pg_untrace — Disable tracing of a PostgreSQL connection
    • pg_update — Update table
    • pg_version — Returns an array with client, protocol and server version (when available)
px_update_record
Introduction
Vendor Specific Database Extensions


Phar

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Using Phar Archives
    • Using Phar Archives: Introduction
    • Using Phar Archives: the phar stream wrapper
    • Using Phar Archives: the Phar and PharData class
  • Creating Phar Archives
    • Creating Phar Archives: Introduction
  • What makes a phar a phar and not a tar or a zip?
    • Ingredients of all Phar archives, independent of file format
    • Phar file stub
    • Head-to-head comparison of Phar, Tar and Zip
    • Tar-based phars
    • Zip-based phars
    • Phar File Format
    • Global Phar bitmapped flags
    • Phar manifest file entry definition
    • Phar Signature format
  • Phar — The Phar class
    • Phar::addEmptyDir — Add an empty directory to the phar archive
    • Phar::addFile — Add a file from the filesystem to the phar archive
    • Phar::addFromString — Add a file from the filesystem to the phar archive
    • Phar::apiVersion — Returns the api version
    • Phar::buildFromDirectory — Construct a phar archive from the files within a directory.
    • Phar::buildFromIterator — Construct a phar archive from an iterator.
    • Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
    • Phar::canWrite — Returns whether phar extension supports writing and creating phars
    • Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
    • Phar::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression
    • Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip compression
    • Phar::compressFiles — Compresses all files in the current Phar archive
    • Phar::__construct — Construct a Phar archive object
    • Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
    • Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
    • Phar::copy — Copy a file internal to the phar archive to another new file within the phar
    • Phar::count — Returns the number of entries (files) in the Phar archive
    • Phar::createDefaultStub — Create a phar-file format specific stub
    • Phar::decompress — Decompresses the entire Phar archive
    • Phar::decompressFiles — Decompresses all files in the current Phar archive
    • Phar::delMetadata — Deletes the global metadata of the phar
    • Phar::delete — Delete a file within a phar archive
    • Phar::extractTo — Extract the contents of a phar archive to a directory
    • Phar::getMetaData — Returns phar archive meta-data
    • Phar::getModified — Return whether phar was modified
    • Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
    • Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
    • Phar::getSupportedCompression — Return array of supported compression algorithms
    • Phar::getSupportedSignatures — Return array of supported signature types
    • Phar::getVersion — Return version info of Phar archive
    • Phar::hasMetaData — Returns whether phar has global meta-data
    • Phar::interceptFileFuncs — instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
    • Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
    • Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
    • Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
    • Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
    • Phar::isWritable — Returns true if the phar archive can be modified
    • Phar::loadPhar — Loads any phar archive with an alias
    • Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
    • Phar::mount — Mount an external path or file to a virtual location within the phar archive
    • Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
    • Phar::offsetExists — determines whether a file exists in the phar
    • Phar::offsetGet — Gets a PharFileInfo object for a specific file
    • Phar::offsetSet — set the contents of an internal file to those of an external file
    • Phar::offsetUnset — remove a file from a phar
    • Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
    • Phar::setAlias — Set the alias for the Phar archive
    • Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
    • Phar::setMetadata — Sets phar archive meta-data
    • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it.
    • Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
    • Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
    • Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
    • Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive
    • Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
    • Phar::webPhar — mapPhar for web-based phars. front controller for web applications
  • PharData — The PharData class
    • PharData::addEmptyDir — Add an empty directory to the tar/zip archive
    • PharData::addFile — Add a file from the filesystem to the tar/zip archive
    • PharData::addFromString — Add a file from the filesystem to the tar/zip archive
    • PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory.
    • PharData::buildFromIterator — Construct a tar or zip archive from an iterator.
    • PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
    • PharData::compressFiles — Compresses all files in the current tar/zip archive
    • PharData::__construct — Construct a non-executable tar or zip archive object
    • PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
    • PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
    • PharData::copy — Copy a file internal to the phar archive to another new file within the phar
    • PharData::decompress — Decompresses the entire Phar archive
    • PharData::decompressFiles — Decompresses all files in the current zip archive
    • PharData::delMetadata — Deletes the global metadata of a zip archive
    • PharData::delete — Delete a file within a tar/zip archive
    • PharData::extractTo — Extract the contents of a tar/zip archive to a directory
    • PharData::isWritable — Returns true if the tar/zip archive can be modified
    • PharData::offsetSet — set the contents of a file within the tar/zip to those of an external file or string
    • PharData::offsetUnset — remove a file from a tar/zip archive
    • PharData::setAlias — dummy function (Phar::setAlias is not valid for PharData)
    • PharData::setDefaultStub — dummy function (Phar::setDefaultStub is not valid for PharData)
    • Phar::setMetadata — Sets phar archive meta-data
    • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it. The
    • PharData::setStub — dummy function (Phar::setStub is not valid for PharData)
  • PharFileInfo — The PharFileInfo class
    • PharFileInfo::chmod — Sets file-specific permission bits
    • PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
    • PharFileInfo::__construct — Construct a Phar entry object
    • PharFileInfo::decompress — Decompresses the current Phar entry within the phar
    • PharFileInfo::delMetadata — Deletes the metadata of the entry
    • PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
    • PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
    • PharFileInfo::getMetaData — Returns file-specific meta-data saved with a file
    • PharFileInfo::getPharFlags — Returns the Phar file entry flags
    • PharFileInfo::hasMetadata — Returns the metadata of the entry
    • PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
    • PharFileInfo::isCompressed — Returns whether the entry is compressed
    • PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2
    • PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz
    • PharFileInfo::setCompressedBZIP2 — Compresses the current Phar entry within the phar using Bzip2 compression
    • PharFileInfo::setCompressedGZ — Compresses the current Phar entry within the phar using gz compression
    • PharFileInfo::setMetaData — Sets file-specific meta-data saved with a file
    • PharFileInfo::setUncompressed — Uncompresses the current Phar entry within the phar, if it is compressed
  • PharException — The PharException class
    • PharException — The PharException class provides a phar-specific exception class for try/catch blocks.
lzf_optimized_for
Introduction
Compression and Archive Extensions


POSIX

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • POSIX Functions
    • posix_access — Determine accessibility of a file
    • posix_ctermid — Get path name of controlling terminal
    • posix_errno — Alias of posix_get_last_error
    • posix_get_last_error — Retrieve the error number set by the last posix function that failed
    • posix_getcwd — Pathname of current directory
    • posix_getegid — Return the effective group ID of the current process
    • posix_geteuid — Return the effective user ID of the current process
    • posix_getgid — Return the real group ID of the current process
    • posix_getgrgid — Return info about a group by group id
    • posix_getgrnam — Return info about a group by name
    • posix_getgroups — Return the group set of the current process
    • posix_getlogin — Return login name
    • posix_getpgid — Get process group id for job control
    • posix_getpgrp — Return the current process group identifier
    • posix_getpid — Return the current process identifier
    • posix_getppid — Return the parent process identifier
    • posix_getpwnam — Return info about a user by username
    • posix_getpwuid — Return info about a user by user id
    • posix_getrlimit — Return info about system resource limits
    • posix_getsid — Get the current sid of the process
    • posix_getuid — Return the real user ID of the current process
    • posix_initgroups — Calculate the group access list
    • posix_isatty — Determine if a file descriptor is an interactive terminal
    • posix_kill — Send a signal to a process
    • posix_mkfifo — Create a fifo special file (a named pipe)
    • posix_mknod — Create a special or ordinary file (POSIX.1)
    • posix_setegid — Set the effective GID of the current process
    • posix_seteuid — Set the effective UID of the current process
    • posix_setgid — Set the GID of the current process
    • posix_setpgid — Set process group id for job control
    • posix_setsid — Make the current process a session leader
    • posix_setuid — Set the UID of the current process
    • posix_strerror — Retrieve the system error message associated with the given errno
    • posix_times — Get process times
    • posix_ttyname — Determine terminal device name
    • posix_uname — Get system name
pcntl_wtermsig
Introduction
Process Control Extensions


PostScript document creation

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • PS Functions
    • ps_add_bookmark — Add bookmark to current page
    • ps_add_launchlink — Adds link which launches file
    • ps_add_locallink — Adds link to a page in the same document
    • ps_add_note — Adds note to current page
    • ps_add_pdflink — Adds link to a page in a second pdf document
    • ps_add_weblink — Adds link to a web location
    • ps_arc — Draws an arc counterclockwise
    • ps_arcn — Draws an arc clockwise
    • ps_begin_page — Start a new page
    • ps_begin_pattern — Start a new pattern
    • ps_begin_template — Start a new template
    • ps_circle — Draws a circle
    • ps_clip — Clips drawing to current path
    • ps_close_image — Closes image and frees memory
    • ps_close — Closes a PostScript document
    • ps_closepath_stroke — Closes and strokes path
    • ps_closepath — Closes path
    • ps_continue_text — Continue text in next line
    • ps_curveto — Draws a curve
    • ps_delete — Deletes all resources of a PostScript document
    • ps_end_page — End a page
    • ps_end_pattern — End a pattern
    • ps_end_template — End a template
    • ps_fill_stroke — Fills and strokes the current path
    • ps_fill — Fills the current path
    • ps_findfont — Loads a font
    • ps_get_buffer — Fetches the full buffer containig the generated PS data
    • ps_get_parameter — Gets certain parameters
    • ps_get_value — Gets certain values
    • ps_hyphenate — Hyphenates a word
    • ps_include_file — Reads an external file with raw PostScript code
    • ps_lineto — Draws a line
    • ps_makespotcolor — Create spot color
    • ps_moveto — Sets current point
    • ps_new — Creates a new PostScript document object
    • ps_open_file — Opens a file for output
    • ps_open_image_file — Opens image from file
    • ps_open_image — Reads an image for later placement
    • ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document
    • ps_place_image — Places image on the page
    • ps_rect — Draws a rectangle
    • ps_restore — Restore previously save context
    • ps_rotate — Sets rotation factor
    • ps_save — Save current context
    • ps_scale — Sets scaling factor
    • ps_set_border_color — Sets color of border for annotations
    • ps_set_border_dash — Sets length of dashes for border of annotations
    • ps_set_border_style — Sets border style of annotations
    • ps_set_info — Sets information fields of document
    • ps_set_parameter — Sets certain parameters
    • ps_set_text_pos — Sets position for text output
    • ps_set_value — Sets certain values
    • ps_setcolor — Sets current color
    • ps_setdash — Sets appearance of a dashed line
    • ps_setflat — Sets flatness
    • ps_setfont — Sets font to use for following output
    • ps_setgray — Sets gray value
    • ps_setlinecap — Sets appearance of line ends
    • ps_setlinejoin — Sets how contected lines are joined
    • ps_setlinewidth — Sets width of a line
    • ps_setmiterlimit — Sets the miter limit
    • ps_setoverprintmode — Sets overprint mode
    • ps_setpolydash — Sets appearance of a dashed line
    • ps_shading_pattern — Creates a pattern based on a shading
    • ps_shading — Creates a shading for later use
    • ps_shfill — Fills an area with a shading
    • ps_show_boxed — Output text in a box
    • ps_show_xy2 — Output text at position
    • ps_show_xy — Output text at given position
    • ps_show2 — Output a text at current position
    • ps_show — Output text
    • ps_string_geometry — Gets geometry of a string
    • ps_stringwidth — Gets width of a string
    • ps_stroke — Draws the current path
    • ps_symbol_name — Gets name of a glyph
    • ps_symbol_width — Gets width of a glyph
    • ps_symbol — Output a glyph
    • ps_translate — Sets translation
PDF_utf8_to_utf16
Introduction
Non-Text MIME Output


Pspell

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Pspell Functions
    • pspell_add_to_personal — Add the word to a personal wordlist
    • pspell_add_to_session — Add the word to the wordlist in the current session
    • pspell_check — Check a word
    • pspell_clear_session — Clear the current session
    • pspell_config_create — Create a config used to open a dictionary
    • pspell_config_data_dir — location of language data files
    • pspell_config_dict_dir — Location of the main word list
    • pspell_config_ignore — Ignore words less than N characters long
    • pspell_config_mode — Change the mode number of suggestions returned
    • pspell_config_personal — Set a file that contains personal wordlist
    • pspell_config_repl — Set a file that contains replacement pairs
    • pspell_config_runtogether — Consider run-together words as valid compounds
    • pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist
    • pspell_new_config — Load a new dictionary with settings based on a given config
    • pspell_new_personal — Load a new dictionary with personal wordlist
    • pspell_new — Load a new dictionary
    • pspell_save_wordlist — Save the personal wordlist to a file
    • pspell_store_replacement — Store a replacement pair for a word
    • pspell_suggest — Suggest spellings of a word
mb_substr
Introduction
Human Language and Character Encoding Support


Radius

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Radius Functions
    • radius_acct_open — Creates a Radius handle for accounting
    • radius_add_server — Adds a server
    • radius_auth_open — Creates a Radius handle for authentication
    • radius_close — Frees all ressources
    • radius_config — Causes the library to read the given configuration file
    • radius_create_request — Create accounting or authentication request
    • radius_cvt_addr — Converts raw data to IP-Address
    • radius_cvt_int — Converts raw data to integer
    • radius_cvt_string — Converts raw data to string
    • radius_demangle_mppe_key — Derives mppe-keys from mangled data
    • radius_demangle — Demangles data
    • radius_get_attr — Extracts an attribute
    • radius_get_vendor_attr — Extracts a vendor specific attribute
    • radius_put_addr — Attaches an IP-Address attribute
    • radius_put_attr — Attaches a binary attribute
    • radius_put_int — Attaches an integer attribute
    • radius_put_string — Attaches a string attribute
    • radius_put_vendor_addr — Attaches a vendor specific IP-Address attribute
    • radius_put_vendor_attr — Attaches a vendor specific binary attribute
    • radius_put_vendor_int — Attaches a vendor specific integer attribute
    • radius_put_vendor_string — Attaches a vendor specific string attribute
    • radius_request_authenticator — Returns the request authenticator
    • radius_send_request — Sends the request and waites for a reply
    • radius_server_secret — Returns the shared secret
    • radius_strerror — Returns an error message
kadm5_modify_principal
Introduction
Authentication Services


Rar Archiving

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • RarArchive — The RarArchive class
    • RarArchive::close — Close RAR archive and free all resources.
    • RarArchive::getComment — Get comment text from the RAR archive.
    • RarArchive::getEntry — Get entry object from the RAR archive.
    • RarArchive::isSolid — Check whether the RAR archive is solid.
    • RarArchive::list — Get entries full list from the RAR archive.
    • RarArchive::open — Open RAR archive.
    • RarArchive::__toString — Get text representation.
  • RarEntry — The RarEntry class
    • RarEntry::extract — Extract entry from the archive.
    • RarEntry::getAttr — Get attributes of the entry.
    • RarEntry::getCrc — Get CRC of the entry.
    • RarEntry::getFileTime — Get entry last modification time.
    • RarEntry::getHostOs — Get entry host OS.
    • RarEntry::getMethod — Get pack method of the entry.
    • RarEntry::getName — Get name of the entry.
    • RarEntry::getPackedSize — Get packed size of the entry.
    • RarEntry::getStream — Get file handler for entry.
    • RarEntry::getUnpackedSize — Get unpacked size of the entry.
    • RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry.
    • RarEntry::isDirectory — Test whether an entry represents a directory.
    • RarEntry::isEncrypted — Test whether an entry is encrypted.
    • RarEntry::__toString — Get text representation of entry.
  • RarException — The RarException class
    • RarException::isUsingExceptions — Check whether error handling with exceptions is in use.
    • RarException::setUsingExceptions — Activate and deactivate error handling with exceptions.
PharException
Introduction
Compression and Archive Extensions


GNU Readline

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Readline Functions
    • readline_add_history — Adds a line to the history
    • readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately
    • readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings
    • readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received
    • readline_clear_history — Clears the history
    • readline_completion_function — Registers a completion function
    • readline_info — Gets/sets various internal readline variables
    • readline_list_history — Lists the history
    • readline_on_new_line — Inform readline that the cursor has moved to a new line
    • readline_read_history — Reads the history
    • readline_redisplay — Redraws the display
    • readline_write_history — Writes the history
    • readline — Reads a line
ncurses_wvline
Introduction
Command Line Specific Extensions


GNU Recode

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Recode Functions
    • recode_file — Recode from file to file according to recode request
    • recode_string — Recode a string according to a recode request
    • recode — Alias of recode_string
pspell_suggest
Introduction
Human Language and Character Encoding Support


RPM Header Reading

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • RPM Reader Functions
    • rpm_close — Closes an RPM file
    • rpm_get_tag — Retrieves a header tag from an RPM file
    • rpm_is_valid — Tests a filename for validity as an RPM file
    • rpm_open — Opens an RPM file
    • rpm_version — Returns a string representing the current version of the rpmreader extension
ps_translate
Introduction
Non-Text MIME Output


runkit

  • Introduction
  • Predefined Constants
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • runkit Functions
    • Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine
    • Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class
    • runkit_class_adopt — Convert a base class to an inherited class, add ancestral methods when appropriate
    • runkit_class_emancipate — Convert an inherited class to a base class, removes any method whose scope is ancestral
    • runkit_constant_add — Similar to define(), but allows defining in class definitions as well
    • runkit_constant_redefine — Redefine an already defined constant
    • runkit_constant_remove — Remove/Delete an already defined constant
    • runkit_function_add — Add a new function, similar to create_function
    • runkit_function_copy — Copy a function to a new function name
    • runkit_function_redefine — Replace a function definition with a new implementation
    • runkit_function_remove — Remove a function definition
    • runkit_function_rename — Change a function's name
    • runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate
    • runkit_lint_file — Check the PHP syntax of the specified file
    • runkit_lint — Check the PHP syntax of the specified php code
    • runkit_method_add — Dynamically adds a new method to a given class
    • runkit_method_copy — Copies a method from class to another
    • runkit_method_redefine — Dynamically changes the code of the given method
    • runkit_method_remove — Dynamically removes the given method
    • runkit_method_rename — Dynamically changes the name of the given method
    • runkit_return_value_used — Determines if the current functions return value will be used
    • runkit_sandbox_output_handler — Specify a function to capture and/or process output from a runkit sandbox
    • runkit_superglobals — Return numerically indexed array of registered superglobals
output_reset_rewrite_vars
Introduction
Affecting PHP's Behaviour


Break the silence operator

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
    • Example that shows the effect of scream
runkit_superglobals
Introduction
Affecting PHP's Behaviour


Semaphore, Shared Memory and IPC

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Semaphore Functions
    • ftok — Convert a pathname and a project identifier to a System V IPC key
    • msg_get_queue — Create or attach to a message queue
    • msg_queue_exists — Check whether a message queue exists
    • msg_receive — Receive a message from a message queue
    • msg_remove_queue — Destroy a message queue
    • msg_send — Send a message to a message queue
    • msg_set_queue — Set information in the message queue data structure
    • msg_stat_queue — Returns information from the message queue data structure
    • sem_acquire — Acquire a semaphore
    • sem_get — Get a semaphore id
    • sem_release — Release a semaphore
    • sem_remove — Remove a semaphore
    • shm_attach — Creates or open a shared memory segment
    • shm_detach — Disconnects from shared memory segment
    • shm_get_var — Returns a variable from shared memory
    • shm_has_var — Check whether a specific entry exists
    • shm_put_var — Inserts or updates a variable in shared memory
    • shm_remove_var — Removes a variable from shared memory
    • shm_remove — Removes shared memory from Unix systems
posix_uname
Introduction
Process Control Extensions


Shared Memory

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Shared Memory Operations Overview
  • Shared Memory Functions
    • shmop_close — Close shared memory block
    • shmop_delete — Delete shared memory block
    • shmop_open — Create or open shared memory block
    • shmop_read — Read data from shared memory block
    • shmop_size — Get size of shared memory block
    • shmop_write — Write data into shared memory block
shm_remove
Introduction
Process Control Extensions


Standard PHP Library (SPL)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Datastructures
    • SplDoublyLinkedList — The SplDoublyLinkedList class
    • SplStack — The SplStack class
    • SplQueue — The SplQueue class
    • SplHeap — The SplHeap class
    • SplMaxHeap — The SplMaxHeap class
    • SplMinHeap — The SplMinHeap class
    • SplPriorityQueue — The SplPriorityQueue class
    • SplFixedArray — The SplFixedArray class
    • SplObjectStorage — The SplObjectStorage class
  • Iterators
    • AppendIterator — The AppendIterator class
    • ArrayIterator — The ArrayIterator class
    • CachingIterator — The CachingIterator class
    • DirectoryIterator — The DirectoryIterator class
    • EmptyIterator — The EmptyIterator class
    • FilesystemIterator — The FilesystemIterator class
    • FilterIterator — The FilterIterator class
    • GlobIterator — The GlobIterator class
    • InfiniteIterator — The InfiniteIterator class
    • IteratorIterator — The IteratorIterator class
    • LimitIterator — The LimitIterator class
    • MultipleIterator — The MultipleIterator class
    • NoRewindIterator — The NoRewindIterator class
    • ParentIterator — The ParentIterator class
    • RecursiveArrayIterator — The RecursiveArrayIterator class
    • RecursiveCachingIterator — The RecursiveCachingIterator class
    • RecursiveDirectoryIterator — The RecursiveDirectoryIterator class
    • RecursiveFilterIterator — The RecursiveFilterIterator class
    • RecursiveIteratorIterator — The RecursiveIteratorIterator class
    • RecursiveRegexIterator — The RecursiveRegexIterator class
    • RecursiveTreeIterator — The RecursiveTreeIterator class
    • RegexIterator — The RegexIterator class
    • SimpleXMLIterator — The SimpleXMLIterator class
  • Interfaces
    • Countable — The Countable interface
    • OuterIterator — The OuterIterator interface
    • RecursiveIterator — The RecursiveIterator interface
    • SeekableIterator — The SeekableIterator interface
  • Exceptions
    • BadFunctionCallException — The BadFunctionCallException class
    • BadMethodCallException — The BadMethodCallException class
    • DomainException — The DomainException class
    • InvalidArgumentException — The InvalidArgumentException class
    • LengthException — The LengthException class
    • LogicException — The LogicException class
    • OutOfBoundsException — The OutOfBoundsException class
    • OutOfRangeException — The OutOfRangeException class
    • OverflowException — The OverflowException class
    • RangeException — The RangeException class
    • RuntimeException — The RuntimeException class
    • UnderflowException — The UnderflowException class
    • UnexpectedValueException — The UnexpectedValueException class
  • SPL Functions
    • class_implements — Return the interfaces which are implemented by the given class
    • class_parents — Return the parent classes of the given class
    • iterator_apply — Call a function for every element in an iterator
    • iterator_count — Count the elements in an iterator
    • iterator_to_array — Copy the iterator into an array
    • spl_autoload_call — Try all registered __autoload() function to load the requested class
    • spl_autoload_extensions — Register and return default file extensions for spl_autoload
    • spl_autoload_functions — Return all registered __autoload() functions
    • spl_autoload_register — Register given function as __autoload() implementation
    • spl_autoload_unregister — Unregister given function as __autoload() implementation
    • spl_autoload — Default implementation for __autoload()
    • spl_classes — Return available SPL classes
    • spl_object_hash — Return hash id for given object
  • File Handling
    • SplFileInfo — The SplFileInfo class
    • SplFileObject — The SplFileObject class
    • SplTempFileObject — The SplTempFileObject class
  • Miscellaneous Classes and Interfaces
    • ArrayObject — The ArrayObject class
    • SplObserver — The SplObserver interface
    • SplSubject — The SplSubject interface
parsekit_func_arginfo
Introduction
Other Basic Extensions


SPPLUS Payment System

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SPPLUS Functions
    • calcul_hmac — Obtain a hmac key (needs 8 arguments)
    • calculhmac — Obtain a hmac key (needs 2 arguments)
    • nthmac — Obtain a nthmac key (needs 2 arguments)
    • signeurlpaiement — Obtain the payment url (needs 2 arguments)
m_verifysslcert
Introduction
Credit Card Processing


SQLite

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SQLite Functions
    • sqlite_array_query — Execute a query against a given database and returns an array
    • sqlite_busy_timeout — Set busy timeout duration, or disable busy handlers
    • sqlite_changes — Returns the number of rows that were changed by the most recent SQL statement
    • sqlite_close — Closes an open SQLite database
    • sqlite_column — Fetches a column from the current row of a result set
    • sqlite_create_aggregate — Register an aggregating UDF for use in SQL statements
    • sqlite_create_function — Registers a "regular" User Defined Function for use in SQL statements
    • sqlite_current — Fetches the current row from a result set as an array
    • sqlite_error_string — Returns the textual description of an error code
    • sqlite_escape_string — Escapes a string for use as a query parameter
    • sqlite_exec — Executes a result-less query against a given database
    • sqlite_factory — Opens a SQLite database and returns a SQLiteDatabase object
    • sqlite_fetch_all — Fetches all rows from a result set as an array of arrays
    • sqlite_fetch_array — Fetches the next row from a result set as an array
    • sqlite_fetch_column_types — Return an array of column types from a particular table
    • sqlite_fetch_object — Fetches the next row from a result set as an object
    • sqlite_fetch_single — Fetches the first column of a result set as a string
    • sqlite_fetch_string — Alias of sqlite_fetch_single
    • sqlite_field_name — Returns the name of a particular field
    • sqlite_has_more — Finds whether or not more rows are available
    • sqlite_has_prev — Returns whether or not a previous row is available
    • sqlite_key — Returns the current row index
    • sqlite_last_error — Returns the error code of the last error for a database
    • sqlite_last_insert_rowid — Returns the rowid of the most recently inserted row
    • sqlite_libencoding — Returns the encoding of the linked SQLite library
    • sqlite_libversion — Returns the version of the linked SQLite library
    • sqlite_next — Seek to the next row number
    • sqlite_num_fields — Returns the number of fields in a result set
    • sqlite_num_rows — Returns the number of rows in a buffered result set
    • sqlite_open — Opens a SQLite database and create the database if it does not exist
    • sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist
    • sqlite_prev — Seek to the previous row number of a result set
    • sqlite_query — Executes a query against a given database and returns a result handle
    • sqlite_rewind — Seek to the first row number
    • sqlite_seek — Seek to a particular row number of a buffered result set
    • sqlite_single_query — Executes a query and returns either an array for one single column or the value of the first row
    • sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF
    • sqlite_udf_encode_binary — Encode binary data before returning it from an UDF
    • sqlite_unbuffered_query — Execute a query that does not prefetch and buffer all data
    • sqlite_valid — Returns whether more rows are available
pg_version
Introduction
Vendor Specific Database Extensions


SQLite3

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SQLite3 — The SQLite3 class
    • SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
    • SQLite3::close — Closes the database connection
    • SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database
    • SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
    • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
    • SQLite3::escapeString — Returns a string that has been properly escaped
    • SQLite3::exec — Executes a result-less query against a given database
    • SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
    • SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
    • SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
    • SQLite3::loadExtension — Attempts to load an SQLite extension library
    • SQLite3::open — Opens an SQLite database
    • SQLite3::prepare — Prepares an SQL statement for execution
    • SQLite3::query — Executes an SQL query
    • SQLite3::querySingle — Executes a query and returns a single result
    • SQLite3::version — Returns the SQLite3 library version as a string constant and as a number
  • SQLite3Stmt — The SQLite3Stmt class
    • SQLite3Stmt::bindParam — Binds a parameter to a statement variable
    • SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
    • SQLite3Stmt::clear — Clears all current bound parameters
    • SQLite3Stmt::close — Closes the prepared statement
    • SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
    • SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
    • SQLite3Stmt::reset — Resets the prepared statement
  • SQLite3Result — The SQLite3Result class
    • SQLite3Result::columnName — Returns the name of the nth column
    • SQLite3Result::columnType — Returns the type of the nth column
    • SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
    • SQLite3Result::finalize — Closes the result set
    • SQLite3Result::numColumns — Returns the number of columns in the result set
    • SQLite3Result::reset — Resets the result set back to the first row
sqlite_valid
Introduction
Vendor Specific Database Extensions


Statistics

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Statistic Functions
    • stats_absolute_deviation — Returns the absolute deviation of an array of values
    • stats_cdf_beta — CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.
    • stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others.
    • stats_cdf_cauchy — Not documented
    • stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others.
    • stats_cdf_exponential — Not documented
    • stats_cdf_f — Calculates any one parameter of the F distribution given values for the others.
    • stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others.
    • stats_cdf_laplace — Not documented
    • stats_cdf_logistic — Not documented
    • stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others.
    • stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others.
    • stats_cdf_noncentral_f — Calculates any one parameter of the Non-central F distribution given values for the others.
    • stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others.
    • stats_cdf_t — Calculates any one parameter of the T distribution given values for the others.
    • stats_cdf_uniform — Not documented
    • stats_cdf_weibull — Not documented
    • stats_covariance — Computes the covariance of two data sets
    • stats_den_uniform — Not documented
    • stats_dens_beta — Not documented
    • stats_dens_cauchy — Not documented
    • stats_dens_chisquare — Not documented
    • stats_dens_exponential — Not documented
    • stats_dens_f — Description
    • stats_dens_gamma — Not documented
    • stats_dens_laplace — Not documented
    • stats_dens_logistic — Not documented
    • stats_dens_negative_binomial — Not documented
    • stats_dens_normal — Not documented
    • stats_dens_pmf_binomial — Not documented
    • stats_dens_pmf_hypergeometric — Description
    • stats_dens_pmf_poisson — Not documented
    • stats_dens_t — Not documented
    • stats_dens_weibull — Not documented
    • stats_harmonic_mean — Returns the harmonic mean of an array of values
    • stats_kurtosis — Computes the kurtosis of the data in the array
    • stats_rand_gen_beta — Generates beta random deviate
    • stats_rand_gen_chisquare — Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.
    • stats_rand_gen_exponential — Generates a single random deviate from an exponential distribution with mean "av"
    • stats_rand_gen_f — Generates a random deviate
    • stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)
    • stats_rand_gen_gamma — Generates random deviates from a gamma distribution
    • stats_rand_gen_ibinomial_negative — Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).
    • stats_rand_gen_ibinomial — Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE
    • stats_rand_gen_int — Generates random integer between 1 and 2147483562
    • stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).
    • stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
    • stats_rand_gen_noncenral_chisquare — Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0
    • stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central denominator chisquare variate.
    • stats_rand_gen_noncentral_t — Generates a single random deviate from a noncentral T distribution
    • stats_rand_gen_normal — Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.
    • stats_rand_gen_t — Generates a single random deviate from a T distribution
    • stats_rand_get_seeds — Not documented
    • stats_rand_phrase_to_seeds — generate two seeds for the RGN random number generator
    • stats_rand_ranf — Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator
    • stats_rand_setall — Not documented
    • stats_skew — Computes the skewness of the data in the array
    • stats_standard_deviation — Returns the standard deviation
    • stats_stat_binomial_coef — Not documented
    • stats_stat_correlation — Not documented
    • stats_stat_gennch — Not documented
    • stats_stat_independent_t — Not documented
    • stats_stat_innerproduct — Description
    • stats_stat_noncentral_t — Calculates any one parameter of the noncentral t distribution give values for the others.
    • stats_stat_paired_t — Not documented
    • stats_stat_percentile — Not documented
    • stats_stat_powersum — Not documented
    • stats_variance — Returns the population variance
tanh
Introduction
Mathematical Extensions


Shockwave Flash

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic Usage
  • SWF Functions
    • swf_actiongeturl — Get a URL from a Shockwave Flash movie
    • swf_actiongotoframe — Play a frame and then stop
    • swf_actiongotolabel — Display a frame with the specified label
    • swf_actionnextframe — Go forward one frame
    • swf_actionplay — Start playing the flash movie from the current frame
    • swf_actionprevframe — Go backwards one frame
    • swf_actionsettarget — Set the context for actions
    • swf_actionstop — Stop playing the flash movie at the current frame
    • swf_actiontogglequality — Toggle between low and high quality
    • swf_actionwaitforframe — Skip actions if a frame has not been loaded
    • swf_addbuttonrecord — Controls location, appearance and active area of the current button
    • swf_addcolor — Set the global add color to the rgba value specified
    • swf_closefile — Close the current Shockwave Flash file
    • swf_definebitmap — Define a bitmap
    • swf_definefont — Defines a font
    • swf_defineline — Define a line
    • swf_definepoly — Define a polygon
    • swf_definerect — Define a rectangle
    • swf_definetext — Define a text string
    • swf_endbutton — End the definition of the current button
    • swf_enddoaction — End the current action
    • swf_endshape — Completes the definition of the current shape
    • swf_endsymbol — End the definition of a symbol
    • swf_fontsize — Change the font size
    • swf_fontslant — Set the font slant
    • swf_fonttracking — Set the current font tracking
    • swf_getbitmapinfo — Get information about a bitmap
    • swf_getfontinfo — Gets font information
    • swf_getframe — Get the frame number of the current frame
    • swf_labelframe — Label the current frame
    • swf_lookat — Define a viewing transformation
    • swf_modifyobject — Modify an object
    • swf_mulcolor — Sets the global multiply color to the rgba value specified
    • swf_nextid — Returns the next free object id
    • swf_oncondition — Describe a transition used to trigger an action list
    • swf_openfile — Open a new Shockwave Flash file
    • swf_ortho2 — Defines 2D orthographic mapping of user coordinates onto the current viewport
    • swf_ortho — Defines an orthographic mapping of user coordinates onto the current viewport
    • swf_perspective — Define a perspective projection transformation
    • swf_placeobject — Place an object onto the screen
    • swf_polarview — Define the viewer's position with polar coordinates
    • swf_popmatrix — Restore a previous transformation matrix
    • swf_posround — Enables or Disables the rounding of the translation when objects are placed or moved
    • swf_pushmatrix — Push the current transformation matrix back unto the stack
    • swf_removeobject — Remove an object
    • swf_rotate — Rotate the current transformation
    • swf_scale — Scale the current transformation
    • swf_setfont — Change the current font
    • swf_setframe — Switch to a specified frame
    • swf_shapearc — Draw a circular arc
    • swf_shapecurveto3 — Draw a cubic bezier curve
    • swf_shapecurveto — Draw a quadratic bezier curve between two points
    • swf_shapefillbitmapclip — Set current fill mode to clipped bitmap
    • swf_shapefillbitmaptile — Set current fill mode to tiled bitmap
    • swf_shapefilloff — Turns off filling
    • swf_shapefillsolid — Set the current fill style to the specified color
    • swf_shapelinesolid — Set the current line style
    • swf_shapelineto — Draw a line
    • swf_shapemoveto — Move the current position
    • swf_showframe — Display the current frame
    • swf_startbutton — Start the definition of a button
    • swf_startdoaction — Start a description of an action list for the current frame
    • swf_startshape — Start a complex shape
    • swf_startsymbol — Define a symbol
    • swf_textwidth — Get the width of a string
    • swf_translate — Translate the current transformations
    • swf_viewport — Select an area for future drawing
rpm_version
Introduction
Non-Text MIME Output


Sybase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Sybase Functions
    • sybase_affected_rows — Gets number of affected rows in last query
    • sybase_close — Closes a Sybase connection
    • sybase_connect — Opens a Sybase server connection
    • sybase_data_seek — Moves internal row pointer
    • sybase_deadlock_retry_count — Sets the deadlock retry count
    • sybase_fetch_array — Fetch row as array
    • sybase_fetch_assoc — Fetch a result row as an associative array
    • sybase_fetch_field — Get field information from a result
    • sybase_fetch_object — Fetch a row as an object
    • sybase_fetch_row — Get a result row as an enumerated array
    • sybase_field_seek — Sets field offset
    • sybase_free_result — Frees result memory
    • sybase_get_last_message — Returns the last message from the server
    • sybase_min_client_severity — Sets minimum client severity
    • sybase_min_error_severity — Sets minimum error severity
    • sybase_min_message_severity — Sets minimum message severity
    • sybase_min_server_severity — Sets minimum server severity
    • sybase_num_fields — Gets the number of fields in a result set
    • sybase_num_rows — Get number of rows in a result set
    • sybase_pconnect — Open persistent Sybase connection
    • sybase_query — Sends a Sybase query
    • sybase_result — Get result data
    • sybase_select_db — Selects a Sybase database
    • sybase_set_message_handler — Sets the handler called when a server message is raised
    • sybase_unbuffered_query — Send a Sybase query and do not block
SQLite3Result::reset
Introduction
Vendor Specific Database Extensions


tokyo_tyrant

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • TokyoTyrant — The TokyoTyrant class
    • TokyoTyrant::add — Adds to a numeric key
    • TokyoTyrant::connect — Connect to a database
    • TokyoTyrant::connectUri — Connects to a database
    • TokyoTyrant::__construct — Construct a new TokyoTyrant object
    • TokyoTyrant::copy — Copies the database
    • TokyoTyrant::ext — Execute a remote script
    • TokyoTyrant::fwmKeys — Returns the forward matching keys
    • TokyoTyrant::get — The get purpose
    • TokyoTyrant::getIterator — Get an iterator
    • TokyoTyrant::num — Number of records in the database
    • TokyoTyrant::out — Removes records
    • TokyoTyrant::put — Puts values
    • TokyoTyrant::putCat — Concatenates to a record
    • TokyoTyrant::putKeep — Puts a record
    • TokyoTyrant::putNr — Puts value
    • TokyoTyrant::putShl — Concatenates to a record
    • TokyoTyrant::restore — Restore the database
    • TokyoTyrant::setMaster — Set the replication master
    • TokyoTyrant::size — Returns the size of the value
    • TokyoTyrant::stat — Get statistics
    • TokyoTyrant::sync — Synchronize the database
    • TokyoTyrant::tune — Tunes connection values
    • TokyoTyrant::vanish — Empties the database
  • TokyoTyrantTable — The TokyoTyrantTable class
    • TokyoTyrantTable::add — Adds a record
    • TokyoTyrantTable::genUid — Generate unique id
    • TokyoTyrantTable::get — Get a row
    • TokyoTyrantTable::getIterator — Get an iterator
    • TokyoTyrantTable::getQuery — Get a query object
    • TokyoTyrantTable::out — Remove records
    • TokyoTyrantTable::put — Store a row
    • TokyoTyrantTable::putCat — Concatenates to a row
    • TokyoTyrantTable::putKeep — Put a new record
    • TokyoTyrantTable::putNr — Puts value
    • TokyoTyrantTable::putShl — Concatenates to a record
    • TokyoTyrantTable::setIndex — Sets index
  • TokyoTyrantQuery — The TokyoTyrantQuery class
    • TokyoTyrantQuery::addCond — Adds a condition to the query
    • TokyoTyrantQuery::__construct — Construct a new query
    • TokyoTyrantQuery::count — Counts records
    • TokyoTyrantQuery::current — Returns the current element
    • TokyoTyrantQuery::hint — Get the hint string of the query
    • TokyoTyrantQuery::key — Returns the current key
    • TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries
    • TokyoTyrantQuery::next — Moves the iterator to next entry
    • TokyoTyrantQuery::out — Removes records based on query
    • TokyoTyrantQuery::rewind — Rewinds the iterator
    • TokyoTyrantQuery::search — Searches records
    • TokyoTyrantQuery::setLimit — Limit results
    • TokyoTyrantQuery::valid — Checks the validity of current item
sybase_unbuffered_query
Introduction
Vendor Specific Database Extensions


Unicode

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Unicode Functions
    • unicode_decode — Convert a binary string into a Unicode string
    • unicode_encode — Convert a unicode string in any encoding
    • unicode_get_error_mode — Get the error mode for strings conversions
    • unicode_get_subst_char — Get the substitution character for string conversion errors
    • unicode_set_error_mode — Set the error mode for strings conversions
    • unicode_set_subst_char — Set the substitution character for string conversion errors
recode
Introduction
Human Language and Character Encoding Support


ODBC (Unified)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • ODBC Functions
    • odbc_autocommit — Toggle autocommit behaviour
    • odbc_binmode — Handling of binary column data
    • odbc_close_all — Close all ODBC connections
    • odbc_close — Close an ODBC connection
    • odbc_columnprivileges — Lists columns and associated privileges for the given table
    • odbc_columns — Lists the column names in specified tables
    • odbc_commit — Commit an ODBC transaction
    • odbc_connect — Connect to a datasource
    • odbc_cursor — Get cursorname
    • odbc_data_source — Returns information about a current connection
    • odbc_do — Alias of odbc_exec
    • odbc_error — Get the last error code
    • odbc_errormsg — Get the last error message
    • odbc_exec — Prepare and execute a SQL statement
    • odbc_execute — Execute a prepared statement
    • odbc_fetch_array — Fetch a result row as an associative array
    • odbc_fetch_into — Fetch one result row into array
    • odbc_fetch_object — Fetch a result row as an object
    • odbc_fetch_row — Fetch a row
    • odbc_field_len — Get the length (precision) of a field
    • odbc_field_name — Get the columnname
    • odbc_field_num — Return column number
    • odbc_field_precision — Alias of odbc_field_len
    • odbc_field_scale — Get the scale of a field
    • odbc_field_type — Datatype of a field
    • odbc_foreignkeys — Retrieves a list of foreign keys
    • odbc_free_result — Free resources associated with a result
    • odbc_gettypeinfo — Retrieves information about data types supported by the data source
    • odbc_longreadlen — Handling of LONG columns
    • odbc_next_result — Checks if multiple results are available
    • odbc_num_fields — Number of columns in a result
    • odbc_num_rows — Number of rows in a result
    • odbc_pconnect — Open a persistent database connection
    • odbc_prepare — Prepares a statement for execution
    • odbc_primarykeys — Gets the primary keys for a table
    • odbc_procedurecolumns — Retrieve information about parameters to procedures
    • odbc_procedures — Get the list of procedures stored in a specific data source
    • odbc_result_all — Print result as HTML table
    • odbc_result — Get result data
    • odbc_rollback — Rollback a transaction
    • odbc_setoption — Adjust ODBC settings
    • odbc_specialcolumns — Retrieves special columns
    • odbc_statistics — Retrieve statistics about a table
    • odbc_tableprivileges — Lists tables and the privileges associated with each table
    • odbc_tables — Get the list of table names stored in a specific data source
dbx_sort
Introduction
Abstraction Layers


vpopmail

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • vpopmail Functions
    • vpopmail_add_alias_domain_ex — Add alias to an existing virtual domain
    • vpopmail_add_alias_domain — Add an alias for a virtual domain
    • vpopmail_add_domain_ex — Add a new virtual domain
    • vpopmail_add_domain — Add a new virtual domain
    • vpopmail_add_user — Add a new user to the specified virtual domain
    • vpopmail_alias_add — Insert a virtual alias
    • vpopmail_alias_del_domain — Deletes all virtual aliases of a domain
    • vpopmail_alias_del — Deletes all virtual aliases of a user
    • vpopmail_alias_get_all — Get all lines of an alias for a domain
    • vpopmail_alias_get — Get all lines of an alias for a domain
    • vpopmail_auth_user — Attempt to validate a username/domain/password
    • vpopmail_del_domain_ex — Delete a virtual domain
    • vpopmail_del_domain — Delete a virtual domain
    • vpopmail_del_user — Delete a user from a virtual domain
    • vpopmail_error — Get text message for last vpopmail error
    • vpopmail_passwd — Change a virtual user's password
    • vpopmail_set_user_quota — Sets a virtual user's quota
mailparse_uudecode_all
Introduction
Mail Related Extensions


Windows Cache for PHP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • WinCache Statistics Script
    • Resource Types
  • Predefined Constants
  • WinCache Functions
    • wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
    • wincache_fcache_meminfo — Retrieves information about file cache memory usage
    • wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
    • wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
    • wincache_refresh_if_changed — Refreshes the cache entries for the cached files
    • wincache_rplist_fileinfo — Retrieves information about resolve file path cache
    • wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
  • Building for Windows
    • Prerequisites
    • Compiling and building
    • Verifying the build
Example that shows the effect of scream
Introduction
Affecting PHP's Behaviour


xattr

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • xattr Functions
    • xattr_get — Get an extended attribute
    • xattr_list — Get a list of extended attributes
    • xattr_remove — Remove an extended attribute
    • xattr_set — Set an extended attribute
    • xattr_supported — Check if filesystem supports extended attributes
Predefined Constants
Introduction
File System Related Extensions


xdiff

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • xdiff Functions
    • xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
    • xdiff_file_bdiff — Make binary diff of two files
    • xdiff_file_bpatch — Patch a file with a binary diff
    • xdiff_file_diff_binary — Alias of xdiff_file_bdiff
    • xdiff_file_diff — Make unified diff of two files
    • xdiff_file_merge3 — Merge 3 files into one
    • xdiff_file_patch_binary — Alias of xdiff_file_bpatch
    • xdiff_file_patch — Patch a file with an unified diff
    • xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
    • xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
    • xdiff_string_bdiff — Make binary diff of two strings
    • xdiff_string_bpatch — Patch a string with a binary diff
    • xdiff_string_diff_binary — Alias of xdiff_string_bdiff
    • xdiff_string_diff — Make unified diff of two strings
    • xdiff_string_merge3 — Merge 3 strings into one
    • xdiff_string_patch_binary — Alias of xdiff_string_bpatch
    • xdiff_string_patch — Patch a string with an unified diff
    • xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
xattr_supported
Introduction
File System Related Extensions


Zip

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • ZipArchive — The ZipArchive class
    • ZipArchive::addEmptyDir — Add a new directory
    • ZipArchive::addFile — Adds a file to a ZIP archive from the given path
    • ZipArchive::addFromString — Add a file to a ZIP archive using its contents
    • ZipArchive::close — Close the active archive (opened or newly created)
    • ZipArchive::deleteIndex — delete an entry in the archive using its index
    • ZipArchive::deleteName — delete an entry in the archive using its name
    • ZipArchive::extractTo — Extract the archive contents
    • ZipArchive::getArchiveComment — Returns the Zip archive comment
    • ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
    • ZipArchive::getCommentName — Returns the comment of an entry using the entry name
    • ZipArchive::getFromIndex — Returns the entry contents using its index.
    • ZipArchive::getFromName — Returns the entry contents using its name.
    • ZipArchive::getNameIndex — Returns the name of an entry using its index
    • ZipArchive::GetStatusString — Returns the status error message, system and/or zip messages.
    • ZipArchive::getStream — Get a file handler to the entry defined by its name (read only).
    • ZipArchive::locateName — Returns the index of the entry in the archive
    • ZipArchive::open — Open a ZIP file archive
    • ZipArchive::renameIndex — Renames an entry defined by its index
    • ZipArchive::renameName — Renames an entry defined by its name
    • ZipArchive::setArchiveComment — Set the comment of a ZIP archive
    • ZipArchive::setCommentIndex — Set the comment of an entry defined by its index
    • ZipArchive::setCommentName — Set the comment of an entry defined by its name
    • ZipArchive::statIndex — Get the details of an entry defined by its index.
    • ZipArchive::statName — Get the details of an entry defined by its name.
    • ZipArchive::unchangeAll — Undo all changes done in the archive.
    • ZipArchive::unchangeArchive — Revert all global changes done in the archive.
    • ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index.
    • ZipArchive::unchangeName — Revert all changes done to an entry with the given name.
  • Zip Functions
    • zip_close — Close a ZIP file archive
    • zip_entry_close — Close a directory entry
    • zip_entry_compressedsize — Retrieve the compressed size of a directory entry
    • zip_entry_compressionmethod — Retrieve the compression method of a directory entry
    • zip_entry_filesize — Retrieve the actual file size of a directory entry
    • zip_entry_name — Retrieve the name of a directory entry
    • zip_entry_open — Open a directory entry for reading
    • zip_entry_read — Read from an open directory entry
    • zip_open — Open a ZIP file archive
    • zip_read — Read next entry in a ZIP file archive
RarException::setUsingExceptions
Introduction
Compression and Archive Extensions


Zlib Compression

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Zlib Functions
    • gzclose — Close an open gz-file pointer
    • gzcompress — Compress a string
    • gzdecode — Decodes a gzip compressed string
    • gzdeflate — Deflate a string
    • gzencode — Create a gzip compressed string
    • gzeof — Test for EOF on a gz-file pointer
    • gzfile — Read entire gz-file into an array
    • gzgetc — Get character from gz-file pointer
    • gzgets — Get line from file pointer
    • gzgetss — Get line from gz-file pointer and strip HTML tags
    • gzinflate — Inflate a deflated string
    • gzopen — Open gz-file
    • gzpassthru — Output all remaining data on a gz-file pointer
    • gzputs — Alias of gzwrite
    • gzread — Binary-safe gz-file read
    • gzrewind — Rewind the position of a gz-file pointer
    • gzseek — Seek on a gz-file pointer
    • gztell — Tell gz-file pointer read/write position
    • gzuncompress — Uncompress a compressed string
    • gzwrite — Binary-safe gz-file write
    • readgzfile — Output a gz-file
    • zlib_get_coding_type — Returns the coding type used for output compression
zip_read
Introduction
Compression and Archive Extensions


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
Bzip2


Examples

This example opens a temporary file and writes a test string to it, then prints out the contents of the file.

Example #1 Small bzip2 Example

<?php

$filename = "/tmp/testfile.bz2";
$str = "This is a test string.\n";

// open file for writing
$bz = bzopen($filename, "w");

// write string to file
bzwrite($bz, $str);

// close file
bzclose($bz);

// open file for reading
$bz = bzopen($filename, "r");

// read 10 characters
echo bzread($bz, 10);

// output until end of the file (or the next 1024 char) and close it.
echo bzread($bz);

bzclose($bz);

?>
Predefined Constants
Bzip2 Functions
Bzip2


Installation

Bzip2 support in PHP is not enabled by default. You will need to use the --with-bz2[=DIR] configuration option when compiling PHP to enable bzip2 support.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

This module uses the functions of the » bzip2 library by Julian Seward. This module requires bzip2/libbzip2 version >= 1.0.x.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension defines one resource type: a file pointer identifying the bz2-file to work on.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Bzip2


Retrieves the availables font types

Cairo
Cairo::availableSurfaces
Cairo
PHP Manual

Cairo::availableFonts

cairo_available_fonts

(PECL cairo >= 0.1.0)

Cairo::availableFonts -- cairo_available_fonts — Retrieves the availables font types

Description

Object oriented style (method):

public static array Cairo::availableFonts ( void )

Procedural style:

array cairo_available_fonts ( void )

Returns an array with the available font backends

Parameters

This function has no parameters.

Return Values

A list-type array with all available font backends.

Examples

Example #1 Object oriented style

<?php

/* Object Oriented Style */
var_dump(Cairo::availableFonts());

?>

The above example will output something similar to:

array(2) {
  [0]=>
  string(5) "WIN32"
  [1]=>
  string(4) "USER"
}

Example #2 Procedural style

<?php

/* Procedural style */
var_dump(cairo_available_fonts());

?>

The above example will output something similar to:

array(2) {
  [0]=>
  string(5) "WIN32"
  [1]=>
  string(4) "USER"
}

See Also

  • Cairo::availableSurfaces - Retrieves all available surfaces

Cairo
Cairo::availableSurfaces
Cairo


Retrieves all available surfaces

Cairo::availableFonts
Cairo::statusToString
Cairo
PHP Manual

Cairo::availableSurfaces

cairo_available_surfaces

(PECL cairo >= 0.1.0)

Cairo::availableSurfaces -- cairo_available_surfaces — Retrieves all available surfaces

Description

Object oriented style (method):

public static array Cairo::availableSurfaces ( void )

Procedural style:

array cairo_available_surfaces ( void )

Returns an array with the available surface backends

Parameters

This function has no parameters.

Return Values

A list-type array with all available surface backends.

Examples

Example #1 Object oriented style

<?php

/* Object Oriented style */
var_dump(Cairo::availableSurfaces());

?>

The above example will output something similar to:

array(6) {
  [0]=>
  string(5) "IMAGE"
  [1]=>
  string(3) "PNG"
  [2]=>
  string(3) "PDF"
  [3]=>
  string(2) "PS"
  [4]=>
  string(3) "SVG"
  [5]=>
  string(5) "WIN32"
}

Example #2 Procedural style

<?php

/* Procedural style */
var_dump(cairo_available_surfaces());

?>

The above example will output something similar to:

array(6) {
  [0]=>
  string(5) "IMAGE"
  [1]=>
  string(3) "PNG"
  [2]=>
  string(3) "PDF"
  [3]=>
  string(2) "PS"
  [4]=>
  string(3) "SVG"
  [5]=>
  string(5) "WIN32"
}

See Also

  • Cairo::availableFonts - Retrieves the availables font types

Cairo::availableFonts
Cairo::statusToString
Cairo


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CAIRO_STATUS_SUCCESS (integer)
CAIRO_STATUS_NO_MEMORY (integer)
CAIRO_STATUS_INVALID_RESTORE (integer)
CAIRO_STATUS_INVALID_POP_GROUP (integer)
CAIRO_STATUS_NO_CURRENT_POINT (integer)
CAIRO_STATUS_INVALID_MATRIX (integer)
CAIRO_STATUS_INVALID_STATUS (integer)
CAIRO_STATUS_NULL_POINTER (integer)
CAIRO_STATUS_INVALID_STRING (integer)
CAIRO_STATUS_INVALID_PATH_DATA (integer)
CAIRO_STATUS_READ_ERROR (integer)
CAIRO_STATUS_WRITE_ERROR (integer)
CAIRO_STATUS_SURFACE_FINISHED (integer)
CAIRO_STATUS_SURFACE_TYPE_MISMATCH (integer)
CAIRO_STATUS_PATTERN_TYPE_MISMATCH (integer)
CAIRO_STATUS_INVALID_CONTENT (integer)
CAIRO_STATUS_INVALID_FORMAT (integer)
CAIRO_STATUS_INVALID_VISUAL (integer)
CAIRO_STATUS_FILE_NOT_FOUND (integer)
CAIRO_STATUS_INVALID_DASH (integer)
CAIRO_STATUS_INVALID_DSC_COMMENT (integer)
CAIRO_STATUS_INVALID_INDEX (integer)
CAIRO_STATUS_CLIP_NOT_REPRESENTABLE (integer)
CAIRO_STATUS_TEMP_FILE_ERROR (integer)
CAIRO_STATUS_INVALID_STRIDE (integer)
CAIRO_ANTIALIAS_DEFAULT (integer)
CAIRO_ANTIALIAS_NONE (integer)
CAIRO_ANTIALIAS_GRAY (integer)
CAIRO_ANTIALIAS_SUBPIXEL (integer)
CAIRO_SUBPIXEL_ORDER_DEFAULT (integer)
CAIRO_SUBPIXEL_ORDER_RGB (integer)
CAIRO_SUBPIXEL_ORDER_BGR (integer)
CAIRO_SUBPIXEL_ORDER_VRGB (integer)
CAIRO_SUBPIXEL_ORDER_VBGR (integer)
CAIRO_FILL_RULE_WINDING (integer)
CAIRO_FILL_RULE_EVEN_ODD (integer)
CAIRO_LINE_CAP_BUTT (integer)
CAIRO_LINE_CAP_ROUND (integer)
CAIRO_LINE_CAP_SQUARE (integer)
CAIRO_LINE_JOIN_MITER (integer)
CAIRO_LINE_JOIN_ROUND (integer)
CAIRO_LINE_JOIN_BEVEL (integer)
CAIRO_OPERATOR_CLEAR (integer)
CAIRO_OPERATOR_SOURCE (integer)
CAIRO_OPERATOR_OVER (integer)
CAIRO_OPERATOR_IN (integer)
CAIRO_OPERATOR_OUT (integer)
CAIRO_OPERATOR_ATOP (integer)
CAIRO_OPERATOR_DEST (integer)
CAIRO_OPERATOR_DEST_OVER (integer)
CAIRO_OPERATOR_DEST_IN (integer)
CAIRO_OPERATOR_DEST_OUT (integer)
CAIRO_OPERATOR_DEST_ATOP (integer)
CAIRO_OPERATOR_XOR (integer)
CAIRO_OPERATOR_ADD (integer)
CAIRO_OPERATOR_SATURATE (integer)
CAIRO_PATTERN_TYPE_SOLID (integer)
CAIRO_PATTERN_TYPE_SURFACE (integer)
CAIRO_PATTERN_TYPE_LINEAR (integer)
CAIRO_PATTERN_TYPE_RADIAL (integer)
CAIRO_EXTEND_NONE (integer)
CAIRO_EXTEND_REPEAT (integer)
CAIRO_EXTEND_REFLECT (integer)
CAIRO_EXTEND_PAD (integer)
CAIRO_FILTER_FAST (integer)
CAIRO_FILTER_GOOD (integer)
CAIRO_FILTER_BEST (integer)
CAIRO_FILTER_NEAREST (integer)
CAIRO_FILTER_BILINEAR (integer)
CAIRO_FILTER_GAUSSIAN (integer)
CAIRO_HINT_STYLE_DEFAULT (integer)
CAIRO_HINT_STYLE_NONE (integer)
CAIRO_HINT_STYLE_SLIGHT (integer)
CAIRO_HINT_STYLE_MEDIUM (integer)
CAIRO_HINT_STYLE_FULL (integer)
CAIRO_HINT_METRICS_DEFAULT (integer)
CAIRO_HINT_METRICS_OFF (integer)
CAIRO_HINT_METRICS_ON (integer)
CAIRO_FONT_TYPE_TOY (integer)
CAIRO_FONT_TYPE_FT (integer)
CAIRO_FONT_TYPE_WIN32 (integer)
CAIRO_FONT_TYPE_QUARTZ (integer)
CAIRO_FONT_SLANT_NORMAL (integer)
CAIRO_FONT_SLANT_ITALIC (integer)
CAIRO_FONT_SLANT_OBLIQUE (integer)
CAIRO_FONT_WEIGHT_NORMAL (integer)
CAIRO_FONT_WEIGHT_BOLD (integer)
CAIRO_CONTENT_COLOR (integer)
CAIRO_CONTENT_ALPHA (integer)
CAIRO_CONTENT_COLOR_ALPHA (integer)
CAIRO_SURFACE_TYPE_IMAGE (integer)
CAIRO_SURFACE_TYPE_PDF (integer)
CAIRO_SURFACE_TYPE_PS (integer)
CAIRO_SURFACE_TYPE_XLIB (integer)
CAIRO_SURFACE_TYPE_XCB (integer)
CAIRO_SURFACE_TYPE_GLITZ (integer)
CAIRO_SURFACE_TYPE_QUARTZ (integer)
CAIRO_SURFACE_TYPE_WIN32 (integer)
CAIRO_SURFACE_TYPE_BEOS (integer)
CAIRO_SURFACE_TYPE_DIRECTFB (integer)
CAIRO_SURFACE_TYPE_SVG (integer)
CAIRO_SURFACE_TYPE_OS2 (integer)
CAIRO_SURFACE_TYPE_WIN32_PRINTING (integer)
CAIRO_SURFACE_TYPE_QUARTZ_IMAGE (integer)
CAIRO_FORMAT_ARGB32 (integer)
CAIRO_FORMAT_RGB24 (integer)
CAIRO_FORMAT_A8 (integer)
CAIRO_FORMAT_A1 (integer)
CAIRO_PS_LEVEL_2 (integer)
CAIRO_PS_LEVEL_3 (integer)
CAIRO_SVG_VERSION_1_1 (integer)
CAIRO_SVG_VERSION_1_2 (integer)

Resource Types
Examples
Cairo


Examples

Description here...

Example #1 Cairo Example

<?php

/* ... */

?>

The above example will output something similar to:

...
Predefined Constants
Cairo Functions
Cairo


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/cairo.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Notes specific to installation on Windows

Binary builds of the extension can be found at » http://perisama.net/cairo/. Download the correct zip file, place php_cairo.dll in the extensions directory, and enable it via the php.ini file in use. Please be sure the PHP minor version (5.2, 5.3) match, the thread safety (Thread Safe TS or Non-Thread Safe NTS), the architecture (x86 or x64), and the compiler version (VC6 or VC9) match or the extension will not load.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

Cairo is only available for PHP 5.2+ and PHP 5.3+ The extension also requires the cairo graphics library version 1.4 or higher. The cairo graphics library uses an even and odd numbering scheme to denote stable and unstable library versions. Both unstable and stable versions can be used with the extension, but conditional support for new features is determined by the stable version below the unstable version in use. The latest cairo release can be found at » http://cairographics.org/.

The binary files used for the windows compiles can be found at » http://perisama.net/cairo/ along with the project files used to create them.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Cairo


Retrieves the current status as string

Cairo::availableSurfaces
Cairo::version
Cairo
PHP Manual

Cairo::statusToString

cairo_status_to_string

(PECL cairo >= 0.1.0)

Cairo::statusToString -- cairo_status_to_string — Retrieves the current status as string

Description

Object oriented style (method):

public static string Cairo::statusToString ( int $status )

Procedural style:

string cairo_status_to_string ( int $status )

Retrieves the current status as a readable string

Parameters

status

A valid status code given by cairo_status() or CairoContext::status

Return Values

A string containing the current status of a CairoContext object

Examples

Example #1 Object oriented style

<?php
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$context = new CairoContext($surface);

var_dump(Cairo::statusToString($context->status()));
?>

The above example will output something similar to:

string(7) "success"

Example #2 Procedural style

<?php
$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$context = cairo_create($surface);

var_dump(cairo_status_to_string(cairo_status($context)));
?>

The above example will output something similar to:

string(7) "success"

See Also

  • CairoContext::status - The status purpose

Cairo::availableSurfaces
Cairo::version
Cairo


Retrives cairo's library version

Cairo::statusToString
Cairo::versionString
Cairo
PHP Manual

Cairo::version

cairo_version

(PECL cairo >= 0.1.0)

Cairo::version -- cairo_version — Retrives cairo's library version

Description

Object oriented style (method):

public static int Cairo::version ( void )

Procedural style:

int cairo_version ( void )

Retrieves the current version of the cairo library as an integer value

Parameters

This function has no parameters.

Return Values

Current Cairo library version integer

Examples

Example #1 Object oriented style

<?php
var_dump(Cairo::version());
?>

The above example will output something similar to:

int(10808)

Example #2 Procedural style

<?php
var_dump(cairo_version());
?>

The above example will output something similar to:

int(10808)

See Also

  • Cairo::versionString - Retrieves cairo version as string

Cairo::statusToString
Cairo::versionString
Cairo


Retrieves cairo version as string

Cairo::version
CairoContext
Cairo
PHP Manual

Cairo::versionString

cairo_version_string

(PECL cairo >= 0.1.0)

Cairo::versionString -- cairo_version_string — Retrieves cairo version as string

Description

Object oriented style (method):

public static string Cairo::versionString ( void )

Procedural style:

string cairo_version_string ( void )

Retrieves the current cairo library version as a string.

Parameters

This function has no parameters.

Return Values

Current Cairo library version string

Examples

Example #1 Object oriented style

<?php

var_dump(Cairo::versionString());

?>

The above example will output something similar to:

string(5) "1.8.8"

Example #2 Procedural style

<?php

var_dump(cairo_version_string());

?>

The above example will output something similar to:

string(5) "1.8.8"

See Also

  • Cairo::version - Retrives cairo's library version

Cairo::version
CairoContext
Cairo


Appends a path to current path

CairoContext
CairoContext::arc
CairoContext
PHP Manual

CairoContext::appendPath

cairo_append_path

(PECL cairo >= 0.1.0)

CairoContext::appendPath -- cairo_append_path — Appends a path to current path

Description

Object oriented style (method):

public void CairoContext::appendPath ( CairoPath $path )

Procedural style:

void cairo_append_path ( CairoContext $context , CairoPath $path )

Appends the path onto the current path. The path may be either the return value from one of CairoContext::copyPath or CairoContext::copyPathFlat;

if path is not a valid CairoPath instance a CairoException will be thrown

Parameters

context

CairoContext object

path

CairoPath object

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$path = $context->copyPath();

$context->appendPath($path);

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

$path = cairo_copy_path($context);

cairo_append_path($context, $path);

?>

See Also

  • CairoPath
  • CairoContext::copyPath - Creates a copy of the current path
  • CairoContext::copyPathFlat - Gets a flattened copy of the current path

CairoContext
CairoContext::arc
CairoContext


Adds a circular arc

CairoContext::appendPath
CairoContext::arcNegative
CairoContext
PHP Manual

CairoContext::arc

cairo_arc

(PECL cairo >= 0.1.0)

CairoContext::arc -- cairo_arc — Adds a circular arc

Description

Object oriented style (method):

public void CairoContext::arc ( float $x , float $y , float $radius , float $angle1 , float $angle2 )

Procedural style:

void cairo_arc ( CairoContext $context , float $x , float $y , float $radius , float $angle1 , float $angle2 )

Adds a circular arc of the given radius to the current path. The arc is centered at (x , y ), begins at angle1 and proceeds in the direction of increasing angles to end at angle2 . If angle2 is less than angle1 it will be progressively increased by 2*M_PI until it is greater than angle1 . If there is a current point, an initial line segment will be added to the path to connect the current point to the beginning of the arc. If this initial line is undesired, it can be avoided by calling CairoContext::newSubPath or procedural cairo_new_sub_path() before calling CairoContext::arc or cairo_arc(). Angles are measured in radians. An angle of 0.0 is in the direction of the positive X axis (in user space). An angle of M_PI/2.0 radians (90 degrees) is in the direction of the positive Y axis (in user space). Angles increase in the direction from the positive X axis toward the positive Y axis. So with the default transformation matrix, angles increase in a clockwise direction. (To convert from degrees to radians, use degrees * (M_PI / 180.).) This function gives the arc in the direction of increasing angles; see CairoContext::arcNegative or cairo_arc_negative() to get the arc in the direction of decreasing angles.

Parameters

context

A valid CairoContext object

x

x position

y

y position

radius

Radius of the arc

angle1

start angle

angle2

end angle

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
// Creates the CairoSurface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

// Get the cairo context
$context = new CairoContext($surface);

// Appends the arc
$context->arc(0, 0, 1, 0, 2 * M_PI);
?>

Example #2 Procedural style

<?php
// Creates the CairoSurface
$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

// Get the cairo context
$context = cairo_create($surface);

// Appends the arc
cairo_arc($context, 0, 0, 1, 0, 2 * M_PI);
?>

See Also

  • CairoContext::arcNegative - Adds a negative arc

CairoContext::appendPath
CairoContext::arcNegative
CairoContext


Adds a negative arc

CairoContext::arc
CairoContext::clip
CairoContext
PHP Manual

CairoContext::arcNegative

cairo_arc_negative

(PECL cairo >= 0.1.0)

CairoContext::arcNegative -- cairo_arc_negative — Adds a negative arc

Description

Object oriented style (method):

public void CairoContext::arcNegative ( float $x , float $y , float $radius , float $angle1 , float $angle2 )

Procedural style:

void cairo_arc_negative ( CairoContext $context , float $x , float $y , float $radius , float $angle1 , float $angle2 )

Adds a circular arc of the given radius to the current path. The arc is centered at (x , y ), begins at angle1 and proceeds in the direction of decreasing angles to end at angle2 . If angle2 is greater than angle1 it will be progressively decreased by 2*M_PI until it is less than angle1 . See CairoContext::arc or cairo_arc() for more details. This function differs only in the direction of the arc between the two angles.

Parameters

context

A valid CairoContext object

x

double x position

y

double y position

radius

The radius of the desired negative arc

angle1

Start angle of the arc

angle2

End angle of the arc

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
// Creates the CairoSurface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

// Get the cairo context
$context = new CairoContext($surface);

// Appends the arc
$context->arcNegative(0, 0, 1, 0, 2 * M_PI);
?>

Example #2 Procedural style

<?php
// Creates the CairoSurface
$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

// Get the cairo context
$context = cairo_create($surface);

// Appends the arc
cairo_arc_negative($context, 0, 0, 1, 0, 2 * M_PI);
?>

See Also

  • CairoContext::arc - Adds a circular arc

CairoContext::arc
CairoContext::clip
CairoContext


Establishes a new clip region

CairoContext::arcNegative
CairoContext::clipExtents
CairoContext
PHP Manual

CairoContext::clip

cairo_clip

(PECL cairo >= 0.1.0)

CairoContext::clip -- cairo_clip — Establishes a new clip region

Description

Object oriented style (method):

public void CairoContext::clip ( void )

Procedural style:

void cairo_clip ( CairoContext $context )

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by CairoContext::fill or cairo_fill() and according to the current fill rule (see CairoContext::setFillRule or cairo_set_fill_rule()).

After CairoContext::clip or cairo_clip(), the current path will be cleared from the cairo context.

The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.

Calling  CairoContext::clip or cairo_clip()
can only make the clip region smaller, never larger. But the current clip is part of the
graphics state, so a temporary restriction of the clip region can be achieved by calling
 CairoContext::clip or cairo_clip() within a
 CairoContext::save/ CairoContext::restore or
cairo_save()/cairo_restore() pair.
The only other means of increasing the size of the clip region is
 CairoContext::resetClip or procedural cairo_reset_clip().

Parameters

context

A valid CairoContext object

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->clip();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_clip($context);

?>

See Also

  • CairoContext::resetClip - The resetClip purpose
  • cairo_reset_clip() - The resetClip purpose

CairoContext::arcNegative
CairoContext::clipExtents
CairoContext


Computes the area inside the current clip

CairoContext::clip
CairoContext::clipPreserve
CairoContext
PHP Manual

CairoContext::clipExtents

cairo_clip_extents

(PECL cairo >= 0.1.0)

CairoContext::clipExtents -- cairo_clip_extents — Computes the area inside the current clip

Description

Object oriented style (method):

public array CairoContext::clipExtents ( void )

Procedural style:

array cairo_clip_extents ( CairoContext $context )

Computes a bounding box in user coordinates covering the area inside the current clip.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

A valid CairoContext object

Return Values

An array containing the (float)x1, (float)y1, (float)x2, (float)y2, coordinates covering the area inside the current clip

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->clipExtents());
?>

The above example will output something similar to:

array(4) {
  [0]=>
  float(0)
  [1]=>
  float(0)
  [2]=>
  float(50)
  [3]=>
  float(50)
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_clip_extents($context));

?>

The above example will output something similar to:

array(4) {
  [0]=>
  float(0)
  [1]=>
  float(0)
  [2]=>
  float(50)
  [3]=>
  float(50)
}

See Also

  • CairoContext::clip - Establishes a new clip region

CairoContext::clip
CairoContext::clipPreserve
CairoContext


Establishes a new clip region from the current clip

CairoContext::clipExtents
CairoContext::clipRectangleList
CairoContext
PHP Manual

CairoContext::clipPreserve

cairo_clip_preserve

(PECL cairo >= 0.1.0)

CairoContext::clipPreserve -- cairo_clip_preserve — Establishes a new clip region from the current clip

Description

Object oriented style (method):

public void CairoContext::clipPreserve ( void )

Procedural style:

void cairo_clip_preserve ( CairoContext $context )

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by Context.fill and according to the current FILL RULE (see CairoContext::setFillRule or cairo_set_fill_rule()).

Unlike CairoContext::clip, CairoContext::clipPreserve preserves the path within the Context. The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.

Calling CairoContext::clipPreserve can only make the clip region smaller, never larger. But the current clip is part of the graphics state, so a temporary restriction of the clip region can be achieved by calling CairoContext::clipPreserve within a CairoContext::save/ CairoContext::restore pair. The only other means of increasing the size of the clip region is CairoContext::resetClip.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

A valid CairoContext object

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->clipPreserve();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_clip_preserve($context);

?>

See Also

  • CairoContext::save - The save purpose
  • CairoContext::restore - The restore purpose
  • CairoContext::resetClip - The resetClip purpose

CairoContext::clipExtents
CairoContext::clipRectangleList
CairoContext


Retrieves the current clip as a list of rectangles

CairoContext::clipPreserve
CairoContext::closePath
CairoContext
PHP Manual

CairoContext::clipRectangleList

cairo_clip_rectangle_list

(PECL cairo >= 0.1.0)

CairoContext::clipRectangleList -- cairo_clip_rectangle_list — Retrieves the current clip as a list of rectangles

Description

Object oriented style (method):

public array CairoContext::clipRectangleList ( void )

Procedural style:

array cairo_clip_rectangle_list ( CairoContext $context )

Returns a list-type array with the current clip region as a list of rectangles in user coordinates

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

Return Values

An array of user-space represented rectangles for the current clip

(The status in the list may be CAIRO_STATUS_CLIP_NOT_REPRESENTABLE to indicate that the clip region cannot be represented as a list of user-space rectangles. The status may have other values to indicate other errors.)

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->clipRectangleList());

?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(4) {
    ["x"]=>
    float(0)
    ["y"]=>
    float(0)
    ["width"]=>
    float(50)
    ["height"]=>
    float(50)
  }
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_clip_rectangle_list($context));

?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(4) {
    ["x"]=>
    float(0)
    ["y"]=>
    float(0)
    ["width"]=>
    float(50)
    ["height"]=>
    float(50)
  }
}

See Also

  • Classname::Method

CairoContext::clipPreserve
CairoContext::closePath
CairoContext


Closes the current path

CairoContext::clipRectangleList
CairoContext::__construct
CairoContext
PHP Manual

CairoContext::closePath

cairo_close_path

(PECL cairo >= 0.1.0)

CairoContext::closePath -- cairo_close_path — Closes the current path

Description

Object oriented style (method):

public void CairoContext::closePath ( void )

Procedural style:

void cairo_close_path ( CairoContext $context )

Adds a line segment to the path from the current point to the beginning of the current sub-path, (the most recent point passed to CairoContext::moveTo), and closes this sub-path. After this call the current point will be at the joined endpoint of the sub-path.

The behavior of close_path() is distinct from simply calling CairoContext::lineTo with the equivalent coordinate in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of the sub-path. Instead, there is a line join connecting the final and initial segments of the sub-path.

If there is no current point before the call to CairoContext::closePath, this function will have no effect.

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->closePath();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_close_path($context);

?>

See Also

  • CairoContext::copyPath - Creates a copy of the current path

CairoContext::clipRectangleList
CairoContext::__construct
CairoContext


Creates a new CairoContext

CairoContext::closePath
CairoContext::copyPage
CairoContext
PHP Manual

CairoContext::__construct

(PECL cairo >= 0.1.0)

CairoContext::__construct — Creates a new CairoContext

Description

CairoContext::__construct ( CairoSurface $surface )

Creates a new CairoContext object to draw

Parameters

surface

A valid CairoSurface like CairoImageSurface or CairoPdfSurface

Return Values

A CairoContext

Examples

Example #1 CairoContext::__construct example

<?php
// The surface to work on
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

// Create a new CairoContext for the CairoSurface
$context = new CairoContext($surface);

?>

See Also

  • Cairo::Method

CairoContext::closePath
CairoContext::copyPage
CairoContext


Emits the current page

CairoContext::__construct
CairoContext::copyPath
CairoContext
PHP Manual

CairoContext::copyPage

cairo_copy_page

(PECL cairo >= 0.1.0)

CairoContext::copyPage -- cairo_copy_page — Emits the current page

Description

Object oriented style (method):

public void CairoContext::copyPage ( void )

Procedural style:

void cairo_copy_page ( CairoContext $context )

Emits the current page for backends that support multiple pages, but doesn’t clear it, so, the contents of the current page will be retained for the next page too. Use CairoContext::showPage if you want to get an empty page after the emission.

This is a convenience function that simply calls CairoSurface::copyPage on CairoContext’s target.

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->copyPage();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_copy_page($context);

?>

See Also

  • CairoContext::showPage - The showPage purpose
  • CairoSurface::copyPage - The copyPage purpose

CairoContext::__construct
CairoContext::copyPath
CairoContext


Creates a copy of the current path

CairoContext::copyPage
CairoContext::copyPathFlat
CairoContext
PHP Manual

CairoContext::copyPath

cairo_copy_path

(PECL cairo >= 0.1.0)

CairoContext::copyPath -- cairo_copy_path — Creates a copy of the current path

Description

Object oriented style (method):

public CairoPath CairoContext::copyPath ( void )

Procedural style:

CairoPath cairo_copy_path ( CairoContext $context )

Creates a copy of the current path and returns it to the user as a CairoPath. See CairoPath for hints on how to iterate over the returned data structure.

This function will always return a valid CairoPath object, but the result will have no data, if either of the following conditions hold:

  • 1. If there is insufficient memory to copy the path. In this case CairoPath->status will be set to CAIRO_STATUS_NO_MEMORY.
  • 2. If context is already in an error state. In this case CairoPath->status will contain the same status that would be returned by cairo_status().

In either case, CairoPath->status will be set to CAIRO_STATUS_NO_MEMORY (regardless of what the error status in cr might have been).

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

Return Values

A copy of the current CairoPath in the context

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->copyPath())

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_copy_path($context));

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

See Also

  • CairoContext::closePath - Closes the current path

CairoContext::copyPage
CairoContext::copyPathFlat
CairoContext


Gets a flattened copy of the current path

CairoContext::copyPath
CairoContext::curveTo
CairoContext
PHP Manual

CairoContext::copyPathFlat

cairo_copy_path_flat

(PECL cairo >= 0.1.0)

CairoContext::copyPathFlat -- cairo_copy_path_flat — Gets a flattened copy of the current path

Description

Object oriented style (method):

public CairoPath CairoContext::copyPathFlat ( void )

Procedural style:

CairoPath cairo_copy_path_flat ( CairoContext $context )

Description here.

Parameters

context

Description...

Return Values

Gets a flattened copy of the current path and returns it to the user as a CairoPath.

This function is like CairoContext::copyPath except that any curves in the path will be approximated with piecewise-linear approximations, (accurate to within the current tolerance value). That is, the result is guaranteed to not have any elements of type CAIRO_PATH_CURVE_TO which will instead be replaced by a series of CAIRO_PATH_LINE_TO elements.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->copyPathFlat());

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_copy_path_flat($context));

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

See Also

  • CairoContext::copyPath - Creates a copy of the current path
  • CairoContext::closePath - Closes the current path

CairoContext::copyPath
CairoContext::curveTo
CairoContext


Adds a curve

CairoContext::copyPathFlat
CairoContext::deviceToUser
CairoContext
PHP Manual

CairoContext::curveTo

cairo_curve_to

(PECL cairo >= 0.1.0)

CairoContext::curveTo -- cairo_curve_to — Adds a curve

Description

Object oriented style (method):

public void CairoContext::curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Procedural style:

void cairo_curve_to ( CairoContext $context , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Adds a cubic Bezier spline to the path from the current point to position x3 ,y3 in user-space coordinates, using x1 , y1 and x2 , y2 as the control points. After this call the current point will be x3 , y3 .

If there is no current point before the call to CairoContext::curveTo this function will behave as if preceded by a call to CairoContext::moveTo (x1 , y1 ).

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

x1

First control point in the x axis for the curve

y1

First control point in the y axis for the curve

x2

Second control point in x axis for the curve

y2

Second control point in y axis for the curve

x3

Final point in the x axis for the curve

y3

Final point in the y axis for the curve

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContext::moveTo - The moveTo purpose

CairoContext::copyPathFlat
CairoContext::deviceToUser
CairoContext


Transform a coordinate

CairoContext::curveTo
CairoContext::deviceToUserDistance
CairoContext
PHP Manual

CairoContext::deviceToUser

cairo_device_to_user

(PECL cairo >= 0.1.0)

CairoContext::deviceToUser -- cairo_device_to_user — Transform a coordinate

Description

Object oriented style (method):

public array CairoContext::deviceToUser ( float $x , float $y )

Procedural style:

array cairo_device_to_user ( CairoContext $context , float $x , float $y )

Transform a coordinate from device space to user space by multiplying the given point by the inverse of the current transformation matrix (CTM).

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

x

x value of the coordinate

y

y value of the coordinate

Return Values

An array containing the x and y coordinates in the user-space

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContext::deviceToUserDistance - Transform a distance

CairoContext::curveTo
CairoContext::deviceToUserDistance
CairoContext


Transform a distance

CairoContext::deviceToUser
CairoContext::fill
CairoContext
PHP Manual

CairoContext::deviceToUserDistance

cairo_device_to_user_distance

(PECL cairo >= 0.1.0)

CairoContext::deviceToUserDistance -- cairo_device_to_user_distance — Transform a distance

Description

Object oriented style (method):

public array CairoContext::deviceToUserDistance ( float $x , float $y )

Procedural style:

array cairo_device_to_user_distance ( CairoContext $context , float $x , float $y )

Transform a distance vector from device space to user space. This function is similar to CairoContext::deviceToUser or cairo_device_to_user() except that the translation components of the inverse Cairo Transformation Matrix will be ignored when transforming (x ,y ).

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

x

X component of a distance vector

y

Y component of a distance vector

Return Values

Returns an array with the x and y values of a distance vector in the user-space

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContext::deviceToUser - Transform a coordinate

CairoContext::deviceToUser
CairoContext::fill
CairoContext


Fills the current path

CairoContext::deviceToUserDistance
CairoContext::fillExtents
CairoContext
PHP Manual

CairoContext::fill

cairo_fill

(PECL cairo >= 0.1.0)

CairoContext::fill -- cairo_fill — Fills the current path

Description

Object oriented style (method):

public void CairoContext::fill ( void )

Procedural style:

void cairo_fill ( CairoContext $context )

A drawing operator that fills the current path according to the current CairoFillRule, (each sub-path is implicitly closed before being filled). After CairoContext::fill or cairo_fill(), the current path will be cleared from the CairoContext.

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContext::setFillRule - The setFillRule purpose
  • ContextContext::fillPreserve
  • CairoFillRule

CairoContext::deviceToUserDistance
CairoContext::fillExtents
CairoContext


Computes the filled area

CairoContext::fill
CairoContext::fillPreserve
CairoContext
PHP Manual

CairoContext::fillExtents

cairo_fill_extents

(PECL cairo >= 0.1.0)

CairoContext::fillExtents -- cairo_fill_extents — Computes the filled area

Description

Object oriented style (method):

public array CairoContext::fillExtents ( void )

Procedural style:

array cairo_fill_extents ( CairoContext $context )

Computes a bounding box in user coordinates covering the area that would be affected, (the “inked” area), by a CairoContext::fill operation given the current path and fill parameters. If the current path is empty, returns an empty rectangle (0,0,0,0). Surface dimensions and clipping are not taken into account.

Contrast with CairoContext::pathExtents, which is similar, but returns non-zero extents for some paths with no inked area, (such as a simple line segment).

Note that CairoContext::fillExtents must necessarily do more work to compute the precise inked areas in light of the fill rule, so CairoContext::pathExtents may be more desirable for sake of performance if the non-inked path extents are desired.

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

Return Values

An array with the coordinates of the afected area

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContext::fill - Fills the current path
  • CairoContext::setFillRule - The setFillRule purpose
  • CairoContext::fillPreserve - Fills and preserve the current path

CairoContext::fill
CairoContext::fillPreserve
CairoContext


Fills and preserve the current path

CairoContext::fillExtents
CairoContext::fontExtents
CairoContext
PHP Manual

CairoContext::fillPreserve

cairo_fill_preserve

(PECL cairo >= 0.1.0)

CairoContext::fillPreserve -- cairo_fill_preserve — Fills and preserve the current path

Description

Object oriented style (method):

public void CairoContext::fillPreserve ( void )

Procedural style:

void cairo_fill_preserve ( CairoContext $context )

A drawing operator that fills the current path according to the current CairoFillRule, (each sub-path is implicitly closed before being filled). Unlike CairoContext::fill, CairoContext::fillPreserve (Procedural cairo_fill(), cairo_fill_preserve(), respectively) preserves the path within the Context.

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContext::setFillRule - The setFillRule purpose
  • CairoContext::fill - Fills the current path

CairoContext::fillExtents
CairoContext::fontExtents
CairoContext


Get the font extents

CairoContext::fillPreserve
CairoContext::getAntialias
CairoContext
PHP Manual

CairoContext::fontExtents

cairo_font_extents

(PECL cairo >= 0.1.0)

CairoContext::fontExtents -- cairo_font_extents — Get the font extents

Description

Object oriented style (method):

public array CairoContext::fontExtents ( void )

Procedural style:

array cairo_font_extents ( CairoContext $context )

Gets the font extents for the currently selected font.

Parameters

context

Description...

Return Values

An array containing the font extents for the current font.

Examples

Example #1 Object oriented style

<?php

$sur = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$con = new CairoContext($sur);

var_dump($con->fontExtents());

?>

The above example will output something similar to:

array(5) {
  ["ascent"]=>
  float(10)
  ["descent"]=>
  float(3)
  ["height"]=>
  float(13.3125)
  ["max_x_advance"]=>
  float(26.65625)
  ["max_y_advance"]=>
  float(0)
}

Example #2 Procedural style

<?php

$sur = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$con = cairo_create($sur);

var_dump(cairo_font_extents($con));

?>

The above example will output something similar to:

array(5) {
  ["ascent"]=>
  float(10)
  ["descent"]=>
  float(3)
  ["height"]=>
  float(13.3125)
  ["max_x_advance"]=>
  float(26.65625)
  ["max_y_advance"]=>
  float(0)
}

See Also

  • Classname::Method

CairoContext::fillPreserve
CairoContext::getAntialias
CairoContext


Retrives the current antialias mode

CairoContext::fontExtents
CairoContext::getCurrentPoint
CairoContext
PHP Manual

CairoContext::getAntialias

cairo_get_antialias

(PECL cairo >= 0.1.0)

CairoContext::getAntialias -- cairo_get_antialias — Retrives the current antialias mode

Description

Object oriented style (method):

public int CairoContext::getAntialias ( void )

Procedural style:

int cairo_get_antialias ( CairoContext $context )

Returns the current CairoAntialias mode, as set by CairoContext::setAntialias.

Parameters

context

A valid CairoContext object created with CairoContext::__construct or cairo_create()

Return Values

The current CairoAntialias mode.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$context = new CairoContext($surface);

$context->setAntialias(CairoAntialias::MODE_SUBPIXEL);

var_dump($context->getAntialias());

?>

The above example will output something similar to:

int(3)

Example #2 Procedural style

<?php

$sur = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$con = cairo_create($sur);

cairo_set_antialias($con, CAIRO_ANTIALIAS_SUBPIXEL);

var_dump(cairo_get_antialias($con));

?>

The above example will output something similar to:

int(3)

See Also

  • CairoContext::setAntialias - The setAntialias purpose

CairoContext::fontExtents
CairoContext::getCurrentPoint
CairoContext


The getCurrentPoint purpose

CairoContext::getAntialias
CairoContext::getDash
CairoContext
PHP Manual

CairoContext::getCurrentPoint

cairo_get_current_point

(PECL cairo >= 0.1.0)

CairoContext::getCurrentPoint -- cairo_get_current_point — The getCurrentPoint purpose

Description

Object oriented style (method):

public array CairoContext::getCurrentPoint ( void )

Procedural style:

array cairo_get_current_point ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getAntialias
CairoContext::getDash
CairoContext


The getDash purpose

CairoContext::getCurrentPoint
CairoContext::getDashCount
CairoContext
PHP Manual

CairoContext::getDash

cairo_get_dash

(PECL cairo >= 0.1.0)

CairoContext::getDash -- cairo_get_dash — The getDash purpose

Description

Object oriented style (method):

public array CairoContext::getDash ( void )

Procedural style:

array cairo_get_dash ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getCurrentPoint
CairoContext::getDashCount
CairoContext


The getDashCount purpose

CairoContext::getDash
CairoContext::getFillRule
CairoContext
PHP Manual

CairoContext::getDashCount

cairo_get_dash_count

(PECL cairo >= 0.1.0)

CairoContext::getDashCount -- cairo_get_dash_count — The getDashCount purpose

Description

Object oriented style (method):

public int CairoContext::getDashCount ( void )

Procedural style:

int cairo_get_dash_count ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getDash
CairoContext::getFillRule
CairoContext


The getFillRule purpose

CairoContext::getDashCount
CairoContext::getFontFace
CairoContext
PHP Manual

CairoContext::getFillRule

cairo_get_fill_rule

(PECL cairo >= 0.1.0)

CairoContext::getFillRule -- cairo_get_fill_rule — The getFillRule purpose

Description

Object oriented style (method):

public int CairoContext::getFillRule ( void )

Procedural style:

int cairo_get_fill_rule ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getDashCount
CairoContext::getFontFace
CairoContext


The getFontFace purpose

CairoContext::getFillRule
CairoContext::getFontMatrix
CairoContext
PHP Manual

CairoContext::getFontFace

cairo_get_font_face

(PECL cairo >= 0.1.0)

CairoContext::getFontFace -- cairo_get_font_face — The getFontFace purpose

Description

Object oriented style (method):

public void CairoContext::getFontFace ( void )

Procedural style:

void cairo_get_font_face ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getFillRule
CairoContext::getFontMatrix
CairoContext


The getFontMatrix purpose

CairoContext::getFontFace
CairoContext::getFontOptions
CairoContext
PHP Manual

CairoContext::getFontMatrix

cairo_get_font_matrix

(PECL cairo >= 0.1.0)

CairoContext::getFontMatrix -- cairo_get_font_matrix — The getFontMatrix purpose

Description

Object oriented style (method):

public void CairoContext::getFontMatrix ( void )

Procedural style:

void cairo_get_font_matrix ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getFontFace
CairoContext::getFontOptions
CairoContext


The getFontOptions purpose

CairoContext::getFontMatrix
CairoContext::getGroupTarget
CairoContext
PHP Manual

CairoContext::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoContext::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Description

Object oriented style (method):

public void CairoContext::getFontOptions ( void )

Procedural style:

void cairo_get_font_options ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getFontMatrix
CairoContext::getGroupTarget
CairoContext


The getGroupTarget purpose

CairoContext::getFontOptions
CairoContext::getLineCap
CairoContext
PHP Manual

CairoContext::getGroupTarget

cairo_get_group_target

(PECL cairo >= 0.1.0)

CairoContext::getGroupTarget -- cairo_get_group_target — The getGroupTarget purpose

Description

Object oriented style (method):

public void CairoContext::getGroupTarget ( void )

Procedural style:

void cairo_get_group_target ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getFontOptions
CairoContext::getLineCap
CairoContext


The getLineCap purpose

CairoContext::getGroupTarget
CairoContext::getLineJoin
CairoContext
PHP Manual

CairoContext::getLineCap

cairo_get_line_cap

(PECL cairo >= 0.1.0)

CairoContext::getLineCap -- cairo_get_line_cap — The getLineCap purpose

Description

Object oriented style (method):

public int CairoContext::getLineCap ( void )

Procedural style:

int cairo_get_line_cap ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getGroupTarget
CairoContext::getLineJoin
CairoContext


The getLineJoin purpose

CairoContext::getLineCap
CairoContext::getLineWidth
CairoContext
PHP Manual

CairoContext::getLineJoin

cairo_get_line_join

(PECL cairo >= 0.1.0)

CairoContext::getLineJoin -- cairo_get_line_join — The getLineJoin purpose

Description

Object oriented style (method):

public int CairoContext::getLineJoin ( void )

Procedural style:

int cairo_get_line_join ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getLineCap
CairoContext::getLineWidth
CairoContext


The getLineWidth purpose

CairoContext::getLineJoin
CairoContext::getMatrix
CairoContext
PHP Manual

CairoContext::getLineWidth

cairo_get_line_width

(PECL cairo >= 0.1.0)

CairoContext::getLineWidth -- cairo_get_line_width — The getLineWidth purpose

Description

Object oriented style (method):

public float CairoContext::getLineWidth ( void )

Procedural style:

float cairo_get_line_width ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getLineJoin
CairoContext::getMatrix
CairoContext


The getMatrix purpose

CairoContext::getLineWidth
CairoContext::getMiterLimit
CairoContext
PHP Manual

CairoContext::getMatrix

cairo_get_matrix

(PECL cairo >= 0.1.0)

CairoContext::getMatrix -- cairo_get_matrix — The getMatrix purpose

Description

Object oriented style (method):

public void CairoContext::getMatrix ( void )

Procedural style:

void cairo_get_matrix ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getLineWidth
CairoContext::getMiterLimit
CairoContext


The getMiterLimit purpose

CairoContext::getMatrix
CairoContext::getOperator
CairoContext
PHP Manual

CairoContext::getMiterLimit

cairo_get_miter_limit

(PECL cairo >= 0.1.0)

CairoContext::getMiterLimit -- cairo_get_miter_limit — The getMiterLimit purpose

Description

Object oriented style (method):

public float CairoContext::getMiterLimit ( void )

Procedural style:

float cairo_get_miter_limit ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getMatrix
CairoContext::getOperator
CairoContext


The getOperator purpose

CairoContext::getMiterLimit
CairoContext::getScaledFont
CairoContext
PHP Manual

CairoContext::getOperator

cairo_get_operator

(PECL cairo >= 0.1.0)

CairoContext::getOperator -- cairo_get_operator — The getOperator purpose

Description

Object oriented style (method):

public int CairoContext::getOperator ( void )

Procedural style:

int cairo_get_operator ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getMiterLimit
CairoContext::getScaledFont
CairoContext


The getScaledFont purpose

CairoContext::getOperator
CairoContext::getSource
CairoContext
PHP Manual

CairoContext::getScaledFont

cairo_get_scaled_font

(PECL cairo >= 0.1.0)

CairoContext::getScaledFont -- cairo_get_scaled_font — The getScaledFont purpose

Description

Object oriented style (method):

public void CairoContext::getScaledFont ( void )

Procedural style:

void cairo_get_scaled_font ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getOperator
CairoContext::getSource
CairoContext


The getSource purpose

CairoContext::getScaledFont
CairoContext::getTarget
CairoContext
PHP Manual

CairoContext::getSource

cairo_get_source

(PECL cairo >= 0.1.0)

CairoContext::getSource -- cairo_get_source — The getSource purpose

Description

Object oriented style (method):

public void CairoContext::getSource ( void )

Procedural style:

void cairo_get_source ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getScaledFont
CairoContext::getTarget
CairoContext


The getTarget purpose

CairoContext::getSource
CairoContext::getTolerance
CairoContext
PHP Manual

CairoContext::getTarget

cairo_get_target

(PECL cairo >= 0.1.0)

CairoContext::getTarget -- cairo_get_target — The getTarget purpose

Description

Object oriented style (method):

public void CairoContext::getTarget ( void )

Procedural style:

void cairo_get_target ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getSource
CairoContext::getTolerance
CairoContext


The getTolerance purpose

CairoContext::getTarget
CairoContext::glyphPath
CairoContext
PHP Manual

CairoContext::getTolerance

cairo_get_tolerance

(PECL cairo >= 0.1.0)

CairoContext::getTolerance -- cairo_get_tolerance — The getTolerance purpose

Description

Object oriented style (method):

public float CairoContext::getTolerance ( void )

Procedural style:

float cairo_get_tolerance ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getTarget
CairoContext::glyphPath
CairoContext


The glyphPath purpose

CairoContext::getTolerance
CairoContext::hasCurrentPoint
CairoContext
PHP Manual

CairoContext::glyphPath

cairo_glyph_path

(PECL cairo >= 0.1.0)

CairoContext::glyphPath -- cairo_glyph_path — The glyphPath purpose

Description

Object oriented style (method):

public void CairoContext::glyphPath ( array $glyphs )

Procedural style:

void cairo_glyph_path ( CairoContext $context , array $glyphs )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

glyphs

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::getTolerance
CairoContext::hasCurrentPoint
CairoContext


The hasCurrentPoint purpose

CairoContext::glyphPath
CairoContext::identityMatrix
CairoContext
PHP Manual

CairoContext::hasCurrentPoint

cairo_has_current_point

(PECL cairo >= 0.1.0)

CairoContext::hasCurrentPoint -- cairo_has_current_point — The hasCurrentPoint purpose

Description

Object oriented style (method):

public bool CairoContext::hasCurrentPoint ( void )

Procedural style:

bool cairo_has_current_point ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::glyphPath
CairoContext::identityMatrix
CairoContext


The identityMatrix purpose

CairoContext::hasCurrentPoint
CairoContext::inFill
CairoContext
PHP Manual

CairoContext::identityMatrix

cairo_identity_matrix

(PECL cairo >= 0.1.0)

CairoContext::identityMatrix -- cairo_identity_matrix — The identityMatrix purpose

Description

Object oriented style (method):

public void CairoContext::identityMatrix ( void )

Procedural style:

void cairo_identity_matrix ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::hasCurrentPoint
CairoContext::inFill
CairoContext


The inFill purpose

CairoContext::identityMatrix
CairoContext::inStroke
CairoContext
PHP Manual

CairoContext::inFill

cairo_in_fill

(PECL cairo >= 0.1.0)

CairoContext::inFill -- cairo_in_fill — The inFill purpose

Description

Object oriented style (method):

public bool CairoContext::inFill ( string $x , string $y )

Procedural style:

bool cairo_in_fill ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::identityMatrix
CairoContext::inStroke
CairoContext


The inStroke purpose

CairoContext::inFill
CairoContext::lineTo
CairoContext
PHP Manual

CairoContext::inStroke

cairo_in_stroke

(PECL cairo >= 0.1.0)

CairoContext::inStroke -- cairo_in_stroke — The inStroke purpose

Description

Object oriented style (method):

public bool CairoContext::inStroke ( string $x , string $y )

Procedural style:

bool cairo_in_stroke ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::inFill
CairoContext::lineTo
CairoContext


The lineTo purpose

CairoContext::inStroke
CairoContext::mask
CairoContext
PHP Manual

CairoContext::lineTo

cairo_line_to

(PECL cairo >= 0.1.0)

CairoContext::lineTo -- cairo_line_to — The lineTo purpose

Description

Object oriented style (method):

public void CairoContext::lineTo ( string $x , string $y )

Procedural style:

void cairo_line_to ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::inStroke
CairoContext::mask
CairoContext


The mask purpose

CairoContext::lineTo
CairoContext::maskSurface
CairoContext
PHP Manual

CairoContext::mask

cairo_mask

(PECL cairo >= 0.1.0)

CairoContext::mask -- cairo_mask — The mask purpose

Description

Object oriented style (method):

public void CairoContext::mask ( string $pattern )

Procedural style:

void cairo_mask ( CairoContext $context , CairoPattern $pattern )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

pattern

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::lineTo
CairoContext::maskSurface
CairoContext


The maskSurface purpose

CairoContext::mask
CairoContext::moveTo
CairoContext
PHP Manual

CairoContext::maskSurface

cairo_mask_surface

(PECL cairo >= 0.1.0)

CairoContext::maskSurface -- cairo_mask_surface — The maskSurface purpose

Description

Object oriented style (method):

public void CairoContext::maskSurface ( string $surface [, string $x [, string $y ]] )

Procedural style:

void cairo_mask_surface ( CairoContext $context , CairoSurface $surface [, string $x [, string $y ]] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

surface

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::mask
CairoContext::moveTo
CairoContext


The moveTo purpose

CairoContext::maskSurface
CairoContext::newPath
CairoContext
PHP Manual

CairoContext::moveTo

cairo_move_to

(PECL cairo >= 0.1.0)

CairoContext::moveTo -- cairo_move_to — The moveTo purpose

Description

Object oriented style (method):

public void CairoContext::moveTo ( string $x , string $y )

Procedural style:

void cairo_move_to ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::maskSurface
CairoContext::newPath
CairoContext


The newPath purpose

CairoContext::moveTo
CairoContext::newSubPath
CairoContext
PHP Manual

CairoContext::newPath

cairo_new_path

(PECL cairo >= 0.1.0)

CairoContext::newPath -- cairo_new_path — The newPath purpose

Description

Object oriented style (method):

public void CairoContext::newPath ( void )

Procedural style:

void cairo_new_path ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::moveTo
CairoContext::newSubPath
CairoContext


The newSubPath purpose

CairoContext::newPath
CairoContext::paint
CairoContext
PHP Manual

CairoContext::newSubPath

cairo_new_sub_path

(PECL cairo >= 0.1.0)

CairoContext::newSubPath -- cairo_new_sub_path — The newSubPath purpose

Description

Object oriented style (method):

public void CairoContext::newSubPath ( void )

Procedural style:

void cairo_new_sub_path ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::newPath
CairoContext::paint
CairoContext


The paint purpose

CairoContext::newSubPath
CairoContext::paintWithAlpha
CairoContext
PHP Manual

CairoContext::paint

cairo_paint

(PECL cairo >= 0.1.0)

CairoContext::paint -- cairo_paint — The paint purpose

Description

Object oriented style (method):

public void CairoContext::paint ( void )

Procedural style:

void cairo_paint ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::newSubPath
CairoContext::paintWithAlpha
CairoContext


The paintWithAlpha purpose

CairoContext::paint
CairoContext::pathExtents
CairoContext
PHP Manual

CairoContext::paintWithAlpha

cairo_paint_with_alpha

(PECL cairo >= 0.1.0)

CairoContext::paintWithAlpha -- cairo_paint_with_alpha — The paintWithAlpha purpose

Description

Object oriented style (method):

public void CairoContext::paintWithAlpha ( string $alpha )

Procedural style:

void cairo_paint_with_alpha ( CairoContext $context , string $alpha )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::paint
CairoContext::pathExtents
CairoContext


The pathExtents purpose

CairoContext::paintWithAlpha
CairoContext::popGroup
CairoContext
PHP Manual

CairoContext::pathExtents

cairo_path_extents

(PECL cairo >= 0.1.0)

CairoContext::pathExtents -- cairo_path_extents — The pathExtents purpose

Description

Object oriented style (method):

public array CairoContext::pathExtents ( void )

Procedural style:

array cairo_path_extents ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::paintWithAlpha
CairoContext::popGroup
CairoContext


The popGroup purpose

CairoContext::pathExtents
CairoContext::popGroupToSource
CairoContext
PHP Manual

CairoContext::popGroup

cairo_pop_group

(PECL cairo >= 0.1.0)

CairoContext::popGroup -- cairo_pop_group — The popGroup purpose

Description

Object oriented style (method):

public void CairoContext::popGroup ( void )

Procedural style:

void cairo_pop_group ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::pathExtents
CairoContext::popGroupToSource
CairoContext


The popGroupToSource purpose

CairoContext::popGroup
CairoContext::pushGroup
CairoContext
PHP Manual

CairoContext::popGroupToSource

cairo_pop_group_to_source

(PECL cairo >= 0.1.0)

CairoContext::popGroupToSource -- cairo_pop_group_to_source — The popGroupToSource purpose

Description

Object oriented style (method):

public void CairoContext::popGroupToSource ( void )

Procedural style:

void cairo_pop_group_to_source ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::popGroup
CairoContext::pushGroup
CairoContext


The pushGroup purpose

CairoContext::popGroupToSource
CairoContext::pushGroupWithContent
CairoContext
PHP Manual

CairoContext::pushGroup

cairo_push_group

(PECL cairo >= 0.1.0)

CairoContext::pushGroup -- cairo_push_group — The pushGroup purpose

Description

Object oriented style (method):

public void CairoContext::pushGroup ( void )

Procedural style:

void cairo_push_group ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::popGroupToSource
CairoContext::pushGroupWithContent
CairoContext


The pushGroupWithContent purpose

CairoContext::pushGroup
CairoContext::rectangle
CairoContext
PHP Manual

CairoContext::pushGroupWithContent

cairo_push_group_with_content

(PECL cairo >= 0.1.0)

CairoContext::pushGroupWithContent -- cairo_push_group_with_content — The pushGroupWithContent purpose

Description

Object oriented style (method):

public void CairoContext::pushGroupWithContent ( string $content )

Procedural style:

void cairo_push_group_with_content ( CairoContext $context , string $content )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

content

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::pushGroup
CairoContext::rectangle
CairoContext


The rectangle purpose

CairoContext::pushGroupWithContent
CairoContext::relCurveTo
CairoContext
PHP Manual

CairoContext::rectangle

cairo_rectangle

(PECL cairo >= 0.1.0)

CairoContext::rectangle -- cairo_rectangle — The rectangle purpose

Description

Object oriented style (method):

public void CairoContext::rectangle ( string $x , string $y , string $width , string $height )

Procedural style:

void cairo_rectangle ( CairoContext $context , string $x , string $y , string $width , string $height )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::pushGroupWithContent
CairoContext::relCurveTo
CairoContext


The relCurveTo purpose

CairoContext::rectangle
CairoContext::relLineTo
CairoContext
PHP Manual

CairoContext::relCurveTo

cairo_rel_curve_to

(PECL cairo >= 0.1.0)

CairoContext::relCurveTo -- cairo_rel_curve_to — The relCurveTo purpose

Description

Object oriented style (method):

public void CairoContext::relCurveTo ( string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )

Procedural style:

void cairo_rel_curve_to ( CairoContext $context , string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x1

Description...

y1

Description...

x2

Description...

y2

Description...

x3

Description...

y3

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::rectangle
CairoContext::relLineTo
CairoContext


The relLineTo purpose

CairoContext::relCurveTo
CairoContext::relMoveTo
CairoContext
PHP Manual

CairoContext::relLineTo

cairo_rel_line_to

(PECL cairo >= 0.1.0)

CairoContext::relLineTo -- cairo_rel_line_to — The relLineTo purpose

Description

Object oriented style (method):

public void CairoContext::relLineTo ( string $x , string $y )

Procedural style:

void cairo_rel_line_to ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::relCurveTo
CairoContext::relMoveTo
CairoContext


The relMoveTo purpose

CairoContext::relLineTo
CairoContext::resetClip
CairoContext
PHP Manual

CairoContext::relMoveTo

cairo_rel_move_to

(PECL cairo >= 0.1.0)

CairoContext::relMoveTo -- cairo_rel_move_to — The relMoveTo purpose

Description

Object oriented style (method):

public void CairoContext::relMoveTo ( string $x , string $y )

Procedural style:

void cairo_rel_move_to ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::relLineTo
CairoContext::resetClip
CairoContext


The resetClip purpose

CairoContext::relMoveTo
CairoContext::restore
CairoContext
PHP Manual

CairoContext::resetClip

cairo_reset_clip

(PECL cairo >= 0.1.0)

CairoContext::resetClip -- cairo_reset_clip — The resetClip purpose

Description

Object oriented style (method):

public void CairoContext::resetClip ( void )

Procedural style:

void cairo_reset_clip ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::relMoveTo
CairoContext::restore
CairoContext


The restore purpose

CairoContext::resetClip
CairoContext::rotate
CairoContext
PHP Manual

CairoContext::restore

cairo_restore

(PECL cairo >= 0.1.0)

CairoContext::restore -- cairo_restore — The restore purpose

Description

Object oriented style (method):

public void CairoContext::restore ( void )

Procedural style:

void cairo_restore ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::resetClip
CairoContext::rotate
CairoContext


The rotate purpose

CairoContext::restore
CairoContext::save
CairoContext
PHP Manual

CairoContext::rotate

cairo_rotate

(PECL cairo >= 0.1.0)

CairoContext::rotate -- cairo_rotate — The rotate purpose

Description

Object oriented style (method):

public void CairoContext::rotate ( string $angle )

Procedural style:

void cairo_rotate ( CairoContext $context , string $angle )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

angle

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::restore
CairoContext::save
CairoContext


The save purpose

CairoContext::rotate
CairoContext::scale
CairoContext
PHP Manual

CairoContext::save

cairo_save

(PECL cairo >= 0.1.0)

CairoContext::save -- cairo_save — The save purpose

Description

Object oriented style (method):

public void CairoContext::save ( void )

Procedural style:

void cairo_save ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::rotate
CairoContext::scale
CairoContext


The scale purpose

CairoContext::save
CairoContext::selectFontFace
CairoContext
PHP Manual

CairoContext::scale

cairo_scale

(PECL cairo >= 0.1.0)

CairoContext::scale -- cairo_scale — The scale purpose

Description

Object oriented style (method):

public void CairoContext::scale ( string $x , string $y )

Procedural style:

void cairo_scale ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::save
CairoContext::selectFontFace
CairoContext


The selectFontFace purpose

CairoContext::scale
CairoContext::setAntialias
CairoContext
PHP Manual

CairoContext::selectFontFace

cairo_select_font_face

(PECL cairo >= 0.1.0)

CairoContext::selectFontFace -- cairo_select_font_face — The selectFontFace purpose

Description

Object oriented style (method):

public void CairoContext::selectFontFace ( string $family [, string $slant [, string $weight ]] )

Procedural style:

void cairo_select_font_face ( CairoContext $context , string $family [, string $slant [, string $weight ]] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

family

Description...

slant

Description...

weight

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::scale
CairoContext::setAntialias
CairoContext


The setAntialias purpose

CairoContext::selectFontFace
CairoContext::setDash
CairoContext
PHP Manual

CairoContext::setAntialias

cairo_set_antialias

(PECL cairo >= 0.1.0)

CairoContext::setAntialias -- cairo_set_antialias — The setAntialias purpose

Description

Object oriented style (method):

public void CairoContext::setAntialias ([ string $antialias ] )

Procedural style:

void cairo_set_antialias ( CairoContext $context [, string $antialias ] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

antialias

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::selectFontFace
CairoContext::setDash
CairoContext


The setDash purpose

CairoContext::setAntialias
CairoContext::setFillRule
CairoContext
PHP Manual

CairoContext::setDash

cairo_set_dash

(PECL cairo >= 0.1.0)

CairoContext::setDash -- cairo_set_dash — The setDash purpose

Description

Object oriented style (method):

public void CairoContext::setDash ( string $dashes [, string $offset ] )

Procedural style:

void cairo_set_dash ( CairoContext $context , array $dashes [, string $offset ] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

dashes

Description...

offset

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setAntialias
CairoContext::setFillRule
CairoContext


The setFillRule purpose

CairoContext::setDash
CairoContext::setFontFace
CairoContext
PHP Manual

CairoContext::setFillRule

cairo_set_fill_rule

(PECL cairo >= 0.1.0)

CairoContext::setFillRule -- cairo_set_fill_rule — The setFillRule purpose

Description

Object oriented style (method):

public void CairoContext::setFillRule ( string $setting )

Procedural style:

void cairo_set_fill_rule ( CairoContext $context , string $setting )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setDash
CairoContext::setFontFace
CairoContext


The setFontFace purpose

CairoContext::setFillRule
CairoContext::setFontMatrix
CairoContext
PHP Manual

CairoContext::setFontFace

cairo_set_font_face

(PECL cairo >= 0.1.0)

CairoContext::setFontFace -- cairo_set_font_face — The setFontFace purpose

Description

Object oriented style (method):

public void CairoContext::setFontFace ( string $fontface )

Procedural style:

void cairo_set_font_face ( CairoContext $context , CairoFontFace $fontface )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

fontface

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setFillRule
CairoContext::setFontMatrix
CairoContext


The setFontMatrix purpose

CairoContext::setFontFace
CairoContext::setFontOptions
CairoContext
PHP Manual

CairoContext::setFontMatrix

cairo_set_font_matrix

(PECL cairo >= 0.1.0)

CairoContext::setFontMatrix -- cairo_set_font_matrix — The setFontMatrix purpose

Description

Object oriented style (method):

public void CairoContext::setFontMatrix ( string $matrix )

Procedural style:

void cairo_set_font_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setFontFace
CairoContext::setFontOptions
CairoContext


The setFontOptions purpose

CairoContext::setFontMatrix
CairoContext::setFontSize
CairoContext
PHP Manual

CairoContext::setFontOptions

cairo_set_font_options

(PECL cairo >= 0.1.0)

CairoContext::setFontOptions -- cairo_set_font_options — The setFontOptions purpose

Description

Object oriented style (method):

public void CairoContext::setFontOptions ( string $fontoptions )

Procedural style:

void cairo_set_font_options ( CairoContext $context , CairoFontOptions $fontoptions )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

fontoptions

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setFontMatrix
CairoContext::setFontSize
CairoContext


The setFontSize purpose

CairoContext::setFontOptions
CairoContext::setLineCap
CairoContext
PHP Manual

CairoContext::setFontSize

cairo_set_font_size

(PECL cairo >= 0.1.0)

CairoContext::setFontSize -- cairo_set_font_size — The setFontSize purpose

Description

Object oriented style (method):

public void CairoContext::setFontSize ( string $size )

Procedural style:

void cairo_set_font_size ( CairoContext $context , string $size )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

size

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setFontOptions
CairoContext::setLineCap
CairoContext


The setLineCap purpose

CairoContext::setFontSize
CairoContext::setLineJoin
CairoContext
PHP Manual

CairoContext::setLineCap

cairo_set_line_cap

(PECL cairo >= 0.1.0)

CairoContext::setLineCap -- cairo_set_line_cap — The setLineCap purpose

Description

Object oriented style (method):

public void CairoContext::setLineCap ( string $setting )

Procedural style:

void cairo_set_line_cap ( CairoContext $context , string $setting )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setFontSize
CairoContext::setLineJoin
CairoContext


The setLineJoin purpose

CairoContext::setLineCap
CairoContext::setLineWidth
CairoContext
PHP Manual

CairoContext::setLineJoin

cairo_set_line_join

(PECL cairo >= 0.1.0)

CairoContext::setLineJoin -- cairo_set_line_join — The setLineJoin purpose

Description

Object oriented style (method):

public void CairoContext::setLineJoin ( string $setting )

Procedural style:

void cairo_set_line_join ( CairoContext $context , string $setting )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setLineCap
CairoContext::setLineWidth
CairoContext


The setLineWidth purpose

CairoContext::setLineJoin
CairoContext::setMatrix
CairoContext
PHP Manual

CairoContext::setLineWidth

cairo_set_line_width

(PECL cairo >= 0.1.0)

CairoContext::setLineWidth -- cairo_set_line_width — The setLineWidth purpose

Description

Object oriented style (method):

public void CairoContext::setLineWidth ( string $width )

Procedural style:

void cairo_set_line_width ( CairoContext $context , string $width )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

width

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setLineJoin
CairoContext::setMatrix
CairoContext


The setMatrix purpose

CairoContext::setLineWidth
CairoContext::setMiterLimit
CairoContext
PHP Manual

CairoContext::setMatrix

cairo_set_matrix

(PECL cairo >= 0.1.0)

CairoContext::setMatrix -- cairo_set_matrix — The setMatrix purpose

Description

Object oriented style (method):

public void CairoContext::setMatrix ( string $matrix )

Procedural style:

void cairo_set_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setLineWidth
CairoContext::setMiterLimit
CairoContext


The setMiterLimit purpose

CairoContext::setMatrix
CairoContext::setOperator
CairoContext
PHP Manual

CairoContext::setMiterLimit

cairo_set_miter_limit

(PECL cairo >= 0.1.0)

CairoContext::setMiterLimit -- cairo_set_miter_limit — The setMiterLimit purpose

Description

Object oriented style (method):

public void CairoContext::setMiterLimit ( string $limit )

Procedural style:

void cairo_set_miter_limit ( CairoContext $context , string $limit )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

limit

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setMatrix
CairoContext::setOperator
CairoContext


The setOperator purpose

CairoContext::setMiterLimit
CairoContext::setScaledFont
CairoContext
PHP Manual

CairoContext::setOperator

cairo_set_operator

(PECL cairo >= 0.1.0)

CairoContext::setOperator -- cairo_set_operator — The setOperator purpose

Description

Object oriented style (method):

public void CairoContext::setOperator ( string $setting )

Procedural style:

void cairo_set_operator ( CairoContext $context , string $setting )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setMiterLimit
CairoContext::setScaledFont
CairoContext


The setScaledFont purpose

CairoContext::setOperator
CairoContext::setSource
CairoContext
PHP Manual

CairoContext::setScaledFont

cairo_set_scaled_font

(PECL cairo >= 0.1.0)

CairoContext::setScaledFont -- cairo_set_scaled_font — The setScaledFont purpose

Description

Object oriented style (method):

public void CairoContext::setScaledFont ( string $scaledfont )

Procedural style:

void cairo_set_scaled_font ( CairoContext $context , CairoScaledFont $scaledfont )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

scaledfont

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setOperator
CairoContext::setSource
CairoContext


The setSource purpose

CairoContext::setScaledFont
CairoContext::setSourceRGB
CairoContext
PHP Manual

CairoContext::setSource

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSource -- cairo_set_source — The setSource purpose

Description

Object oriented style (method):

public void CairoContext::setSource ( string $pattern )

Procedural style:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

pattern

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setScaledFont
CairoContext::setSourceRGB
CairoContext


The setSourceRGB purpose

CairoContext::setSource
CairoContext::setSourceRGBA
CairoContext
PHP Manual

CairoContext::setSourceRGB

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSourceRGB -- cairo_set_source — The setSourceRGB purpose

Description

Object oriented style (method):

public void CairoContext::setSourceRGB ( string $red , string $green , string $blue )

Procedural style:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

pattern

Description...

red

Description...

green

Description...

blue

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setSource
CairoContext::setSourceRGBA
CairoContext


The setSourceRGBA purpose

CairoContext::setSourceRGB
CairoContext::setSourceSurface
CairoContext
PHP Manual

CairoContext::setSourceRGBA

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSourceRGBA -- cairo_set_source — The setSourceRGBA purpose

Description

Object oriented style (method):

public void CairoContext::setSourceRGBA ( string $red , string $green , string $blue , string $alpha )

Procedural style:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

pattern

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setSourceRGB
CairoContext::setSourceSurface
CairoContext


The setSourceSurface purpose

CairoContext::setSourceRGBA
CairoContext::setTolerance
CairoContext
PHP Manual

CairoContext::setSourceSurface

cairo_set_source_surface

(PECL cairo >= 0.1.0)

CairoContext::setSourceSurface -- cairo_set_source_surface — The setSourceSurface purpose

Description

Object oriented style (method):

public void CairoContext::setSourceSurface ( string $surface [, string $x [, string $y ]] )

Procedural style:

void cairo_set_source_surface ( CairoContext $context , CairoSurface $surface [, string $x [, string $y ]] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

surface

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setSourceRGBA
CairoContext::setTolerance
CairoContext


The setTolerance purpose

CairoContext::setSourceSurface
CairoContext::showPage
CairoContext
PHP Manual

CairoContext::setTolerance

cairo_set_tolerance

(PECL cairo >= 0.1.0)

CairoContext::setTolerance -- cairo_set_tolerance — The setTolerance purpose

Description

Object oriented style (method):

public void CairoContext::setTolerance ( string $tolerance )

Procedural style:

void cairo_set_tolerance ( CairoContext $context , string $tolerance )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

tolerance

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setSourceSurface
CairoContext::showPage
CairoContext


The showPage purpose

CairoContext::setTolerance
CairoContext::showText
CairoContext
PHP Manual

CairoContext::showPage

cairo_show_page

(PECL cairo >= 0.1.0)

CairoContext::showPage -- cairo_show_page — The showPage purpose

Description

Object oriented style (method):

public void CairoContext::showPage ( void )

Procedural style:

void cairo_show_page ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::setTolerance
CairoContext::showText
CairoContext


The showText purpose

CairoContext::showPage
CairoContext::status
CairoContext
PHP Manual

CairoContext::showText

cairo_show_text

(PECL cairo >= 0.1.0)

CairoContext::showText -- cairo_show_text — The showText purpose

Description

Object oriented style (method):

public void CairoContext::showText ( string $text )

Procedural style:

void cairo_show_text ( CairoContext $context , string $text )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

text

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::showPage
CairoContext::status
CairoContext


The status purpose

CairoContext::showText
CairoContext::stroke
CairoContext
PHP Manual

CairoContext::status

cairo_status

(PECL cairo >= 0.1.0)

CairoContext::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public int CairoContext::status ( void )

Procedural style:

int cairo_status ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::showText
CairoContext::stroke
CairoContext


The stroke purpose

CairoContext::status
CairoContext::strokeExtents
CairoContext
PHP Manual

CairoContext::stroke

cairo_stroke

(PECL cairo >= 0.1.0)

CairoContext::stroke -- cairo_stroke — The stroke purpose

Description

Object oriented style (method):

public void CairoContext::stroke ( void )

Procedural style:

void cairo_stroke ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::status
CairoContext::strokeExtents
CairoContext


The strokeExtents purpose

CairoContext::stroke
CairoContext::strokePreserve
CairoContext
PHP Manual

CairoContext::strokeExtents

cairo_stroke_extents

(PECL cairo >= 0.1.0)

CairoContext::strokeExtents -- cairo_stroke_extents — The strokeExtents purpose

Description

Object oriented style (method):

public array CairoContext::strokeExtents ( void )

Procedural style:

array cairo_stroke_extents ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::stroke
CairoContext::strokePreserve
CairoContext


The strokePreserve purpose

CairoContext::strokeExtents
CairoContext::textExtents
CairoContext
PHP Manual

CairoContext::strokePreserve

cairo_stroke_preserve

(PECL cairo >= 0.1.0)

CairoContext::strokePreserve -- cairo_stroke_preserve — The strokePreserve purpose

Description

Object oriented style (method):

public void CairoContext::strokePreserve ( void )

Procedural style:

void cairo_stroke_preserve ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::strokeExtents
CairoContext::textExtents
CairoContext


The textExtents purpose

CairoContext::strokePreserve
CairoContext::textPath
CairoContext
PHP Manual

CairoContext::textExtents

cairo_text_extents

(PECL cairo >= 0.1.0)

CairoContext::textExtents -- cairo_text_extents — The textExtents purpose

Description

Object oriented style (method):

public array CairoContext::textExtents ( string $text )

Procedural style:

array cairo_text_extents ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

text

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::strokePreserve
CairoContext::textPath
CairoContext


The textPath purpose

CairoContext::textExtents
CairoContext::transform
CairoContext
PHP Manual

CairoContext::textPath

cairo_text_path

(PECL cairo >= 0.1.0)

CairoContext::textPath -- cairo_text_path — The textPath purpose

Description

Object oriented style (method):

public void CairoContext::textPath ( string $string )

Procedural style:

void cairo_text_path ( CairoContext $context , string $text )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

text

Description...

string

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::textExtents
CairoContext::transform
CairoContext


The transform purpose

CairoContext::textPath
CairoContext::translate
CairoContext
PHP Manual

CairoContext::transform

cairo_transform

(PECL cairo >= 0.1.0)

CairoContext::transform -- cairo_transform — The transform purpose

Description

Object oriented style (method):

public void CairoContext::transform ( string $matrix )

Procedural style:

void cairo_transform ( CairoContext $context , CairoMatrix $matrix )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::textPath
CairoContext::translate
CairoContext


The translate purpose

CairoContext::transform
CairoContext::userToDevice
CairoContext
PHP Manual

CairoContext::translate

cairo_translate

(PECL cairo >= 0.1.0)

CairoContext::translate -- cairo_translate — The translate purpose

Description

Object oriented style (method):

public void CairoContext::translate ( string $x , string $y )

Procedural style:

void cairo_translate ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::transform
CairoContext::userToDevice
CairoContext


The userToDevice purpose

CairoContext::translate
CairoContext::userToDeviceDistance
CairoContext
PHP Manual

CairoContext::userToDevice

cairo_user_to_device

(PECL cairo >= 0.1.0)

CairoContext::userToDevice -- cairo_user_to_device — The userToDevice purpose

Description

Object oriented style (method):

public array CairoContext::userToDevice ( string $x , string $y )

Procedural style:

array cairo_user_to_device ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::translate
CairoContext::userToDeviceDistance
CairoContext


The userToDeviceDistance purpose

CairoContext::userToDevice
CairoException
CairoContext
PHP Manual

CairoContext::userToDeviceDistance

cairo_user_to_device_distance

(PECL cairo >= 0.1.0)

CairoContext::userToDeviceDistance -- cairo_user_to_device_distance — The userToDeviceDistance purpose

Description

Object oriented style (method):

public array CairoContext::userToDeviceDistance ( string $x , string $y )

Procedural style:

array cairo_user_to_device_distance ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoContext::userToDevice
CairoException
CairoContext


Creates a new CairoFontFace object

CairoFontFace
CairoFontFace::getType
CairoFontFace
PHP Manual

CairoFontFace::__construct

(PECL cairo >= 0.1.0)

CairoFontFace::__construct — Creates a new CairoFontFace object

Description

CairoFontFace::__construct ( void )

CairoFontFace class represents a particular font at a particular weight, slant, and other characteristic but no transformation or size.

Note: This class can't be instantiated directly it is created by CairoContext::getFontFace or cairo_scaled_font_get_font_face()

Parameters

This function has no parameters.

Return Values

CairoFontFace

Examples

Example #1 CairoFontFace::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Class::Method

CairoFontFace
CairoFontFace::getType
CairoFontFace


Retrieves the font face type

CairoFontFace::__construct
CairoFontFace::status
CairoFontFace
PHP Manual

CairoFontFace::getType

(PECL cairo >= 0.1.0)

CairoFontFace::getType — Retrieves the font face type

Description

public int CairoFontFace::getType ( void )

This function returns the type of the backend used to create a font face. See CairoFontType class constants for available types.

Parameters

This function has no parameters.

Return Values

A font type that can be any one defined in CairoFontType

Examples

Example #1 CairoFontFace::getType example

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face type
var_dump($fontface->getType());

?>

The above example will output something similar to:

int(0)

See Also

  • Classname::Method

CairoFontFace::__construct
CairoFontFace::status
CairoFontFace


Check for CairoFontFace errors

CairoFontFace::getType
CairoFontOptions
CairoFontFace
PHP Manual

CairoFontFace::status

cairo_font_face_status

(PECL cairo >= 0.1.0)

CairoFontFace::status -- cairo_font_face_status — Check for CairoFontFace errors

Description

Object oriented style (method):

public int CairoFontFace::status ( void )

Procedural style:

int cairo_font_face_status ( CairoFontFace $fontface )

Checks whether an error has previously occurred for this font face

Parameters

fontface

A valid CairoFontFace object

Return Values

CAIRO_STATUS_SUCCESS or another error such as CAIRO_STATUS_NO_MEMORY.

Examples

Example #1 Object oriented style

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face status
var_dump($fontface->status()); // should be the value of CAIRO_STATUS_SUCCESS

?>

The above example will output something similar to:

int(0)

Example #2 Procedural style

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face status
var_dump(cairo_font_face_status($fontface)); // should be the value of CAIRO_STATUS_SUCCESS

?>

The above example will output something similar to:

int(0)

See Also

  • Classname::Method

CairoFontFace::getType
CairoFontOptions
CairoFontFace


The __construct purpose

CairoFontOptions
CairoFontOptions::equal
CairoFontOptions
PHP Manual

CairoFontOptions::__construct

(PECL cairo >= 0.1.0)

CairoFontOptions::__construct — The __construct purpose

Description

CairoFontOptions::__construct ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions
CairoFontOptions::equal
CairoFontOptions


The equal purpose

CairoFontOptions::__construct
CairoFontOptions::getAntialias
CairoFontOptions
PHP Manual

CairoFontOptions::equal

(PECL cairo >= 0.1.0)

CairoFontOptions::equal — The equal purpose

Description

public bool CairoFontOptions::equal ( string $other )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

other

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::equal example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::__construct
CairoFontOptions::getAntialias
CairoFontOptions


The getAntialias purpose

CairoFontOptions::equal
CairoFontOptions::getHintMetrics
CairoFontOptions
PHP Manual

CairoFontOptions::getAntialias

cairo_get_antialias

(PECL cairo >= 0.1.0)

CairoFontOptions::getAntialias -- cairo_get_antialias — The getAntialias purpose

Description

Object oriented style (method):

public int CairoFontOptions::getAntialias ( void )

Procedural style:

int cairo_get_antialias ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::equal
CairoFontOptions::getHintMetrics
CairoFontOptions


The getHintMetrics purpose

CairoFontOptions::getAntialias
CairoFontOptions::getHintStyle
CairoFontOptions
PHP Manual

CairoFontOptions::getHintMetrics

(PECL cairo >= 0.1.0)

CairoFontOptions::getHintMetrics — The getHintMetrics purpose

Description

public int CairoFontOptions::getHintMetrics ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::getHintMetrics example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::getAntialias
CairoFontOptions::getHintStyle
CairoFontOptions


The getHintStyle purpose

CairoFontOptions::getHintMetrics
CairoFontOptions::getSubpixelOrder
CairoFontOptions
PHP Manual

CairoFontOptions::getHintStyle

(PECL cairo >= 0.1.0)

CairoFontOptions::getHintStyle — The getHintStyle purpose

Description

public int CairoFontOptions::getHintStyle ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::getHintStyle example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::getHintMetrics
CairoFontOptions::getSubpixelOrder
CairoFontOptions


The getSubpixelOrder purpose

CairoFontOptions::getHintStyle
CairoFontOptions::hash
CairoFontOptions
PHP Manual

CairoFontOptions::getSubpixelOrder

(PECL cairo >= 0.1.0)

CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose

Description

public int CairoFontOptions::getSubpixelOrder ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::getSubpixelOrder example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::getHintStyle
CairoFontOptions::hash
CairoFontOptions


The hash purpose

CairoFontOptions::getSubpixelOrder
CairoFontOptions::merge
CairoFontOptions
PHP Manual

CairoFontOptions::hash

(PECL cairo >= 0.1.0)

CairoFontOptions::hash — The hash purpose

Description

public int CairoFontOptions::hash ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::hash example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::getSubpixelOrder
CairoFontOptions::merge
CairoFontOptions


The merge purpose

CairoFontOptions::hash
CairoFontOptions::setAntialias
CairoFontOptions
PHP Manual

CairoFontOptions::merge

(PECL cairo >= 0.1.0)

CairoFontOptions::merge — The merge purpose

Description

public void CairoFontOptions::merge ( string $other )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

other

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::merge example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::hash
CairoFontOptions::setAntialias
CairoFontOptions


The setAntialias purpose

CairoFontOptions::merge
CairoFontOptions::setHintMetrics
CairoFontOptions
PHP Manual

CairoFontOptions::setAntialias

cairo_set_antialias

(PECL cairo >= 0.1.0)

CairoFontOptions::setAntialias -- cairo_set_antialias — The setAntialias purpose

Description

Object oriented style (method):

public void CairoFontOptions::setAntialias ( string $antialias )

Procedural style:

void cairo_set_antialias ( CairoContext $context [, string $antialias ] )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

antialias

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::merge
CairoFontOptions::setHintMetrics
CairoFontOptions


The setHintMetrics purpose

CairoFontOptions::setAntialias
CairoFontOptions::setHintStyle
CairoFontOptions
PHP Manual

CairoFontOptions::setHintMetrics

(PECL cairo >= 0.1.0)

CairoFontOptions::setHintMetrics — The setHintMetrics purpose

Description

public void CairoFontOptions::setHintMetrics ( string $hint_metrics )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

hint_metrics

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::setHintMetrics example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::setAntialias
CairoFontOptions::setHintStyle
CairoFontOptions


The setHintStyle purpose

CairoFontOptions::setHintMetrics
CairoFontOptions::setSubpixelOrder
CairoFontOptions
PHP Manual

CairoFontOptions::setHintStyle

(PECL cairo >= 0.1.0)

CairoFontOptions::setHintStyle — The setHintStyle purpose

Description

public void CairoFontOptions::setHintStyle ( string $hint_style )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

hint_style

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::setHintStyle example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::setHintMetrics
CairoFontOptions::setSubpixelOrder
CairoFontOptions


The setSubpixelOrder purpose

CairoFontOptions::setHintStyle
CairoFontOptions::status
CairoFontOptions
PHP Manual

CairoFontOptions::setSubpixelOrder

(PECL cairo >= 0.1.0)

CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose

Description

public void CairoFontOptions::setSubpixelOrder ( string $subpixel_order )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

subpixel_order

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::setSubpixelOrder example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::setHintStyle
CairoFontOptions::status
CairoFontOptions


The status purpose

CairoFontOptions::setSubpixelOrder
CairoFontSlant
CairoFontOptions
PHP Manual

CairoFontOptions::status

cairo_status

(PECL cairo >= 0.1.0)

CairoFontOptions::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public int CairoFontOptions::status ( void )

Procedural style:

int cairo_status ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFontOptions::setSubpixelOrder
CairoFontSlant
CairoFontOptions


Provides an appropiate stride to use

CairoFormat
CairoFillRule
CairoFormat
PHP Manual

CairoFormat::strideForWidth

(PECL cairo >= 0.1.0)

CairoFormat::strideForWidth — Provides an appropiate stride to use

Description

public static int CairoFormat::strideForWidth ( int $format , int $width )

This method provides a stride value that will respect all alignment requirements of the accelerated image-rendering code within cairo.

Parameters

format

The desired CairoFormat to use

width

The width of the image

Return Values

The appropriate stride to use given the desired format and width, or -1 if either the format is invalid or the width too large.

Examples

Example #1 CairoFormat::strideForWidth example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoFormat
CairoFillRule
CairoFormat


The addColorStopRgb purpose

CairoGradientPattern
CairoGradientPattern::addColorStopRgba
CairoGradientPattern
PHP Manual

CairoGradientPattern::addColorStopRgb

(PECL cairo >= 0.1.0)

CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose

Description

public void CairoGradientPattern::addColorStopRgb ( string $offset , string $red , string $green , string $blue )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

offset

Description...

red

Description...

green

Description...

blue

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::addColorStopRgb example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoGradientPattern
CairoGradientPattern::addColorStopRgba
CairoGradientPattern


The addColorStopRgba purpose

CairoGradientPattern::addColorStopRgb
CairoGradientPattern::getColorStopCount
CairoGradientPattern
PHP Manual

CairoGradientPattern::addColorStopRgba

(PECL cairo >= 0.1.0)

CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose

Description

public void CairoGradientPattern::addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

offset

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::addColorStopRgba example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoGradientPattern::addColorStopRgb
CairoGradientPattern::getColorStopCount
CairoGradientPattern


The getColorStopCount purpose

CairoGradientPattern::addColorStopRgba
CairoGradientPattern::getColorStopRgba
CairoGradientPattern
PHP Manual

CairoGradientPattern::getColorStopCount

(PECL cairo >= 0.1.0)

CairoGradientPattern::getColorStopCount — The getColorStopCount purpose

Description

public int CairoGradientPattern::getColorStopCount ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoGradientPattern::getColorStopCount example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoGradientPattern::addColorStopRgba
CairoGradientPattern::getColorStopRgba
CairoGradientPattern


The getColorStopRgba purpose

CairoGradientPattern::getColorStopCount
CairoGradientPattern::getExtend
CairoGradientPattern
PHP Manual

CairoGradientPattern::getColorStopRgba

(PECL cairo >= 0.1.0)

CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose

Description

public array CairoGradientPattern::getColorStopRgba ( string $index )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::getColorStopRgba example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoGradientPattern::getColorStopCount
CairoGradientPattern::getExtend
CairoGradientPattern


The getExtend purpose

CairoGradientPattern::getColorStopRgba
CairoGradientPattern::setExtend
CairoGradientPattern
PHP Manual

CairoGradientPattern::getExtend

(PECL cairo >= 0.1.0)

CairoGradientPattern::getExtend — The getExtend purpose

Description

public int CairoGradientPattern::getExtend ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoGradientPattern::getExtend example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoGradientPattern::getColorStopRgba
CairoGradientPattern::setExtend
CairoGradientPattern


The setExtend purpose

CairoGradientPattern::getExtend
CairoSolidPattern
CairoGradientPattern
PHP Manual

CairoGradientPattern::setExtend

(PECL cairo >= 0.1.0)

CairoGradientPattern::setExtend — The setExtend purpose

Description

public void CairoGradientPattern::setExtend ( int $extend )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

extend

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::setExtend example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoGradientPattern::getExtend
CairoSolidPattern
CairoGradientPattern


Creates a new CairoImageSurface

CairoImageSurface
CairoImageSurface::createForData
CairoImageSurface
PHP Manual

CairoImageSurface::__construct

(PECL cairo >= 0.1.0)

CairoImageSurface::__construct — Creates a new CairoImageSurface

Description

CairoImageSurface::__construct ( int $format , int $width , int $height )

Creates a new CairoImageSuface object of type format

Parameters

format

Can be any defined in CairoFormat

width

The width of the image surface

height

The height of the image surface

Return Values

A new CairoImageSurface

Examples

Example #1 CairoImageSurface::__construct example

<?php

// Creates a image with ARGB32 format of 50 width and 50 height
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50,50);

?>

See Also

  • CairoContext::__construct - Creates a new CairoContext

CairoImageSurface
CairoImageSurface::createForData
CairoImageSurface


The createForData purpose

CairoImageSurface::__construct
CairoImageSurface::createFromPng
CairoImageSurface
PHP Manual

CairoImageSurface::createForData

(PECL cairo >= 0.1.0)

CairoImageSurface::createForData — The createForData purpose

Description

public static void CairoImageSurface::createForData ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

Description...

format

Description...

width

Description...

height

Description...

stride

Description...

Return Values

Description...

Examples

Example #1 CairoImageSurface::createForData example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoImageSurface::__construct
CairoImageSurface::createFromPng
CairoImageSurface


Creates a new CairoImageSurface form a png image file

CairoImageSurface::createForData
CairoImageSurface::getData
CairoImageSurface
PHP Manual

CairoImageSurface::createFromPng

(PECL cairo >= 0.1.0)

CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file

Description

public staticCairoImageSurface CairoImageSurface::createFromPng ( string $file )

Creates a new CairoImageSurface form a png image file

This method should be called static

Parameters

file

Path to PNG image file

Return Values

CairoImageSurface object

Examples

Example #1 CairoImageSurface::createFromPng example

<?php

$surface = CairoImageSurface::createFromPng('/path/to/image/file.png');

?>

The above example will output something similar to:

...

See Also

  • CairoImageSurface::__construct - Creates a new CairoImageSurface

CairoImageSurface::createForData
CairoImageSurface::getData
CairoImageSurface


Gets the image data as string

CairoImageSurface::createFromPng
CairoImageSurface::getFormat
CairoImageSurface
PHP Manual

CairoImageSurface::getData

(PECL cairo >= 0.1.0)

CairoImageSurface::getData — Gets the image data as string

Description

public string CairoImageSurface::getData ( void )

Returns the image data of this surface or NULL if surface is not an image surface, or if CairoContext::finish, procedural : cairo_surface_finish(), has been called.

Parameters

This function has no parameters.

Return Values

The image data as string

Examples

Example #1 CairoImageSurface::getData example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoImageSurface::getStride - The getStride purpose

CairoImageSurface::createFromPng
CairoImageSurface::getFormat
CairoImageSurface


Get the image format

CairoImageSurface::getData
CairoImageSurface::getHeight
CairoImageSurface
PHP Manual

CairoImageSurface::getFormat

(PECL cairo >= 0.1.0)

CairoImageSurface::getFormat — Get the image format

Description

public int CairoImageSurface::getFormat ( void )

Retrieves the image format, as one of the CairoFormat defined

Parameters

This function has no parameters.

Return Values

One of the CairoFormat enums

Examples

Example #1 CairoImageSurface::getFormat example

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

var_dump($surface->getFormat()); // 0

$surface2 = new CairoImageSurface(CairoFormat::A8, 50, 50);

var_dump($surface2->getFormat()); // 2

?>

The above example will output something similar to:

int(0)
int(2)

See Also

  • CairoImageSurface::getHeight - Retrieves the height of the CairoImageSurface
  • CairoImageSurface::getWidth - Retrieves the width of the CairoImageSurface

CairoImageSurface::getData
CairoImageSurface::getHeight
CairoImageSurface


Retrieves the height of the CairoImageSurface

CairoImageSurface::getFormat
CairoImageSurface::getStride
CairoImageSurface
PHP Manual

CairoImageSurface::getHeight

(PECL cairo >= 0.1.0)

CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface

Description

public int CairoImageSurface::getHeight ( void )

This methods returns the CairoImageSurface height.

Parameters

This function has no parameters.

Return Values

CairoImageSurface object height

Examples

Example #1 CairoImageSurface::getHeight example

<?php
// creates a new image surface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 80, 50);

//gets the width
var_dump($surface->getHeight());

?>

The above example will output something similar to:

int(50)

See Also

  • CairoImageSurface::getWidth - Retrieves the width of the CairoImageSurface

CairoImageSurface::getFormat
CairoImageSurface::getStride
CairoImageSurface


The getStride purpose

CairoImageSurface::getHeight
CairoImageSurface::getWidth
CairoImageSurface
PHP Manual

CairoImageSurface::getStride

(PECL cairo >= 0.1.0)

CairoImageSurface::getStride — The getStride purpose

Description

public int CairoImageSurface::getStride ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoImageSurface::getStride example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoImageSurface::getHeight
CairoImageSurface::getWidth
CairoImageSurface


Retrieves the width of the CairoImageSurface

CairoImageSurface::getStride
CairoPdfSurface
CairoImageSurface
PHP Manual

CairoImageSurface::getWidth

(PECL cairo >= 0.1.0)

CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface

Description

public int CairoImageSurface::getWidth ( void )

Gets the width of the CairoImageSurface

Parameters

This function has no parameters.

Return Values

Returns the width of the CairoImageSurface object

Examples

Example #1 CairoImageSurface::getWidth example

<?php
// creates a new image surface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 80, 50);

//gets the width
var_dump($surface->getWidth());

?>

The above example will output something similar to:

int(80)

See Also

  • CairoImageSurface::getHeight - Retrieves the height of the CairoImageSurface

CairoImageSurface::getStride
CairoPdfSurface
CairoImageSurface


The __construct purpose

CairoLinearGradient
CairoLinearGradient::getPoints
CairoLinearGradient
PHP Manual

CairoLinearGradient::__construct

(PECL cairo >= 0.1.0)

CairoLinearGradient::__construct — The __construct purpose

Description

CairoLinearGradient::__construct ( float $x0 , float $y0 , float $x1 , float $y1 )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x0

Description...

y0

Description...

x1

Description...

y1

Description...

Return Values

Description...

Examples

Example #1 CairoLinearGradient::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoLinearGradient
CairoLinearGradient::getPoints
CairoLinearGradient


The getPoints purpose

CairoLinearGradient::__construct
CairoRadialGradient
CairoLinearGradient
PHP Manual

CairoLinearGradient::getPoints

(PECL cairo >= 0.1.0)

CairoLinearGradient::getPoints — The getPoints purpose

Description

public array CairoLinearGradient::getPoints ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoLinearGradient::getPoints example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoLinearGradient::__construct
CairoRadialGradient
CairoLinearGradient


Creates a new CairoMatrix object

CairoMatrix
CairoMatrix::initIdentity
CairoMatrix
PHP Manual

CairoMatrix::__construct

cairo_matrix_init

(PECL cairo >= 0.1.0)

CairoMatrix::__construct -- cairo_matrix_init — Creates a new CairoMatrix object

Description

Object oriented style (method):

CairoMatrix::__construct ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )

Procedural style:

object cairo_matrix_init ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )

Returns new CairoMatrix object. Matrices are used throughout cairo to convert between different coordinate spaces. Sets matrix to be the affine transformation given by xx, yx, xy, yy, x0, y0. The transformation is given by: x_new = xx * x + xy * y + x0; and y_new = yx * x + yy * y + y0;

Parameters

xx

xx component of the affine transformation

yx

yx component of the affine transformation

xy

xy component of the affine transformation

yy

yy component of the affine transformation

x0

X translation component of the affine transformation

y0

Y translation component of the affine transformation

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = new CairoMatrix(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
?>

See Also

  • CairoMatrix::initIdentity - Creates a new identity matrix
  • CairoMatrix::initRotate - Creates a new rotated matrix
  • CairoMatrix::initScale - Creates a new scaling matrix
  • CairoMatrix::initTranslate - Creates a new translation matrix

CairoMatrix
CairoMatrix::initIdentity
CairoMatrix


Creates a new identity matrix

CairoMatrix::__construct
CairoMatrix::initRotate
CairoMatrix
PHP Manual

CairoMatrix::initIdentity

cairo_matrix_init_identity

(PECL cairo >= 0.1.0)

CairoMatrix::initIdentity -- cairo_matrix_init_identity — Creates a new identity matrix

Description

Object oriented style (method):

public static void CairoMatrix::initIdentity ( void )

Procedural style:

object cairo_matrix_init_identity ( void )

Creates a new matrix that is an identity transformation. An identity transformation means the source data is copied into the destination data without change

Parameters

This function has no parameters.

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initIdentity();
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_identity();
?>

See Also

  • CairoMatrix::__construct - Creates a new CairoMatrix object
  • CairoMatrix::initRotate - Creates a new rotated matrix
  • CairoMatrix::initScale - Creates a new scaling matrix
  • CairoMatrix::initTranslate - Creates a new translation matrix

CairoMatrix::__construct
CairoMatrix::initRotate
CairoMatrix


Creates a new rotated matrix

CairoMatrix::initIdentity
CairoMatrix::initScale
CairoMatrix
PHP Manual

CairoMatrix::initRotate

cairo_matrix_init_rotate

(PECL cairo >= 0.1.0)

CairoMatrix::initRotate -- cairo_matrix_init_rotate — Creates a new rotated matrix

Description

Object oriented style (method):

public static void CairoMatrix::initRotate ( float $radians )

Procedural style:

object cairo_matrix_init_rotate ( float $radians )

Creats a new matrix to a transformation that rotates by radians provided

Parameters

radians

angle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the positive X axis toward the positive Y axis. With the default axis orientation of cairo, positive angles rotate in a clockwise direction.

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initRotate(0.3);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_rotate(0.3);
?>

See Also

  • CairoMatrix::__construct - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity - Creates a new identity matrix
  • CairoMatrix::initScale - Creates a new scaling matrix
  • CairoMatrix::initTranslate - Creates a new translation matrix

CairoMatrix::initIdentity
CairoMatrix::initScale
CairoMatrix


Creates a new scaling matrix

CairoMatrix::initRotate
CairoMatrix::initTranslate
CairoMatrix
PHP Manual

CairoMatrix::initScale

cairo_matrix_init_scale

cairo_matrix_create_scale

(PECL cairo >= 0.1.0)

CairoMatrix::initScale -- cairo_matrix_init_scale -- cairo_matrix_create_scale — Creates a new scaling matrix

Description

Object oriented style (method):

public static void CairoMatrix::initScale ( float $sx , float $sy )

Procedural style:

object cairo_matrix_init_scale ( float $sx , float $sy )

Creates a new matrix to a transformation that scales by sx and sy in the X and Y dimensions, respectively.

Parameters

sx

scale factor in the X direction

sy

scale factor in the Y direction

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initScale(1.0, 2.0);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_scale(1.0, 2.0);
?>

See Also

  • CairoMatrix::__construct - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity - Creates a new identity matrix
  • CairoMatrix::initRotate - Creates a new rotated matrix
  • CairoMatrix::initTranslate - Creates a new translation matrix

CairoMatrix::initRotate
CairoMatrix::initTranslate
CairoMatrix


Creates a new translation matrix

CairoMatrix::initScale
CairoMatrix::invert
CairoMatrix
PHP Manual

CairoMatrix::initTranslate

cairo_matrix_init_translate

(PECL cairo >= 0.1.0)

CairoMatrix::initTranslate -- cairo_matrix_init_translate — Creates a new translation matrix

Description

Object oriented style (method):

public static void CairoMatrix::initTranslate ( float $tx , float $ty )

Procedural style:

object cairo_matrix_init_translate ( float $tx , float $ty )

Creates a new matrix to a transformation that translates by tx and ty in the X and Y dimensions, respectively.

Parameters

tx

amount to translate in the X direction

ty

amount to translate in the Y direction

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initTranslate(1.0, 2.0);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_translate(1.0, 2.0);
?>

See Also

  • CairoMatrix::__construct - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity - Creates a new identity matrix
  • CairoMatrix::initRotate - Creates a new rotated matrix
  • CairoMatrix::initScale - Creates a new scaling matrix

CairoMatrix::initScale
CairoMatrix::invert
CairoMatrix


The invert purpose

CairoMatrix::initTranslate
CairoMatrix::multiply
CairoMatrix
PHP Manual

CairoMatrix::invert

(PECL cairo >= 0.1.0)

CairoMatrix::invert — The invert purpose

Description

public void CairoMatrix::invert ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoMatrix::invert example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoMatrix::initTranslate
CairoMatrix::multiply
CairoMatrix


The multiply purpose

CairoMatrix::invert
CairoMatrix::rotate
CairoMatrix
PHP Manual

CairoMatrix::multiply

(PECL cairo >= 0.1.0)

CairoMatrix::multiply — The multiply purpose

Description

public static CairoMatrix CairoMatrix::multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix1

Description...

matrix2

Description...

Return Values

Description...

Examples

Example #1 CairoMatrix::multiply example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoMatrix::invert
CairoMatrix::rotate
CairoMatrix


The rotate purpose

CairoMatrix::multiply
CairoMatrix::scale
CairoMatrix
PHP Manual

CairoMatrix::rotate

cairo_rotate

(PECL cairo >= 0.1.0)

CairoMatrix::rotate -- cairo_rotate — The rotate purpose

Description

Object oriented style (method):

public void CairoMatrix::rotate ( string $sx , string $sy )

Procedural style:

void cairo_rotate ( CairoContext $context , string $angle )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

angle

Description...

sx

Description...

sy

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoMatrix::multiply
CairoMatrix::scale
CairoMatrix


Applies scaling to a matrix

CairoMatrix::rotate
CairoMatrix::transformDistance
CairoMatrix
PHP Manual

CairoMatrix::scale

cairo_matrix_scale

(PECL cairo >= 0.1.0)

CairoMatrix::scale -- cairo_matrix_scale — Applies scaling to a matrix

Description

Object oriented style (method):

public void CairoMatrix::scale ( float $sx , float $sy )

Procedural style:

void cairo_matrix_scale ( CairoContext $context , float $sx , float $sy )

Applies scaling by sx, sy to the transformation in the matrix. The effect of the new transformation is to first scale the coordinates by sx and sy, then apply the original transformation to the coordinates.

Parameters

matrix

Procedural only - CairoMatrix instance

sx

scale factor in the X direction

sy

scale factor in the Y direction

Examples

Example #1 Object oriented style

<?php
/* Apply scaling to a matrix */
$matrix = new CairoMatrix(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
$matrix->scale(0.2, 2.0);
?>

Example #2 Procedural style

<?php
/* Apply scaling to a matrix */
$matrix = cairo_matrix_init(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
cairo_matrix_scale($matrix, 0.2, 2.0);
?>

See Also

  • CairoMatrix::initScale - Creates a new scaling matrix

CairoMatrix::rotate
CairoMatrix::transformDistance
CairoMatrix


The transformDistance purpose

CairoMatrix::scale
CairoMatrix::transformPoint
CairoMatrix
PHP Manual

CairoMatrix::transformDistance

(PECL cairo >= 0.1.0)

CairoMatrix::transformDistance — The transformDistance purpose

Description

public array CairoMatrix::transformDistance ( string $dx , string $dy )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

dx

Description...

dy

Description...

Return Values

Description...

Examples

Example #1 CairoMatrix::transformDistance example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoMatrix::scale
CairoMatrix::transformPoint
CairoMatrix


The transformPoint purpose

CairoMatrix::transformDistance
CairoMatrix::translate
CairoMatrix
PHP Manual

CairoMatrix::transformPoint

(PECL cairo >= 0.1.0)

CairoMatrix::transformPoint — The transformPoint purpose

Description

public array CairoMatrix::transformPoint ( string $dx , string $dy )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

dx

Description...

dy

Description...

Return Values

Description...

Examples

Example #1 CairoMatrix::transformPoint example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoMatrix::transformDistance
CairoMatrix::translate
CairoMatrix


The translate purpose

CairoMatrix::transformPoint
CairoOperator
CairoMatrix
PHP Manual

CairoMatrix::translate

cairo_translate

(PECL cairo >= 0.1.0)

CairoMatrix::translate -- cairo_translate — The translate purpose

Description

Object oriented style (method):

public void CairoMatrix::translate ( string $tx , string $ty )

Procedural style:

void cairo_translate ( CairoContext $context , string $x , string $y )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

tx

Description...

ty

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoMatrix::transformPoint
CairoOperator
CairoMatrix


The __construct purpose

CairoPattern
CairoPattern::getMatrix
CairoPattern
PHP Manual

CairoPattern::__construct

(PECL cairo >= 0.1.0)

CairoPattern::__construct — The __construct purpose

Description

CairoPattern::__construct ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPattern::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPattern
CairoPattern::getMatrix
CairoPattern


The getMatrix purpose

CairoPattern::__construct
CairoPattern::getType
CairoPattern
PHP Manual

CairoPattern::getMatrix

cairo_get_matrix

(PECL cairo >= 0.1.0)

CairoPattern::getMatrix -- cairo_get_matrix — The getMatrix purpose

Description

Object oriented style (method):

public void CairoPattern::getMatrix ( void )

Procedural style:

void cairo_get_matrix ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPattern::__construct
CairoPattern::getType
CairoPattern


The getType purpose

CairoPattern::getMatrix
CairoPattern::setMatrix
CairoPattern
PHP Manual

CairoPattern::getType

(PECL cairo >= 0.1.0)

CairoPattern::getType — The getType purpose

Description

public int CairoPattern::getType ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPattern::getType example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPattern::getMatrix
CairoPattern::setMatrix
CairoPattern


The setMatrix purpose

CairoPattern::getType
CairoPattern::status
CairoPattern
PHP Manual

CairoPattern::setMatrix

cairo_set_matrix

(PECL cairo >= 0.1.0)

CairoPattern::setMatrix -- cairo_set_matrix — The setMatrix purpose

Description

Object oriented style (method):

public void CairoPattern::setMatrix ( string $matrix )

Procedural style:

void cairo_set_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPattern::getType
CairoPattern::status
CairoPattern


The status purpose

CairoPattern::setMatrix
CairoGradientPattern
CairoPattern
PHP Manual

CairoPattern::status

cairo_status

(PECL cairo >= 0.1.0)

CairoPattern::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public int CairoPattern::status ( void )

Procedural style:

int cairo_status ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPattern::setMatrix
CairoGradientPattern
CairoPattern


The __construct purpose

CairoPdfSurface
CairoPdfSurface::setSize
CairoPdfSurface
PHP Manual

CairoPdfSurface::__construct

(PECL cairo >= 0.1.0)

CairoPdfSurface::__construct — The __construct purpose

Description

CairoPdfSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPdfSurface::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPdfSurface
CairoPdfSurface::setSize
CairoPdfSurface


The setSize purpose

CairoPdfSurface::__construct
CairoPsSurface
CairoPdfSurface
PHP Manual

CairoPdfSurface::setSize

(PECL cairo >= 0.1.0)

CairoPdfSurface::setSize — The setSize purpose

Description

public void CairoPdfSurface::setSize ( string $width , string $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPdfSurface::setSize example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPdfSurface::__construct
CairoPsSurface
CairoPdfSurface


The __construct purpose

CairoPsSurface
CairoPsSurface::dscBeginPageSetup
CairoPsSurface
PHP Manual

CairoPsSurface::__construct

(PECL cairo >= 0.1.0)

CairoPsSurface::__construct — The __construct purpose

Description

CairoPsSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPsSurface
CairoPsSurface::dscBeginPageSetup
CairoPsSurface


The dscBeginPageSetup purpose

CairoPsSurface::__construct
CairoPsSurface::dscBeginSetup
CairoPsSurface
PHP Manual

CairoPsSurface::dscBeginPageSetup

(PECL cairo >= 0.1.0)

CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose

Description

public void CairoPsSurface::dscBeginPageSetup ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::dscBeginPageSetup example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPsSurface::__construct
CairoPsSurface::dscBeginSetup
CairoPsSurface


The dscBeginSetup purpose

CairoPsSurface::dscBeginPageSetup
CairoPsSurface::dscComment
CairoPsSurface
PHP Manual

CairoPsSurface::dscBeginSetup

(PECL cairo >= 0.1.0)

CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose

Description

public void CairoPsSurface::dscBeginSetup ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::dscBeginSetup example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPsSurface::dscBeginPageSetup
CairoPsSurface::dscComment
CairoPsSurface


The dscComment purpose

CairoPsSurface::dscBeginSetup
CairoPsSurface::getEps
CairoPsSurface
PHP Manual

CairoPsSurface::dscComment

(PECL cairo >= 0.1.0)

CairoPsSurface::dscComment — The dscComment purpose

Description

public void CairoPsSurface::dscComment ( string $comment )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

comment

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::dscComment example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPsSurface::dscBeginSetup
CairoPsSurface::getEps
CairoPsSurface


The getEps purpose

CairoPsSurface::dscComment
CairoPsSurface::getLevels
CairoPsSurface
PHP Manual

CairoPsSurface::getEps

(PECL cairo >= 0.1.0)

CairoPsSurface::getEps — The getEps purpose

Description

public bool CairoPsSurface::getEps ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::getEps example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPsSurface::dscComment
CairoPsSurface::getLevels
CairoPsSurface


The getLevels purpose

CairoPsSurface::getEps
CairoPsSurface::levelToString
CairoPsSurface
PHP Manual

CairoPsSurface::getLevels

(PECL cairo >= 0.1.0)

CairoPsSurface::getLevels — The getLevels purpose

Description

public static array CairoPsSurface::getLevels ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::getLevels example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPsSurface::getEps
CairoPsSurface::levelToString
CairoPsSurface


The levelToString purpose

CairoPsSurface::getLevels
CairoPsSurface::restrictToLevel
CairoPsSurface
PHP Manual

CairoPsSurface::levelToString

(PECL cairo >= 0.1.0)

CairoPsSurface::levelToString — The levelToString purpose

Description

public static string CairoPsSurface::levelToString ( string $level )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::levelToString example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPsSurface::getLevels
CairoPsSurface::restrictToLevel
CairoPsSurface


The restrictToLevel purpose

CairoPsSurface::levelToString
CairoPsSurface::setEps
CairoPsSurface
PHP Manual

CairoPsSurface::restrictToLevel

(PECL cairo >= 0.1.0)

CairoPsSurface::restrictToLevel — The restrictToLevel purpose

Description

public void CairoPsSurface::restrictToLevel ( string $level )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::restrictToLevel example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPsSurface::levelToString
CairoPsSurface::setEps
CairoPsSurface


The setEps purpose

CairoPsSurface::restrictToLevel
CairoPsSurface::setSize
CairoPsSurface
PHP Manual

CairoPsSurface::setEps

(PECL cairo >= 0.1.0)

CairoPsSurface::setEps — The setEps purpose

Description

public void CairoPsSurface::setEps ( string $level )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::setEps example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPsSurface::restrictToLevel
CairoPsSurface::setSize
CairoPsSurface


The setSize purpose

CairoPsSurface::setEps
CairoSurfaceType
CairoPsSurface
PHP Manual

CairoPsSurface::setSize

(PECL cairo >= 0.1.0)

CairoPsSurface::setSize — The setSize purpose

Description

public void CairoPsSurface::setSize ( string $width , string $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::setSize example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoPsSurface::setEps
CairoSurfaceType
CairoPsSurface


The __construct purpose

CairoRadialGradient
CairoRadialGradient::getCircles
CairoRadialGradient
PHP Manual

CairoRadialGradient::__construct

(PECL cairo >= 0.1.0)

CairoRadialGradient::__construct — The __construct purpose

Description

CairoRadialGradient::__construct ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x0

Description...

y0

Description...

r0

Description...

x1

Description...

y1

Description...

r1

Description...

Return Values

Description...

Examples

Example #1 CairoRadialGradient::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoRadialGradient
CairoRadialGradient::getCircles
CairoRadialGradient


The getCircles purpose

CairoRadialGradient::__construct
CairoAntialias
CairoRadialGradient
PHP Manual

CairoRadialGradient::getCircles

(PECL cairo >= 0.1.0)

CairoRadialGradient::getCircles — The getCircles purpose

Description

public array CairoRadialGradient::getCircles ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoRadialGradient::getCircles example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoRadialGradient::__construct
CairoAntialias
CairoRadialGradient


The __construct purpose

CairoScaledFont
CairoScaledFont::extents
CairoScaledFont
PHP Manual

CairoScaledFont::__construct

(PECL cairo >= 0.1.0)

CairoScaledFont::__construct — The __construct purpose

Description

CairoScaledFont::__construct ( CairoFontFace $font_face , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $options )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

font_face

Description...

matrix

Description...

ctm

Description...

options

Description...

Return Values

Description...

Examples

Example #1 CairoScaledFont::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont
CairoScaledFont::extents
CairoScaledFont


The extents purpose

CairoScaledFont::__construct
CairoScaledFont::getCtm
CairoScaledFont
PHP Manual

CairoScaledFont::extents

(PECL cairo >= 0.1.0)

CairoScaledFont::extents — The extents purpose

Description

public array CairoScaledFont::extents ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::extents example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont::__construct
CairoScaledFont::getCtm
CairoScaledFont


The getCtm purpose

CairoScaledFont::extents
CairoScaledFont::getFontFace
CairoScaledFont
PHP Manual

CairoScaledFont::getCtm

(PECL cairo >= 0.1.0)

CairoScaledFont::getCtm — The getCtm purpose

Description

public CairoMatrix CairoScaledFont::getCtm ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::getCtm example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont::extents
CairoScaledFont::getFontFace
CairoScaledFont


The getFontFace purpose

CairoScaledFont::getCtm
CairoScaledFont::getFontMatrix
CairoScaledFont
PHP Manual

CairoScaledFont::getFontFace

cairo_get_font_face

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontFace -- cairo_get_font_face — The getFontFace purpose

Description

Object oriented style (method):

public void CairoScaledFont::getFontFace ( void )

Procedural style:

void cairo_get_font_face ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont::getCtm
CairoScaledFont::getFontMatrix
CairoScaledFont


The getFontMatrix purpose

CairoScaledFont::getFontFace
CairoScaledFont::getFontOptions
CairoScaledFont
PHP Manual

CairoScaledFont::getFontMatrix

cairo_get_font_matrix

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontMatrix -- cairo_get_font_matrix — The getFontMatrix purpose

Description

Object oriented style (method):

public void CairoScaledFont::getFontMatrix ( void )

Procedural style:

void cairo_get_font_matrix ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont::getFontFace
CairoScaledFont::getFontOptions
CairoScaledFont


The getFontOptions purpose

CairoScaledFont::getFontMatrix
CairoScaledFont::getScaleMatrix
CairoScaledFont
PHP Manual

CairoScaledFont::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Description

Object oriented style (method):

public void CairoScaledFont::getFontOptions ( void )

Procedural style:

void cairo_get_font_options ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont::getFontMatrix
CairoScaledFont::getScaleMatrix
CairoScaledFont


The getScaleMatrix purpose

CairoScaledFont::getFontOptions
CairoScaledFont::getType
CairoScaledFont
PHP Manual

CairoScaledFont::getScaleMatrix

(PECL cairo >= 0.1.0)

CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose

Description

public void CairoScaledFont::getScaleMatrix ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::getScaleMatrix example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont::getFontOptions
CairoScaledFont::getType
CairoScaledFont


The getType purpose

CairoScaledFont::getScaleMatrix
CairoScaledFont::glyphExtents
CairoScaledFont
PHP Manual

CairoScaledFont::getType

(PECL cairo >= 0.1.0)

CairoScaledFont::getType — The getType purpose

Description

public int CairoScaledFont::getType ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::getType example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont::getScaleMatrix
CairoScaledFont::glyphExtents
CairoScaledFont


The glyphExtents purpose

CairoScaledFont::getType
CairoScaledFont::status
CairoScaledFont
PHP Manual

CairoScaledFont::glyphExtents

(PECL cairo >= 0.1.0)

CairoScaledFont::glyphExtents — The glyphExtents purpose

Description

public array CairoScaledFont::glyphExtents ( string $glyphs )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

glyphs

Description...

Return Values

Description...

Examples

Example #1 CairoScaledFont::glyphExtents example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont::getType
CairoScaledFont::status
CairoScaledFont


The status purpose

CairoScaledFont::glyphExtents
CairoScaledFont::textExtents
CairoScaledFont
PHP Manual

CairoScaledFont::status

cairo_status

(PECL cairo >= 0.1.0)

CairoScaledFont::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public int CairoScaledFont::status ( void )

Procedural style:

int cairo_status ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont::glyphExtents
CairoScaledFont::textExtents
CairoScaledFont


The textExtents purpose

CairoScaledFont::status
CairoToyFontFace
CairoScaledFont
PHP Manual

CairoScaledFont::textExtents

cairo_text_extents

(PECL cairo >= 0.1.0)

CairoScaledFont::textExtents -- cairo_text_extents — The textExtents purpose

Description

Object oriented style (method):

public array CairoScaledFont::textExtents ( string $text )

Procedural style:

array cairo_text_extents ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

text

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoScaledFont::status
CairoToyFontFace
CairoScaledFont


The __construct purpose

CairoSolidPattern
CairoSolidPattern::getRgba
CairoSolidPattern
PHP Manual

CairoSolidPattern::__construct

(PECL cairo >= 0.1.0)

CairoSolidPattern::__construct — The __construct purpose

Description

CairoSolidPattern::__construct ( float $red , float $green , float $blue [, float $alpha = 0 ] )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 CairoSolidPattern::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSolidPattern
CairoSolidPattern::getRgba
CairoSolidPattern


The getRgba purpose

CairoSolidPattern::__construct
CairoSurfacePattern
CairoSolidPattern
PHP Manual

CairoSolidPattern::getRgba

(PECL cairo >= 0.1.0)

CairoSolidPattern::getRgba — The getRgba purpose

Description

public array CairoSolidPattern::getRgba ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSolidPattern::getRgba example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSolidPattern::__construct
CairoSurfacePattern
CairoSolidPattern


The __construct purpose

CairoSurface
CairoSurface::copyPage
CairoSurface
PHP Manual

CairoSurface::__construct

(PECL cairo >= 0.1.0)

CairoSurface::__construct — The __construct purpose

Description

CairoSurface::__construct ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface
CairoSurface::copyPage
CairoSurface


The copyPage purpose

CairoSurface::__construct
CairoSurface::createSimilar
CairoSurface
PHP Manual

CairoSurface::copyPage

cairo_copy_page

(PECL cairo >= 0.1.0)

CairoSurface::copyPage -- cairo_copy_page — The copyPage purpose

Description

Object oriented style (method):

public void CairoSurface::copyPage ( void )

Procedural style:

void cairo_copy_page ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::__construct
CairoSurface::createSimilar
CairoSurface


The createSimilar purpose

CairoSurface::copyPage
CairoSurface::finish
CairoSurface
PHP Manual

CairoSurface::createSimilar

(PECL cairo >= 0.1.0)

CairoSurface::createSimilar — The createSimilar purpose

Description

public void CairoSurface::createSimilar ( string $content , string $width , string $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

content

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::createSimilar example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::copyPage
CairoSurface::finish
CairoSurface


The finish purpose

CairoSurface::createSimilar
CairoSurface::flush
CairoSurface
PHP Manual

CairoSurface::finish

(PECL cairo >= 0.1.0)

CairoSurface::finish — The finish purpose

Description

public void CairoSurface::finish ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::finish example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::createSimilar
CairoSurface::flush
CairoSurface


The flush purpose

CairoSurface::finish
CairoSurface::getContent
CairoSurface
PHP Manual

CairoSurface::flush

(PECL cairo >= 0.1.0)

CairoSurface::flush — The flush purpose

Description

public void CairoSurface::flush ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::flush example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::finish
CairoSurface::getContent
CairoSurface


The getContent purpose

CairoSurface::flush
CairoSurface::getDeviceOffset
CairoSurface
PHP Manual

CairoSurface::getContent

(PECL cairo >= 0.1.0)

CairoSurface::getContent — The getContent purpose

Description

public int CairoSurface::getContent ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::getContent example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::flush
CairoSurface::getDeviceOffset
CairoSurface


The getDeviceOffset purpose

CairoSurface::getContent
CairoSurface::getFontOptions
CairoSurface
PHP Manual

CairoSurface::getDeviceOffset

(PECL cairo >= 0.1.0)

CairoSurface::getDeviceOffset — The getDeviceOffset purpose

Description

public array CairoSurface::getDeviceOffset ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::getDeviceOffset example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::getContent
CairoSurface::getFontOptions
CairoSurface


The getFontOptions purpose

CairoSurface::getDeviceOffset
CairoSurface::getType
CairoSurface
PHP Manual

CairoSurface::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoSurface::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Description

Object oriented style (method):

public void CairoSurface::getFontOptions ( void )

Procedural style:

void cairo_get_font_options ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::getDeviceOffset
CairoSurface::getType
CairoSurface


The getType purpose

CairoSurface::getFontOptions
CairoSurface::markDirty
CairoSurface
PHP Manual

CairoSurface::getType

(PECL cairo >= 0.1.0)

CairoSurface::getType — The getType purpose

Description

public int CairoSurface::getType ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::getType example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::getFontOptions
CairoSurface::markDirty
CairoSurface


The markDirty purpose

CairoSurface::getType
CairoSurface::markDirtyRectangle
CairoSurface
PHP Manual

CairoSurface::markDirty

(PECL cairo >= 0.1.0)

CairoSurface::markDirty — The markDirty purpose

Description

public void CairoSurface::markDirty ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::markDirty example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::getType
CairoSurface::markDirtyRectangle
CairoSurface


The markDirtyRectangle purpose

CairoSurface::markDirty
CairoSurface::setDeviceOffset
CairoSurface
PHP Manual

CairoSurface::markDirtyRectangle

(PECL cairo >= 0.1.0)

CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose

Description

public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x

Description...

y

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::markDirtyRectangle example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::markDirty
CairoSurface::setDeviceOffset
CairoSurface


The setDeviceOffset purpose

CairoSurface::markDirtyRectangle
CairoSurface::setFallbackResolution
CairoSurface
PHP Manual

CairoSurface::setDeviceOffset

(PECL cairo >= 0.1.0)

CairoSurface::setDeviceOffset — The setDeviceOffset purpose

Description

public void CairoSurface::setDeviceOffset ( string $x , string $y )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::setDeviceOffset example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::markDirtyRectangle
CairoSurface::setFallbackResolution
CairoSurface


The setFallbackResolution purpose

CairoSurface::setDeviceOffset
CairoSurface::showPage
CairoSurface
PHP Manual

CairoSurface::setFallbackResolution

(PECL cairo >= 0.1.0)

CairoSurface::setFallbackResolution — The setFallbackResolution purpose

Description

public void CairoSurface::setFallbackResolution ( string $x , string $y )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::setFallbackResolution example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::setDeviceOffset
CairoSurface::showPage
CairoSurface


The showPage purpose

CairoSurface::setFallbackResolution
CairoSurface::status
CairoSurface
PHP Manual

CairoSurface::showPage

cairo_show_page

(PECL cairo >= 0.1.0)

CairoSurface::showPage -- cairo_show_page — The showPage purpose

Description

Object oriented style (method):

public void CairoSurface::showPage ( void )

Procedural style:

void cairo_show_page ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::setFallbackResolution
CairoSurface::status
CairoSurface


The status purpose

CairoSurface::showPage
CairoSurface::writeToPng
CairoSurface
PHP Manual

CairoSurface::status

cairo_status

(PECL cairo >= 0.1.0)

CairoSurface::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public int CairoSurface::status ( void )

Procedural style:

int cairo_status ( CairoContext $context )

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::showPage
CairoSurface::writeToPng
CairoSurface


The writeToPng purpose

CairoSurface::status
CairoSvgSurface
CairoSurface
PHP Manual

CairoSurface::writeToPng

(PECL cairo >= 0.1.0)

CairoSurface::writeToPng — The writeToPng purpose

Description

public void CairoSurface::writeToPng ( string $file )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::writeToPng example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurface::status
CairoSvgSurface
CairoSurface


The __construct purpose

CairoSurfacePattern
CairoSurfacePattern::getExtend
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::__construct

(PECL cairo >= 0.1.0)

CairoSurfacePattern::__construct — The __construct purpose

Description

CairoSurfacePattern::__construct ( CairoSurface $surface )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurfacePattern
CairoSurfacePattern::getExtend
CairoSurfacePattern


The getExtend purpose

CairoSurfacePattern::__construct
CairoSurfacePattern::getFilter
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::getExtend

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getExtend — The getExtend purpose

Description

public int CairoSurfacePattern::getExtend ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::getExtend example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurfacePattern::__construct
CairoSurfacePattern::getFilter
CairoSurfacePattern


The getFilter purpose

CairoSurfacePattern::getExtend
CairoSurfacePattern::getSurface
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::getFilter

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getFilter — The getFilter purpose

Description

public int CairoSurfacePattern::getFilter ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::getFilter example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurfacePattern::getExtend
CairoSurfacePattern::getSurface
CairoSurfacePattern


The getSurface purpose

CairoSurfacePattern::getFilter
CairoSurfacePattern::setExtend
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::getSurface

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getSurface — The getSurface purpose

Description

public void CairoSurfacePattern::getSurface ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::getSurface example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurfacePattern::getFilter
CairoSurfacePattern::setExtend
CairoSurfacePattern


The setExtend purpose

CairoSurfacePattern::getSurface
CairoSurfacePattern::setFilter
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::setExtend

(PECL cairo >= 0.1.0)

CairoSurfacePattern::setExtend — The setExtend purpose

Description

public void CairoSurfacePattern::setExtend ( int $extend )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

extend

Description...

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::setExtend example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurfacePattern::getSurface
CairoSurfacePattern::setFilter
CairoSurfacePattern


The setFilter purpose

CairoSurfacePattern::setExtend
CairoLinearGradient
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::setFilter

(PECL cairo >= 0.1.0)

CairoSurfacePattern::setFilter — The setFilter purpose

Description

public void CairoSurfacePattern::setFilter ( string $filter )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filter

Description...

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::setFilter example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSurfacePattern::setExtend
CairoLinearGradient
CairoSurfacePattern


The __construct purpose

CairoSvgSurface
CairoSvgSurface::getVersions
CairoSvgSurface
PHP Manual

CairoSvgSurface::__construct

(PECL cairo >= 0.1.0)

CairoSvgSurface::__construct — The __construct purpose

Description

CairoSvgSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoSvgSurface::__construct example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSvgSurface
CairoSvgSurface::getVersions
CairoSvgSurface


Used to retrieve a list of supported SVG versions

CairoSvgSurface::__construct
CairoSvgSurface::restrictToVersion
CairoSvgSurface
PHP Manual

CairoSvgSurface::getVersions

cairo_svg_surface_get_versions

(PECL cairo >= 0.1.0)

CairoSvgSurface::getVersions -- cairo_svg_surface_get_versions — Used to retrieve a list of supported SVG versions

Description

Object oriented style (method):

public static array CairoSvgSurface::getVersions ( void )

Procedural style:

array cairo_svg_get_versions ( void )

Returns a numerically indexed array of currently available CairoSvgVersion constants. In order to retreive the string values for each item, use CairoSvgSurface::versionToString.

Parameters

This function has no parameters.

Return Values

Returns a numerically indexed array of integer values.

Examples

Example #1 CairoSvgSurface::getVersions example

<?php
/* Grab our list of versions */
$versions = CairoSvgSurface::getVersions();
var_dump($versions);

/* echo the string name of each version */
foreach($versions as $id) {
    echo CairoSvgSurface::versionToString($id), PHP_EOL;
}
?>

The above example will output something similar to:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
SVG 1.1
SVG 1.2

Example #2 Procedural style

<?php
/* Grab our list of versions */
$versions = cairo_svg_surface_get_versions();
var_dump($versions);

/* echo the string name of each version */
foreach($versions as $id) {
    echo cairo_svg_surface_version_to_string($id), PHP_EOL;
}
?>

The above example will output something similar to:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
SVG 1.1
SVG 1.2

See Also

  • CairoSvgSurface::versionToString - The versionToString purpose

CairoSvgSurface::__construct
CairoSvgSurface::restrictToVersion
CairoSvgSurface


The restrictToVersion purpose

CairoSvgSurface::getVersions
CairoSvgSurface::versionToString
CairoSvgSurface
PHP Manual

CairoSvgSurface::restrictToVersion

(PECL cairo >= 0.1.0)

CairoSvgSurface::restrictToVersion — The restrictToVersion purpose

Description

public void CairoSvgSurface::restrictToVersion ( string $version )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

version

Description...

Return Values

Description...

Examples

Example #1 CairoSvgSurface::restrictToVersion example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSvgSurface::getVersions
CairoSvgSurface::versionToString
CairoSvgSurface


The versionToString purpose

CairoSvgSurface::restrictToVersion
CairoImageSurface
CairoSvgSurface
PHP Manual

CairoSvgSurface::versionToString

(PECL cairo >= 0.1.0)

CairoSvgSurface::versionToString — The versionToString purpose

Description

public static string CairoSvgSurface::versionToString ( int $version )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

version

Description...

Return Values

Description...

Examples

Example #1 CairoSvgSurface::versionToString example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

CairoSvgSurface::restrictToVersion
CairoImageSurface
CairoSvgSurface


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CAL_GREGORIAN (integer)
CAL_JULIAN (integer)
CAL_JEWISH (integer)
CAL_FRENCH (integer)
CAL_NUM_CALS (integer)
CAL_DOW_DAYNO (integer)
CAL_DOW_SHORT (integer)
CAL_DOW_LONG (integer)
CAL_MONTH_GREGORIAN_SHORT (integer)
CAL_MONTH_GREGORIAN_LONG (integer)
CAL_MONTH_JULIAN_SHORT (integer)
CAL_MONTH_JULIAN_LONG (integer)
CAL_MONTH_JEWISH (integer)
CAL_MONTH_FRENCH (integer)

The following constants are available since PHP 4.3.0 :

CAL_EASTER_DEFAULT (integer)
CAL_EASTER_ROMAN (integer)
CAL_EASTER_ALWAYS_GREGORIAN (integer)
CAL_EASTER_ALWAYS_JULIAN (integer)

The following constants are available since PHP 5.0.0 :

CAL_JEWISH_ADD_ALAFIM_GERESH (integer)
CAL_JEWISH_ADD_ALAFIM (integer)
CAL_JEWISH_ADD_GERESHAYIM (integer)
Resource Types
Calendar Functions
Calendar


Installation

To get these functions to work, you have to compile PHP with --enable-calendar.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Calendar


The ArrayAccess interface

Introduction

Interface to provide accessing objects as arrays.

Interface synopsis

ArrayAccess
ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )
}

Example #1 Basic usage

<?php
class obj implements arrayaccess {
    private $container = array();
    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }
    public function offsetSet($offset, $value) {
        $this->container[$offset] = $value;
    }
    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }
    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }
    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new obj;

var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);

?>

The above example will output something similar to:

bool(true)
int(2)
bool(false)
string(7) "A value"

Table of Contents

  • ArrayAccess::offsetExists — Whether a offset exists
  • ArrayAccess::offsetGet — Offset to retrieve
  • ArrayAccess::offsetSet — Offset to set
  • ArrayAccess::offsetUnset — Offset to unset
IteratorAggregate::getIterator
ArrayAccess::offsetExists
Predefined Interfaces


The KTaglib_MPEG_AudioProperties class

Introduction

Represents the audio properties of a MPEG file, like length, bitrate or samplerate.

Class synopsis

KTaglib_MPEG_Audioproperties
KTaglib_MPEG_AudioProperties {
}

Table of Contents

  • KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file
  • KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file
  • KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file
  • KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file
  • KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file
  • KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file
  • KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the length of a MPEG file
  • KTaglib_MPEG_AudioProperties::isOriginal — Returns the length of a MPEG file
  • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns the length of a MPEG file
KTaglib_MPEG_File::getID3v2Tag
KTaglib_MPEG_AudioProperties::getBitrate
KTaglib


The Cairo class

Introduction

Simple class with some static helper methods.

Class synopsis

Cairo
Cairo {
/* Methods */
public static array availableFonts ( void )
public static array availableSurfaces ( void )
public static string statusToString ( int $status )
public static int version ( void )
public static string versionString ( void )
}

Table of Contents

  • Cairo::availableFonts — Retrieves the availables font types
  • Cairo::availableSurfaces — Retrieves all available surfaces
  • Cairo::statusToString — Retrieves the current status as string
  • Cairo::version — Retrives cairo's library version
  • Cairo::versionString — Retrieves cairo version as string
cairo_svg_version_to_string
Cairo::availableFonts
Cairo


The CairoAntialias class

Introduction

Enum class that specifies the type of antialiasing to do when rendering text or shapes.

Class synopsis

CairoAntialias
CairoAntialias {
/* Constants */
const integer CairoAntialias::MODE_DEFAULT = 0 ;
const integer CairoAntialias::MODE_NONE = 1 ;
const integer CairoAntialias::MODE_GRAY = 2 ;
const integer CairoAntialias::MODE_SUBPIXEL = 3 ;
}

Predefined Constants

CairoAntialias Node Types

CairoAntialias::MODE_DEFAULT

Use the default antialiasing for the subsystem and target device

CairoAntialias::MODE_NONE

Use a bilevel alpha mask

CairoAntialias::MODE_GRAY

Perform single-color antialiasing (using shades of gray for black text on a white background, for example).

CairoAntialias::MODE_SUBPIXEL

Perform antialiasing by taking advantage of the order of subpixel elements on devices such as LCD panels.

CairoRadialGradient::getCircles
CairoContent
Cairo


The CairoContent class

Introduction

CairoContent is used to describe the content that a surface will contain, whether color information, alpha information (translucence vs. opacity), or both.

Note: The large values here are designed to keep CairoContent values distinct from CairoContent values so that the implementation can detect the error if users confuse the two types.

Class synopsis

CairoContent
CairoContent {
/* Constants */
const integer CairoContent::COLOR = 4096 ;
const integer CairoContent::ALPHA = 8192 ;
const integer CairoContent::COLOR_ALPHA = 12288 ;
}

Predefined Constants

CairoContent Node Types

CairoContent::COLOR

The surface will hold color content only.

CairoContent::ALPHA

The surface will hold alpha content only.

CairoContent::COLOR_ALPHA

The surface will hold color and alpha content.

CairoAntialias
CairoExtend
Cairo


The CairoContext class

Introduction

Context is the main object used when drawing with cairo. To draw with cairo, you create a CairoContext, set the target CairoSurface, and drawing options for the CairoContext, create shapes with functions . like CairoContext::moveTo and CairoContext::lineTo, and then draw shapes with CairoContext::stroke or CairoContext::fill. Contexts can be pushed to a stack via CairoContext::save. They may then safely be changed, without loosing the current state. Use CairoContext::restore to restore to the saved state.

Class synopsis

CairoContext
CairoContext {
/* Methods */
public void appendPath ( CairoPath $path )
public void arc ( float $x , float $y , float $radius , float $angle1 , float $angle2 )
public void arcNegative ( float $x , float $y , float $radius , float $angle1 , float $angle2 )
public void clip ( void )
public array clipExtents ( void )
public void clipPreserve ( void )
public array clipRectangleList ( void )
public void closePath ( void )
__construct ( CairoSurface $surface )
public void copyPage ( void )
public CairoPath copyPath ( void )
public CairoPath copyPathFlat ( void )
public void curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )
public array deviceToUser ( float $x , float $y )
public array deviceToUserDistance ( float $x , float $y )
public void fill ( void )
public array fillExtents ( void )
public void fillPreserve ( void )
public array fontExtents ( void )
public int getAntialias ( void )
public array getCurrentPoint ( void )
public array getDash ( void )
public int getDashCount ( void )
public int getFillRule ( void )
public void getFontFace ( void )
public void getFontMatrix ( void )
public void getFontOptions ( void )
public void getGroupTarget ( void )
public int getLineCap ( void )
public int getLineJoin ( void )
public float getLineWidth ( void )
public void getMatrix ( void )
public float getMiterLimit ( void )
public int getOperator ( void )
public void getScaledFont ( void )
public void getSource ( void )
public void getTarget ( void )
public float getTolerance ( void )
public void glyphPath ( array $glyphs )
public bool hasCurrentPoint ( void )
public void identityMatrix ( void )
public bool inFill ( string $x , string $y )
public bool inStroke ( string $x , string $y )
public void lineTo ( string $x , string $y )
public void mask ( string $pattern )
public void maskSurface ( string $surface [, string $x [, string $y ]] )
public void moveTo ( string $x , string $y )
public void newPath ( void )
public void newSubPath ( void )
public void paint ( void )
public void paintWithAlpha ( string $alpha )
public array pathExtents ( void )
public void popGroup ( void )
public void popGroupToSource ( void )
public void pushGroup ( void )
public void pushGroupWithContent ( string $content )
public void rectangle ( string $x , string $y , string $width , string $height )
public void relCurveTo ( string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )
public void relLineTo ( string $x , string $y )
public void relMoveTo ( string $x , string $y )
public void resetClip ( void )
public void restore ( void )
public void rotate ( string $angle )
public void save ( void )
public void scale ( string $x , string $y )
public void selectFontFace ( string $family [, string $slant [, string $weight ]] )
public void setAntialias ([ string $antialias ] )
public void setDash ( string $dashes [, string $offset ] )
public void setFillRule ( string $setting )
public void setFontFace ( string $fontface )
public void setFontMatrix ( string $matrix )
public void setFontOptions ( string $fontoptions )
public void setFontSize ( string $size )
public void setLineCap ( string $setting )
public void setLineJoin ( string $setting )
public void setLineWidth ( string $width )
public void setMatrix ( string $matrix )
public void setMiterLimit ( string $limit )
public void setOperator ( string $setting )
public void setScaledFont ( string $scaledfont )
public void setSource ( string $pattern )
public void setSourceRGB ( string $red , string $green , string $blue )
public void setSourceRGBA ( string $red , string $green , string $blue , string $alpha )
public void setSourceSurface ( string $surface [, string $x [, string $y ]] )
public void setTolerance ( string $tolerance )
public void showPage ( void )
public void showText ( string $text )
public int status ( void )
public void stroke ( void )
public array strokeExtents ( void )
public void strokePreserve ( void )
public array textExtents ( string $text )
public void textPath ( string $string )
public void transform ( string $matrix )
public void translate ( string $x , string $y )
public array userToDevice ( string $x , string $y )
public array userToDeviceDistance ( string $x , string $y )
}

Table of Contents

  • CairoContext::appendPath — Appends a path to current path
  • CairoContext::arc — Adds a circular arc
  • CairoContext::arcNegative — Adds a negative arc
  • CairoContext::clip — Establishes a new clip region
  • CairoContext::clipExtents — Computes the area inside the current clip
  • CairoContext::clipPreserve — Establishes a new clip region from the current clip
  • CairoContext::clipRectangleList — Retrieves the current clip as a list of rectangles
  • CairoContext::closePath — Closes the current path
  • CairoContext::__construct — Creates a new CairoContext
  • CairoContext::copyPage — Emits the current page
  • CairoContext::copyPath — Creates a copy of the current path
  • CairoContext::copyPathFlat — Gets a flattened copy of the current path
  • CairoContext::curveTo — Adds a curve
  • CairoContext::deviceToUser — Transform a coordinate
  • CairoContext::deviceToUserDistance — Transform a distance
  • CairoContext::fill — Fills the current path
  • CairoContext::fillExtents — Computes the filled area
  • CairoContext::fillPreserve — Fills and preserve the current path
  • CairoContext::fontExtents — Get the font extents
  • CairoContext::getAntialias — Retrives the current antialias mode
  • CairoContext::getCurrentPoint — The getCurrentPoint purpose
  • CairoContext::getDash — The getDash purpose
  • CairoContext::getDashCount — The getDashCount purpose
  • CairoContext::getFillRule — The getFillRule purpose
  • CairoContext::getFontFace — The getFontFace purpose
  • CairoContext::getFontMatrix — The getFontMatrix purpose
  • CairoContext::getFontOptions — The getFontOptions purpose
  • CairoContext::getGroupTarget — The getGroupTarget purpose
  • CairoContext::getLineCap — The getLineCap purpose
  • CairoContext::getLineJoin — The getLineJoin purpose
  • CairoContext::getLineWidth — The getLineWidth purpose
  • CairoContext::getMatrix — The getMatrix purpose
  • CairoContext::getMiterLimit — The getMiterLimit purpose
  • CairoContext::getOperator — The getOperator purpose
  • CairoContext::getScaledFont — The getScaledFont purpose
  • CairoContext::getSource — The getSource purpose
  • CairoContext::getTarget — The getTarget purpose
  • CairoContext::getTolerance — The getTolerance purpose
  • CairoContext::glyphPath — The glyphPath purpose
  • CairoContext::hasCurrentPoint — The hasCurrentPoint purpose
  • CairoContext::identityMatrix — The identityMatrix purpose
  • CairoContext::inFill — The inFill purpose
  • CairoContext::inStroke — The inStroke purpose
  • CairoContext::lineTo — The lineTo purpose
  • CairoContext::mask — The mask purpose
  • CairoContext::maskSurface — The maskSurface purpose
  • CairoContext::moveTo — The moveTo purpose
  • CairoContext::newPath — The newPath purpose
  • CairoContext::newSubPath — The newSubPath purpose
  • CairoContext::paint — The paint purpose
  • CairoContext::paintWithAlpha — The paintWithAlpha purpose
  • CairoContext::pathExtents — The pathExtents purpose
  • CairoContext::popGroup — The popGroup purpose
  • CairoContext::popGroupToSource — The popGroupToSource purpose
  • CairoContext::pushGroup — The pushGroup purpose
  • CairoContext::pushGroupWithContent — The pushGroupWithContent purpose
  • CairoContext::rectangle — The rectangle purpose
  • CairoContext::relCurveTo — The relCurveTo purpose
  • CairoContext::relLineTo — The relLineTo purpose
  • CairoContext::relMoveTo — The relMoveTo purpose
  • CairoContext::resetClip — The resetClip purpose
  • CairoContext::restore — The restore purpose
  • CairoContext::rotate — The rotate purpose
  • CairoContext::save — The save purpose
  • CairoContext::scale — The scale purpose
  • CairoContext::selectFontFace — The selectFontFace purpose
  • CairoContext::setAntialias — The setAntialias purpose
  • CairoContext::setDash — The setDash purpose
  • CairoContext::setFillRule — The setFillRule purpose
  • CairoContext::setFontFace — The setFontFace purpose
  • CairoContext::setFontMatrix — The setFontMatrix purpose
  • CairoContext::setFontOptions — The setFontOptions purpose
  • CairoContext::setFontSize — The setFontSize purpose
  • CairoContext::setLineCap — The setLineCap purpose
  • CairoContext::setLineJoin — The setLineJoin purpose
  • CairoContext::setLineWidth — The setLineWidth purpose
  • CairoContext::setMatrix — The setMatrix purpose
  • CairoContext::setMiterLimit — The setMiterLimit purpose
  • CairoContext::setOperator — The setOperator purpose
  • CairoContext::setScaledFont — The setScaledFont purpose
  • CairoContext::setSource — The setSource purpose
  • CairoContext::setSourceRGB — The setSourceRGB purpose
  • CairoContext::setSourceRGBA — The setSourceRGBA purpose
  • CairoContext::setSourceSurface — The setSourceSurface purpose
  • CairoContext::setTolerance — The setTolerance purpose
  • CairoContext::showPage — The showPage purpose
  • CairoContext::showText — The showText purpose
  • CairoContext::status — The status purpose
  • CairoContext::stroke — The stroke purpose
  • CairoContext::strokeExtents — The strokeExtents purpose
  • CairoContext::strokePreserve — The strokePreserve purpose
  • CairoContext::textExtents — The textExtents purpose
  • CairoContext::textPath — The textPath purpose
  • CairoContext::transform — The transform purpose
  • CairoContext::translate — The translate purpose
  • CairoContext::userToDevice — The userToDevice purpose
  • CairoContext::userToDeviceDistance — The userToDeviceDistance purpose
Cairo::versionString
CairoContext::appendPath
Cairo


The CairoException class

Introduction

Exception class throwed by Cairo functions and methods

Class synopsis

CairoException
CairoException extends Exception {
/* Properties */
/* Inherited methods */
}

Properties

message

Prop description

code

Prop description

file

Prop description

line

Prop description

CairoContext::userToDeviceDistance
CairoStatus
Cairo


The CairoExtend class

Introduction

Description of the class.

Class synopsis

CairoExtend
CairoExtend {
/* Constants */
const integer CairoExtend::NONE = 0 ;
const integer CairoExtend::REPEAT = 1 ;
const integer CairoExtend::REFLECT = 2 ;
const integer CairoExtend::PAD = 3 ;
}

Predefined Constants

CairoExtend Node Types

CairoExtend::NONE

Description here...

CairoExtend::REPEAT

Description here...

CairoExtend::REFLECT

Description here...

CairoExtend::PAD

Description here...

CairoContent
CairoFormat
Cairo


The CairoFillRule class

Introduction

A CairoFillRule is used to select how paths are filled. For both fill rules, whether or not a point is included in the fill is determined by taking a ray from that point to infinity and looking at intersections with the path. The ray can be in any direction, as long as it doesn't pass through the end point of a segment or have a tricky intersection such as intersecting tangent to the path. (Note that filling is not actually implemented in this way. This is just a description of the rule that is applied.)

The default fill rule is CairoFillRule::WINDING.

Class synopsis

CairoFillRule
CairoFillRule {
/* Constants */
const integer CairoFillRule::WINDING = 0 ;
const integer CairoFillRule::EVEN_ODD = 1 ;
}

Predefined Constants

CairoFillRule Node Types

CairoFillRule::WINDING

If the path crosses the ray from left-to-right, counts +1. If the path crosses the ray from right to left, counts -1. (Left and right are determined from the perspective of looking along the ray from the starting point.) If the total count is non-zero, the point will be filled.

CairoFillRule::EVEN_ODD

Counts the total number of intersections, without regard to the orientation of the contour. If the total number of intersections is odd, the point will be filled.

CairoFormat::strideForWidth
CairoFilter
Cairo


The CairoFilter class

Introduction

A CairoFilter is used to indicate what filtering should be applied when reading pixel values from patterns. See CairoPattern::setSource or cairo_pattern_set_source() for indicating the desired filter to be used with a particular pattern.

Class synopsis

CairoFilter
CairoFilter {
/* Constants */
const integer CairoFilter::FAST = 0 ;
const integer CairoFilter::GOOD = 1 ;
const integer CairoFilter::BEST = 2 ;
const integer CairoFilter::NEAREST = 3 ;
const integer CairoFilter::BILINEAR = 4 ;
const integer CairoFilter::GAUSSIAN = 5 ;
}

Predefined Constants

CairoFilter Node Types

CairoFilter::FAST

A high-performance filter, with quality similar to CairoFilter::NEAREST

CairoFilter::GOOD

A reasonable-performance filter, with quality similar to CairoFilter::BILINEAR

CairoFilter::BEST

The highest-quality available, performance may not be suitable for interactive use.

CairoFilter::NEAREST

Nearest-neighbor filtering

CairoFilter::BILINEAR

Linear interpolation in two dimensions

CairoFilter::GAUSSIAN

This filter value is currently unimplemented, and should not be used in current code.

CairoFillRule
CairoHintMetrics
Cairo


The CairoFontFace class

Introduction

CairoFontFace abstract class represents a particular font at a particular weight, slant, and other characteristic but no transformation or size.

Note: This class can not be instantiated directly, it is created by CairoContext::getFontFace or cairo_scaled_font_get_font_face().

Class synopsis

CairoFontFace
CairoFontFace {
/* Methods */
__construct ( void )
public int getType ( void )
public int status ( void )
}

Table of Contents

  • CairoFontFace::__construct — Creates a new CairoFontFace object
  • CairoFontFace::getType — Retrieves the font face type
  • CairoFontFace::status — Check for CairoFontFace errors
CairoSurfaceType
CairoFontFace::__construct
Cairo


The CairoFontOptions class

Introduction

An opaque structure holding all options that are used when rendering fonts.

Individual features of a cairo_font_options_t can be set or accessed using functions named cairo_font_options_set_feature_name and cairo_font_options_get_feature_name, like cairo_font_options_set_antialias() and cairo_font_options_get_antialias().

New features may be added to CairoFontOptions in the future. For this reason CairoFontOptions::copy, CairoFontOptions::equal, CairoFontOptions::merge, CairoFontOptions::hash (cairo_font_options_copy(), cairo_font_options_equal(), cairo_font_options_merge(), and cairo_font_options_hash() in procedural way) should be used to copy, check for equality, merge, or compute a hash value of CairoFontOptions objects.

Class synopsis

CairoFontOptions
CairoFontOptions {
/* Methods */
__construct ( void )
public bool equal ( string $other )
public int getAntialias ( void )
public int getHintMetrics ( void )
public int getHintStyle ( void )
public int getSubpixelOrder ( void )
public int hash ( void )
public void merge ( string $other )
public void setAntialias ( string $antialias )
public void setHintMetrics ( string $hint_metrics )
public void setHintStyle ( string $hint_style )
public void setSubpixelOrder ( string $subpixel_order )
public int status ( void )
}

Table of Contents

  • CairoFontOptions::__construct — The __construct purpose
  • CairoFontOptions::equal — The equal purpose
  • CairoFontOptions::getAntialias — The getAntialias purpose
  • CairoFontOptions::getHintMetrics — The getHintMetrics purpose
  • CairoFontOptions::getHintStyle — The getHintStyle purpose
  • CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose
  • CairoFontOptions::hash — The hash purpose
  • CairoFontOptions::merge — The merge purpose
  • CairoFontOptions::setAntialias — The setAntialias purpose
  • CairoFontOptions::setHintMetrics — The setHintMetrics purpose
  • CairoFontOptions::setHintStyle — The setHintStyle purpose
  • CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose
  • CairoFontOptions::status — The status purpose
CairoFontFace::status
CairoFontOptions::__construct
Cairo


The CairoFontSlant class

Introduction

Specifies variants of a font face based on their slant.

Class synopsis

CairoFontSlant
CairoFontSlant {
/* Constants */
const integer CairoFontSlant::NORMAL = 0 ;
const integer CairoFontSlant::ITALIC = 1 ;
const integer CairoFontSlant::OBLIQUE = 2 ;
}

Predefined Constants

CairoFontSlant Node Types

CairoFontSlant::NORMAL

Upright font style

CairoFontSlant::ITALIC

Italic font style

CairoFontSlant::OBLIQUE

Oblique font style

CairoFontOptions::status
CairoFontType
Cairo


The CairoFontType class

Introduction

CairoFontType class is an abstract final class that contains constants used to describe the type of a given CairoFontFace or CairoScaledFont. The font types are also known as "font backends" within cairo.

The type of a CairoFontFace is determined by the how it is created, an example would be the CairoToyFontFace::__construct. The CairoFontFace type can be queried with CairoFontFace::getType or cairo_font_face_get_type()

The various CairoFontFace functions can be used with a font face of any type.

The type of a CairoScaledFont is determined by the type of the CairoFontFace passed to CairoScaledFont::__construct or cairo_scaled_font_create(). The scaled font type can be queried with CairoScaledFont::getType or cairo_scaled_font_get_type().

Class synopsis

CairoFontType
CairoFontType {
/* Constants */
const integer CairoFontType::TOY = 0 ;
const integer CairoFontType::FT = 1 ;
const integer CairoFontType::WIN32 = 2 ;
const integer CairoFontType::QUARTZ = 3 ;
}

Predefined Constants

CairoFontType Node Types

CairoFontType::TOY

The font was created using CairoToyFont api

CairoFontType::FT

The font is of type CairoFreeType

CairoFontType::WIN32

The font is of type Win32

CairoFontType::QUARTZ

The font is of type Quartz

CairoFontType::USER

The font was create using cairo's user font api

CairoFontSlant
CairoFontWeight
Cairo


The CairoFontWeight class

Introduction

Specifies variants of a font face based on their weight.

Class synopsis

CairoFontWeight
CairoFontWeight {
/* Constants */
const integer CairoFontWeight::NORMAL = 0 ;
const integer CairoFontWeight::BOLD = 1 ;
}

Predefined Constants

CairoFontWeight Node Types

CairoFontWeight::NORMAL

Normal font weight

CairoFontWeight::BOLD

Bold font weight

CairoFontType
CairoScaledFont
Cairo


The CairoFormat class

Introduction

CairoFormat enums are used to identify the memory format of the image data.

Class synopsis

CairoFormat
CairoFormat {
/* Constants */
const integer CairoFormat::ARGB32 = 0 ;
const integer CairoFormat::RGB24 = 1 ;
const integer CairoFormat::A8 = 2 ;
const integer CairoFormat::A1 = 3 ;
/* Methods */
public static int strideForWidth ( int $format , int $width )
}

Predefined Constants

CairoFormat Node Types

CairoFormat::ARGB32

Each pixel is a 32-bit quantity, with alpha in the upper 8 bits, then red, then green, then blue. The 32-bit quantities are stored native-endian. Pre-multiplied alpha is used. (That is, 50% transparent red is 0x80800000, not 0x80ff0000.)

CairoFormat::RGB24

Each pixel is a 32-bit quantity, with the upper 8 bits unused. Red, Green, and Blue are stored in the remaining 24 bits in that order.

CairoFormat::A8

Each pixel is a 8-bit quantity holding an alpha value.

CairoFormat::A1

Each pixel is a 1-bit quantity holding an alpha value. Pixels are packed together into 32-bit quantities. The ordering of the bits matches the endianess of the platform. On a big-endian machine, the first pixel is in the uppermost bit, on a little-endian machine the first pixel is in the least-significant bit.

Table of Contents

  • CairoFormat::strideForWidth — Provides an appropiate stride to use
CairoExtend
CairoFormat::strideForWidth
Cairo


The CairoGradientPattern class

Introduction

CairoGradientPattern is an abstract base class from which other Pattern classes derive. It cannot be instantiated directly.

Class synopsis

CairoGradientPattern
CairoGradientPattern extends CairoPattern {
/* Methods */
public void addColorStopRgb ( string $offset , string $red , string $green , string $blue )
public void addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )
public int getColorStopCount ( void )
public array getColorStopRgba ( string $index )
public int getExtend ( void )
public void setExtend ( int $extend )
/* Inherited methods */
CairoPattern::__construct ( void )
public void CairoPattern::getMatrix ( void )
public int CairoPattern::getType ( void )
public void CairoPattern::setMatrix ( string $matrix )
public int CairoPattern::status ( void )
}

Table of Contents

  • CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose
  • CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose
  • CairoGradientPattern::getColorStopCount — The getColorStopCount purpose
  • CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose
  • CairoGradientPattern::getExtend — The getExtend purpose
  • CairoGradientPattern::setExtend — The setExtend purpose
CairoPattern::status
CairoGradientPattern::addColorStopRgb
Cairo


The CairoHintMetrics class

Introduction

Specifies whether to hint font metrics; hinting font metrics means quantizing them so that they are integer values in device space. Doing this improves the consistency of letter and line spacing, however it also means that text will be laid out differently at different zoom factors.

Class synopsis

CairoHintMetrics
CairoHintMetrics {
/* Constants */
const integer CairoHintMetrics::METRICS_DEFAULT = 0 ;
const integer CairoHintMetrics::METRICS_OFF = 1 ;
const integer CairoHintMetrics::METRICS_ON = 2 ;
}

Predefined Constants

CairoHintMetrics Node Types

CairoHintMetrics::METRICS_DEFAULT

Hint metrics in the default manner for the font backend and target device

CairoHintMetrics::METRICS_OFF

Do not hint font metrics

CairoHintMetrics::METRICS_ON

Hint font metrics

CairoFilter
CairoHintStyle
Cairo


The CairoHintStyle class

Introduction

Specifies the type of hinting to do on font outlines. Hinting is the process of fitting outlines to the pixel grid in order to improve the appearance of the result. Since hinting outlines involves distorting them, it also reduces the faithfulness to the original outline shapes. Not all of the outline hinting styles are supported by all font backends.

Class synopsis

CairoHintStyle
CairoHintStyle {
/* Constants */
const integer CairoHintStyle::STYLE_DEFAULT = 0 ;
const integer CairoHintStyle::STYLE_NONE = 1 ;
const integer CairoHintStyle::STYLE_SLIGHT = 2 ;
const integer CairoHintStyle::STYLE_MEDIUM = 3 ;
const integer CairoHintStyle::STYLE_FULL = 4 ;
}

Predefined Constants

CairoHintStyle Node Types

CairoHintStyle::STYLE_DEFAULT

Use the default hint style for font backend and target device

CairoHintStyle::STYLE_NONE

Do not hint outlines

CairoHintStyle::STYLE_SLIGHT

Hint outlines slightly to improve contrast while retaining good fidelity to the original shapes.

CairoHintStyle::STYLE_MEDIUM

Hint outlines with medium strength giving a compromise between fidelity to the original shapes and contrast

CairoHintStyle::STYLE_FULL

Hint outlines to maximize contrast

CairoHintMetrics
CairoLineCap
Cairo


The CairoImageSurface class

Introduction

CairoImageSurface provide the ability to render to memory buffers either allocated by cairo or by the calling code. The supported image formats are those defined in CairoFormat.

Class synopsis

CairoImageSurface
CairoImageSurface extends CairoSurface {
/* Methods */
__construct ( int $format , int $width , int $height )
public static void createForData ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )
public staticCairoImageSurface createFromPng ( string $file )
public string getData ( void )
public int getFormat ( void )
public int getHeight ( void )
public int getStride ( void )
public int getWidth ( void )
/* Inherited methods */
CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( string $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Table of Contents

  • CairoImageSurface::__construct — Creates a new CairoImageSurface
  • CairoImageSurface::createForData — The createForData purpose
  • CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file
  • CairoImageSurface::getData — Gets the image data as string
  • CairoImageSurface::getFormat — Get the image format
  • CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface
  • CairoImageSurface::getStride — The getStride purpose
  • CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface
CairoSvgSurface::versionToString
CairoImageSurface::__construct
Cairo


The CairoLinearGradient class

Introduction

Create a new CairoLinearGradient along the line defined

Class synopsis

CairoLinearGradient
CairoLinearGradient extends CairoGradientPattern {
/* Methods */
__construct ( float $x0 , float $y0 , float $x1 , float $y1 )
public array getPoints ( void )
/* Inherited methods */
public void CairoGradientPattern::addColorStopRgb ( string $offset , string $red , string $green , string $blue )
public void CairoGradientPattern::addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )
public int CairoGradientPattern::getColorStopCount ( void )
public array CairoGradientPattern::getColorStopRgba ( string $index )
public int CairoGradientPattern::getExtend ( void )
public void CairoGradientPattern::setExtend ( int $extend )
}

Table of Contents

  • CairoLinearGradient::__construct — The __construct purpose
  • CairoLinearGradient::getPoints — The getPoints purpose
CairoSurfacePattern::setFilter
CairoLinearGradient::__construct
Cairo


The CairoLineCap class

Introduction

Specifies how to render the endpoints of the path when stroking.

The default line cap style is CairoLineCap::BUTT.

Class synopsis

CairoLineCap
CairoLineCap {
/* Constants */
const integer CairoLineCap::BUTT = 0 ;
const integer CairoLineCap::ROUND = 1 ;
const integer CairoLineCap::SQUARE = 2 ;
}

Predefined Constants

CairoLineCap Node Types

CairoLineCap::BUTT

Start(stop) the line exactly at the start(end) point

CairoLineCap::ROUND

Use a round ending, the center of the circle is the end point

CairoLineCap::SQUARE

Use squared ending, the center of the square is the end point

CairoHintStyle
CairoLineJoin
Cairo


The CairoLineJoin class

Introduction

Description of the class.

Class synopsis

CairoLineJoin
CairoLineJoin {
/* Constants */
const integer CairoLineJoin::MITER = 0 ;
const integer CairoLineJoin::ROUND = 1 ;
const integer CairoLineJoin::BEVEL = 2 ;
}

Predefined Constants

CairoLineJoin Node Types

CairoLineJoin::MITER

Description here...

CairoLineJoin::ROUND

Description here...

CairoLineJoin::BEVEL

Description here...

CairoLineCap
CairoMatrix
Cairo


The CairoMatrix class

Introduction

Matrices are used throughout cairo to convert between different coordinate spaces.

Class synopsis

CairoMatrix
CairoMatrix {
/* Methods */
__construct ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )
public static void initIdentity ( void )
public static void initRotate ( float $radians )
public static void initScale ( float $sx , float $sy )
public static void initTranslate ( float $tx , float $ty )
public void invert ( void )
public static CairoMatrix multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )
public void rotate ( string $sx , string $sy )
public void scale ( float $sx , float $sy )
public array transformDistance ( string $dx , string $dy )
public array transformPoint ( string $dx , string $dy )
public void translate ( string $tx , string $ty )
}

Table of Contents

  • CairoMatrix::__construct — Creates a new CairoMatrix object
  • CairoMatrix::initIdentity — Creates a new identity matrix
  • CairoMatrix::initRotate — Creates a new rotated matrix
  • CairoMatrix::initScale — Creates a new scaling matrix
  • CairoMatrix::initTranslate — Creates a new translation matrix
  • CairoMatrix::invert — The invert purpose
  • CairoMatrix::multiply — The multiply purpose
  • CairoMatrix::rotate — The rotate purpose
  • CairoMatrix::scale — Applies scaling to a matrix
  • CairoMatrix::transformDistance — The transformDistance purpose
  • CairoMatrix::transformPoint — The transformPoint purpose
  • CairoMatrix::translate — The translate purpose
CairoLineJoin
CairoMatrix::__construct
Cairo


The CairoOperator class

Introduction

This is used to set the compositing operator for all cairo drawing operations.

The default operator is CairoOperator::OVER

The operators marked as unbounded modify their destination even outside of the mask layer (that is, their effect is not bound by the mask layer). However, their effect can still be limited by way of clipping.

To keep things simple, the operator descriptions here document the behavior for when both source and destination are either fully transparent or fully opaque. The actual implementation works for translucent layers too. For a more detailed explanation of the effects of each operator, including the mathematical definitions, see http://cairographics.org/operators/.

Class synopsis

CairoOperator
CairoOperator {
/* Constants */
const integer CairoOperator::CLEAR = 0 ;
const integer CairoOperator::SOURCE = 1 ;
const integer CairoOperator::OVER = 2 ;
const integer CairoOperator::IN = 3 ;
const integer CairoOperator::OUT = 4 ;
const integer CairoOperator::ATOP = 5 ;
const integer CairoOperator::DEST = 6 ;
const integer CairoOperator::DEST_OVER = 7 ;
const integer CairoOperator::DEST_IN = 8 ;
const integer CairoOperator::DEST_OUT = 9 ;
const integer CairoOperator::DEST_ATOP = 10 ;
const integer CairoOperator::XOR = 11 ;
const integer CairoOperator::ADD = 12 ;
const integer CairoOperator::SATURATE = 13 ;
}

Predefined Constants

CairoOperator Node Types

CairoOperator::CLEAR

Clear destination layer (bounded)

CairoOperator::SOURCE

Replace destination layer (bounded)

CairoOperator::OVER

Draw source layer on top of destination layer (bounded)

CairoOperator::IN

Draw source where there was destination content (unbounded)

CairoOperator::OUT

Draw source where there was no destination content (unbounded)

CairoOperator::ATOP

Draw source on top of destination content and only there

CairoOperator::DEST

Ignore the source

CairoOperator::DEST_OVER

Draw destination on top of source

CairoOperator::DEST_IN

Leave destination only where there was source content (unbounded)

CairoOperator::DEST_OUT

Leave destination only where there was no source content

CairoOperator::DEST_ATOP

Leave destination on top of source content and only there (unbounded)

CairoOperator::XOR

Source and destination are shown where there is only one of them

CairoOperator::ADD

Source and destination layers are accumulated

CairoOperator::SATURATE

Like CairoOperator::OVER, but assuming source and dest are disjoint geometries

CairoMatrix::translate
CairoPath
Cairo


The CairoPath class

Introduction

Description of the class.

Note: CairoPath class cannot be instantiated directly, doing so will result in Fatal Error if used or passed

Class synopsis

CairoPath
CairoPath {
}
CairoOperator
CairoPsLevel
Cairo


The CairoPattern class

Introduction

CairoPattern is the abstract base class from which all the other pattern classes derive. It cannot be instantiated directly

Class synopsis

CairoPattern
CairoPattern {
/* Methods */
__construct ( void )
public void getMatrix ( void )
public int getType ( void )
public void setMatrix ( string $matrix )
public int status ( void )
}

Table of Contents

  • CairoPattern::__construct — The __construct purpose
  • CairoPattern::getMatrix — The getMatrix purpose
  • CairoPattern::getType — The getType purpose
  • CairoPattern::setMatrix — The setMatrix purpose
  • CairoPattern::status — The status purpose
CairoPatternType
CairoPattern::__construct
Cairo


The CairoPatternType class

Introduction

CairoPatternType is used to describe the type of a given pattern.

The type of a pattern is determined by the function used to create it. The cairo_pattern_create_rgb() and cairo_pattern_create_rgba() functions create CairoPatternType::SOLID patterns. The remaining cairo_pattern_create_* functions map to pattern types in obvious ways.

Class synopsis

CairoPatternType
CairoPatternType {
/* Constants */
const integer CairoPatternType::SOLID = 0 ;
const integer CairoPatternType::SURFACE = 1 ;
const integer CairoPatternType::LINEAR = 2 ;
const integer CairoPatternType::RADIAL = 3 ;
}

Predefined Constants

CairoPatternType Node Types

CairoPatternType::SOLID

The pattern is a solid (uniform) color. It may be opaque or translucent.

CairoPatternType::SURFACE

The pattern is a based on a surface (an image).

CairoPatternType::LINEAR

The pattern is a linear gradient.

CairoPatternType::RADIAL

The pattern is a radial gradient.

CairoToyFontFace
CairoPattern
Cairo


The CairoPdfSurface class

Introduction

Description of the class.

Class synopsis

CairoPdfSurface
CairoPdfSurface extends CairoSurface {
/* Methods */
__construct ( string $file , float $width , float $height )
public void setSize ( string $width , string $height )
/* Inherited methods */
CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( string $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Table of Contents

  • CairoPdfSurface::__construct — The __construct purpose
  • CairoPdfSurface::setSize — The setSize purpose
CairoImageSurface::getWidth
CairoPdfSurface::__construct
Cairo


The CairoPsLevel class

Introduction

Description of the class.

Class synopsis

CairoPsLevel
CairoPsLevel {
/* Constants */
const integer CairoPsLevel::LEVEL_2 = 0 ;
const integer CairoPsLevel::LEVEL_3 = 1 ;
}

Predefined Constants

CairoPsLevel Node Types

CairoPsLevel::LEVEL_2

Description here...

CairoPsLevel::LEVEL_3

Description here...

CairoPath
CairoSubpixelOrder
Cairo


The CairoPsSurface class

Introduction

Description of the class.

Class synopsis

CairoPsSurface
CairoPsSurface extends CairoSurface {
/* Methods */
__construct ( string $file , float $width , float $height )
public void dscBeginPageSetup ( void )
public void dscBeginSetup ( void )
public void dscComment ( string $comment )
public bool getEps ( void )
public static array getLevels ( void )
public static string levelToString ( string $level )
public void restrictToLevel ( string $level )
public void setEps ( string $level )
public void setSize ( string $width , string $height )
/* Inherited methods */
CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( string $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Table of Contents

  • CairoPsSurface::__construct — The __construct purpose
  • CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose
  • CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose
  • CairoPsSurface::dscComment — The dscComment purpose
  • CairoPsSurface::getEps — The getEps purpose
  • CairoPsSurface::getLevels — The getLevels purpose
  • CairoPsSurface::levelToString — The levelToString purpose
  • CairoPsSurface::restrictToLevel — The restrictToLevel purpose
  • CairoPsSurface::setEps — The setEps purpose
  • CairoPsSurface::setSize — The setSize purpose
CairoPdfSurface::setSize
CairoPsSurface::__construct
Cairo


The CairoRadialGradient class

Introduction

Description of the class.

Class synopsis

CairoRadialGradient
CairoRadialGradient extends CairoGradientPattern {
/* Methods */
__construct ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )
public array getCircles ( void )
/* Inherited methods */
public void CairoGradientPattern::addColorStopRgb ( string $offset , string $red , string $green , string $blue )
public void CairoGradientPattern::addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )
public int CairoGradientPattern::getColorStopCount ( void )
public array CairoGradientPattern::getColorStopRgba ( string $index )
public int CairoGradientPattern::getExtend ( void )
public void CairoGradientPattern::setExtend ( int $extend )
}

Table of Contents

  • CairoRadialGradient::__construct — The __construct purpose
  • CairoRadialGradient::getCircles — The getCircles purpose
CairoLinearGradient::getPoints
CairoRadialGradient::__construct
Cairo


The CairoScaledFont class

Introduction

Description of the class.

Class synopsis

CairoScaledFont
CairoScaledFont {
/* Methods */
__construct ( CairoFontFace $font_face , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $options )
public array extents ( void )
public CairoMatrix getCtm ( void )
public void getFontFace ( void )
public void getFontMatrix ( void )
public void getFontOptions ( void )
public void getScaleMatrix ( void )
public int getType ( void )
public array glyphExtents ( string $glyphs )
public int status ( void )
public array textExtents ( string $text )
}

Table of Contents

  • CairoScaledFont::__construct — The __construct purpose
  • CairoScaledFont::extents — The extents purpose
  • CairoScaledFont::getCtm — The getCtm purpose
  • CairoScaledFont::getFontFace — The getFontFace purpose
  • CairoScaledFont::getFontMatrix — The getFontMatrix purpose
  • CairoScaledFont::getFontOptions — The getFontOptions purpose
  • CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose
  • CairoScaledFont::getType — The getType purpose
  • CairoScaledFont::glyphExtents — The glyphExtents purpose
  • CairoScaledFont::status — The status purpose
  • CairoScaledFont::textExtents — The textExtents purpose
CairoFontWeight
CairoScaledFont::__construct
Cairo


The CairoSolidPattern class

Introduction

Description of the class.

Class synopsis

CairoSolidPattern
CairoSolidPattern extends CairoPattern {
/* Methods */
__construct ( float $red , float $green , float $blue [, float $alpha = 0 ] )
public array getRgba ( void )
/* Inherited methods */
CairoPattern::__construct ( void )
public void CairoPattern::getMatrix ( void )
public int CairoPattern::getType ( void )
public void CairoPattern::setMatrix ( string $matrix )
public int CairoPattern::status ( void )
}

Table of Contents

  • CairoSolidPattern::__construct — The __construct purpose
  • CairoSolidPattern::getRgba — The getRgba purpose
CairoGradientPattern::setExtend
CairoSolidPattern::__construct
Cairo


The CairoStatus class

Introduction

CairoStatus is used to indicate errors that can occur when using Cairo. In some cases it is returned directly by functions. but when using CairoContext, the last error, if any, is stored in the object and can be retrieved with CairoContext::status or cairo_status(). New entries may be added in future versions.

Use Cairo::statusToString or cairo_status_to_string() to get a human-readable representation of an error message.

Class synopsis

CairoStatus
CairoStatus {
/* Constants */
const integer CairoStatus::SUCCESS = 0 ;
const integer CairoStatus::NO_MEMORY = 1 ;
const integer CairoStatus::INVALID_RESTORE = 2 ;
const integer CairoStatus::INVALID_POP_GROUP = 3 ;
const integer CairoStatus::NO_CURRENT_POINT = 4 ;
const integer CairoStatus::INVALID_MATRIX = 5 ;
const integer CairoStatus::INVALID_STATUS = 6 ;
const integer CairoStatus::NULL_POINTER = 7 ;
const integer CairoStatus::INVALID_STRING = 8 ;
const integer CairoStatus::INVALID_PATH_DATA = 9 ;
const integer CairoStatus::READ_ERROR = 10 ;
const integer CairoStatus::WRITE_ERROR = 11 ;
const integer CairoStatus::SURFACE_FINISHED = 12 ;
const integer CairoStatus::SURFACE_TYPE_MISMATCH = 13 ;
const integer CairoStatus::PATTERN_TYPE_MISMATCH = 14 ;
const integer CairoStatus::INVALID_CONTENT = 15 ;
const integer CairoStatus::INVALID_FORMAT = 16 ;
const integer CairoStatus::INVALID_VISUAL = 17 ;
const integer CairoStatus::FILE_NOT_FOUND = 18 ;
const integer CairoStatus::INVALID_DASH = 19 ;
const integer CairoStatus::INVALID_DSC_COMMENT = 20 ;
const integer CairoStatus::INVALID_INDEX = 21 ;
const integer CairoStatus::CLIP_NOT_REPRESENTABLE = 22 ;
const integer CairoStatus::TEMP_FILE_ERROR = 23 ;
const integer CairoStatus::INVALID_STRIDE = 24 ;
}

Predefined Constants

CairoStatus Node Types

CairoStatus::SUCCESS

No error has occurred

CairoStatus::NO_MEMORY

Out of memory

CairoStatus::INVALID_RESTORE

cairo_restore() called without matching cairo_save()

CairoStatus::INVALID_POP_GROUP

No saved group to pop

CairoStatus::NO_CURRENT_POINT

No current point defined

CairoStatus::INVALID_MATRIX

Invalid matrix (not invertible)

CairoStatus::INVALID_STATUS

Invalid value for an input CairoStatus>

CairoStatus::NULL_POINTER

Null pointer

CairoStatus::INVALID_STRING

Input string not valid UTF-8 string

CairoStatus::INVALID_PATH_DATA

Input path data not valid

CairoStatus::READ_ERROR

Error while reading from input stream

CairoStatus::WRITE_ERROR

Error while writing to output stream

CairoStatus::SURFACE_FINISHED

Target surface has been finished

CairoStatus::SURFACE_TYPE_MISMATCH

The surface type is not appropriate for the operation

CairoStatus::PATTERN_TYPE_MISMATCH

The pattern type is not appropriate for the operation

CairoStatus::INVALID_CONTENT

Invalid value for an input CairoContent

CairoStatus::INVALID_FORMAT

Invalid value for an input CairoFormat

CairoStatus::INVALID_VISUAL

Invalid value for an input Visual

CairoStatus::FILE_NOT_FOUND

File not found

CairoStatus::INVALID_DASH

Invalid value for a dash setting

CairoStatus::INVALID_DSC_COMMENT

Invalid value for a DSC comment

CairoStatus::INVALID_INDEX

Invalid index passed to getter

CairoStatus::CLIP_NOT_REPRESENTABLE

Clip region not representable in desired format

CairoStatus::TEMP_FILE_ERROR

Error creating or writing to a temporary file

CairoStatus::INVALID_STRIDE

Invalid value for CairoStride

CairoException
CairoSurface
Cairo


The CairoSubpixelOrder class

Introduction

Description of the class.

Class synopsis

CairoSubpixelOrder
CairoSubpixelOrder {
/* Constants */
const integer CairoSubpixelOrder::ORDER_DEFAULT = 0 ;
const integer CairoSubpixelOrder::ORDER_RGB = 1 ;
const integer CairoSubpixelOrder::ORDER_BGR = 2 ;
const integer CairoSubpixelOrder::ORDER_VRGB = 3 ;
const integer CairoSubpixelOrder::ORDER_VBGR = 4 ;
}

Predefined Constants

CairoSubpixelOrder Node Types

CairoSubpixelOrder::ORDER_DEFAULT

Description here...

CairoSubpixelOrder::ORDER_RGB

Description here...

CairoSubpixelOrder::ORDER_BGR

Description here...

CairoSubpixelOrder::ORDER_VRGB

Description here...

CairoSubpixelOrder::ORDER_VBGR

Description here...

CairoPsLevel
CairoSvgVersion
Cairo


The CairoSurface class

Introduction

Description of the class.

Class synopsis

CairoSurface
CairoSurface {
/* Methods */
__construct ( void )
public void copyPage ( void )
public void createSimilar ( string $content , string $width , string $height )
public void finish ( void )
public void flush ( void )
public int getContent ( void )
public array getDeviceOffset ( void )
public void getFontOptions ( void )
public int getType ( void )
public void markDirty ( void )
public void markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void setDeviceOffset ( string $x , string $y )
public void setFallbackResolution ( string $x , string $y )
public void showPage ( void )
public int status ( void )
public void writeToPng ( string $file )
}

Table of Contents

  • CairoSurface::__construct — The __construct purpose
  • CairoSurface::copyPage — The copyPage purpose
  • CairoSurface::createSimilar — The createSimilar purpose
  • CairoSurface::finish — The finish purpose
  • CairoSurface::flush — The flush purpose
  • CairoSurface::getContent — The getContent purpose
  • CairoSurface::getDeviceOffset — The getDeviceOffset purpose
  • CairoSurface::getFontOptions — The getFontOptions purpose
  • CairoSurface::getType — The getType purpose
  • CairoSurface::markDirty — The markDirty purpose
  • CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose
  • CairoSurface::setDeviceOffset — The setDeviceOffset purpose
  • CairoSurface::setFallbackResolution — The setFallbackResolution purpose
  • CairoSurface::showPage — The showPage purpose
  • CairoSurface::status — The status purpose
  • CairoSurface::writeToPng — The writeToPng purpose
CairoStatus
CairoSurface::__construct
Cairo


The CairoSurfacePattern class

Introduction

Description of the class.

Class synopsis

CairoSurfacePattern
CairoSurfacePattern extends CairoPattern {
/* Methods */
__construct ( CairoSurface $surface )
public int getExtend ( void )
public int getFilter ( void )
public void getSurface ( void )
public void setExtend ( int $extend )
public void setFilter ( string $filter )
/* Inherited methods */
CairoPattern::__construct ( void )
public void CairoPattern::getMatrix ( void )
public int CairoPattern::getType ( void )
public void CairoPattern::setMatrix ( string $matrix )
public int CairoPattern::status ( void )
}

Table of Contents

  • CairoSurfacePattern::__construct — The __construct purpose
  • CairoSurfacePattern::getExtend — The getExtend purpose
  • CairoSurfacePattern::getFilter — The getFilter purpose
  • CairoSurfacePattern::getSurface — The getSurface purpose
  • CairoSurfacePattern::setExtend — The setExtend purpose
  • CairoSurfacePattern::setFilter — The setFilter purpose
CairoSolidPattern::getRgba
CairoSurfacePattern::__construct
Cairo


The CairoSurfaceType class

Introduction

Description of the class.

Class synopsis

CairoSurfaceType
CairoSurfaceType {
/* Constants */
const integer CairoSurfaceType::IMAGE = 0 ;
const integer CairoSurfaceType::PDF = 1 ;
const integer CairoSurfaceType::PS = 2 ;
const integer CairoSurfaceType::XLIB = 3 ;
const integer CairoSurfaceType::XCB = 4 ;
const integer CairoSurfaceType::GLITZ = 5 ;
const integer CairoSurfaceType::QUARTZ = 6 ;
const integer CairoSurfaceType::WIN32 = 7 ;
const integer CairoSurfaceType::BEOS = 8 ;
const integer CairoSurfaceType::DIRECTFB = 9 ;
const integer CairoSurfaceType::SVG = 10 ;
const integer CairoSurfaceType::OS2 = 11 ;
const integer CairoSurfaceType::WIN32_PRINTING = 12 ;
const integer CairoSurfaceType::QUARTZ_IMAGE = 13 ;
}

Predefined Constants

CairoSurfaceType Node Types

CairoSurfaceType::IMAGE

Description here...

CairoSurfaceType::PDF

Description here...

CairoSurfaceType::PS

Description here...

CairoSurfaceType::XLIB

Description here...

CairoSurfaceType::XCB

Description here...

CairoSurfaceType::GLITZ

Description here...

CairoSurfaceType::QUARTZ

Description here...

CairoSurfaceType::WIN32

Description here...

CairoSurfaceType::BEOS

Description here...

CairoSurfaceType::DIRECTFB

Description here...

CairoSurfaceType::SVG

Description here...

CairoSurfaceType::OS2

Description here...

CairoSurfaceType::WIN32_PRINTING

Description here...

CairoSurfaceType::QUARTZ_IMAGE

Description here...

CairoPsSurface::setSize
CairoFontFace
Cairo


Svg Surface Backend

Introduction

Svg specific surface class, uses the SVG (standard vector graphics) surface backend.

Class synopsis

CairoSvgSurface
CairoSvgSurface extends CairoSurface {
/* Methods */
__construct ( string $file , float $width , float $height )
public static array getVersions ( void )
public void restrictToVersion ( string $version )
public static string versionToString ( int $version )
/* Inherited methods */
CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( string $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Table of Contents

  • CairoSvgSurface::__construct — The __construct purpose
  • CairoSvgSurface::getVersions — Used to retrieve a list of supported SVG versions
  • CairoSvgSurface::restrictToVersion — The restrictToVersion purpose
  • CairoSvgSurface::versionToString — The versionToString purpose
CairoSurface::writeToPng
CairoSvgSurface::__construct
Cairo


The CairoSvgVersion class

Introduction

Description of the class.

Class synopsis

CairoSvgVersion
CairoSvgVersion {
/* Constants */
const integer CairoSvgVersion::VERSION_1_1 = 0 ;
const integer CairoSvgVersion::VERSION_1_2 = 1 ;
}

Predefined Constants

CairoSvgVersion Node Types

CairoSvgVersion::VERSION_1_1

Description here...

CairoSvgVersion::VERSION_1_2

Description here...

CairoSubpixelOrder
Mail Related Extensions
Cairo


The CairoToyFontFace class

Introduction

The CairoToyFontFace class can be used instead of CairoContext::selectFontFace to create a toy font independently of a context.

Class synopsis

CairoToyFontFace
CairoToyFontFace extends CairoFontFace {
/* Inherited methods */
}
CairoScaledFont::textExtents
CairoPatternType
Cairo


The Collator class

Introduction

Provides string comparison capability with support for appropriate locale-sensitive sort orderings.

Class synopsis

Collator
Collator {
/* Methods */
__construct ( string $locale )
bool asort ( array &$arr [, int $sort_flag ] )
int compare ( string $str1 , string $str2 )
static Collator create ( string $locale )
int getAttribute ( int $attr )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ([ int $type ] )
string getSortKey ( string $str )
int getStrength ( void )
bool setAttribute ( int $attr , int $val )
bool setStrength ( int $strength )
bool sortWithSortKeys ( array &$arr )
bool sort ( array &$arr [, int $sort_flag ] )
}

Predefined Constants

Collator::FRENCH_COLLATION (integer)

Sort strings with different accents from the back of the string. This attribute is automatically set to On for the French locales and a few others. Users normally would not need to explicitly set this attribute. There is a string comparison performance cost when it is set On, but sort key length is unaffected. Possible values are:

  • Collator::ON
  • Collator::OFF(default)
  • Collator::DEFAULT_VALUE

Example #1 FRENCH_COLLATION rules

  • F=OFF cote < coté < côte < côté
  • F=ON cote < côte < coté < côté

Collator::ALTERNATE_HANDLING (integer)

The Alternate attribute is used to control the handling of the so called variable characters in the UCA: whitespace, punctuation and symbols. If Alternate is set to NonIgnorable (N), then differences among these characters are of the same importance as differences among letters. If Alternate is set to Shifted (S), then these characters are of only minor importance. The Shifted value is often used in combination with Strength set to Quaternary. In such a case, whitespace, punctuation, and symbols are considered when comparing strings, but only if all other aspects of the strings (base letters, accents, and case) are identical. If Alternate is not set to Shifted, then there is no difference between a Strength of 3 and a Strength of 4. For more information and examples, see Variable_Weighting in the » UCA . The reason the Alternate values are not simply On and Off is that additional Alternate values may be added in the future. The UCA option Blanked is expressed with Strength set to 3, and Alternate set to Shifted. The default for most locales is NonIgnorable. If Shifted is selected, it may be slower if there are many strings that are the same except for punctuation; sort key length will not be affected unless the strength level is also increased.

Possible values are:

  • Collator::NON_IGNORABLE(default)
  • Collator::SHIFTED
  • Collator::DEFAULT_VALUE

Example #2 ALTERNATE_HANDLING rules

  • S=3, A=N di Silva < Di Silva < diSilva < U.S.A. < USA
  • S=3, A=S di Silva = diSilva < Di Silva < U.S.A. = USA
  • S=4, A=S di Silva < diSilva < Di Silva < U.S.A. < USA

Collator::CASE_FIRST (integer)

The Case_First attribute is used to control whether uppercase letters come before lowercase letters or vice versa, in the absence of other differences in the strings. The possible values are Uppercase_First (U) and Lowercase_First (L), plus the standard Default and Off. There is almost no difference between the Off and Lowercase_First options in terms of results, so typically users will not use Lowercase_First: only Off or Uppercase_First. (People interested in the detailed differences between X and L should consult the Collation Customization). Specifying either L or U won't affect string comparison performance, but will affect the sort key length.

Possible values are:

  • Collator::OFF(default)
  • Collator::LOWER_FIRST
  • Collator::UPPER_FIRST
  • Collator:DEFAULT

Example #3 CASE_FIRST rules

  • C=X or C=L "china" < "China" < "denmark" < "Denmark"
  • C=U "China" < "china" < "Denmark" < "denmark"

Collator::CASE_LEVEL (integer)

The Case_Level attribute is used when ignoring accents but not case. In such a situation, set Strength to be Primary, and Case_Level to be On. In most locales, this setting is Off by default. There is a small string comparison performance and sort key impact if this attribute is set to be On.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Example #4 CASE_LEVEL rules

  • S=1, E=X role = Role = rôle
  • S=1, E=O role = rôle < Role

Collator::NORMALIZATION_MODE (integer)

The Normalization setting determines whether text is thoroughly normalized or not in comparison. Even if the setting is off (which is the default for many locales), text as represented in common usage will compare correctly (for details, see UTN #5). Only if the accent marks are in noncanonical order will there be a problem. If the setting is On, then the best results are guaranteed for all possible text input. There is a medium string comparison performance cost if this attribute is On, depending on the frequency of sequences that require normalization. There is no significant effect on sort key length. If the input text is known to be in NFD or NFKD normalization forms, there is no need to enable this Normalization option.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::STRENGTH (integer)

The ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions. For more detailed information, see collator_set_strength() chapter.

Possible values are:

  • Collator::PRIMARY
  • Collator::SECONDARY
  • Collator::TERTIARY(default)
  • Collator::QUATERNARY
  • Collator::IDENTICAL
  • Collator::DEFAULT_VALUE

Collator::HIRAGANA_QUATERNARY_MODE (integer)

Compatibility with JIS x 4061 requires the introduction of an additional level to distinguish Hiragana and Katakana characters. If compatibility with that standard is required, then this attribute should be set On, and the strength set to Quaternary. This will affect sort key length and string comparison string comparison performance.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::NUMERIC_COLLATION (integer)

When turned on, this attribute generates a collation key for the numeric value of substrings of digits. This is a way to get '100' to sort AFTER '2'.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::DEFAULT_VALUE (integer)
Collator::PRIMARY (integer)
Collator::SECONDARY (integer)
Collator::TERTIARY (integer)
Collator::DEFAULT_STRENGTH (integer)
Collator::QUATERNARY (integer)
Collator::IDENTICAL (integer)
Collator::OFF (integer)
Collator::ON (integer)
Collator::SHIFTED (integer)
Collator::NON_IGNORABLE (integer)
Collator::LOWER_FIRST (integer)
Collator::UPPER_FIRST (integer)

Table of Contents

  • Collator::asort — Sort array maintaining index association
  • Collator::compare — Compare two Unicode strings
  • Collator::__construct — Create a collator
  • Collator::create — Create a collator
  • Collator::getAttribute — Get collation attribute value
  • Collator::getErrorCode — Get collator's last error code
  • Collator::getErrorMessage — Get text for collator's last error code
  • Collator::getLocale — Get the locale name of the collator
  • Collator::getSortKey — Get sorting key for a string
  • Collator::getStrength — Get current collation strength
  • Collator::setAttribute — Set collation attribute
  • Collator::setStrength — Set collation strength
  • Collator::sortWithSortKeys — Sort array using specified collator and sort keys
  • Collator::sort — Sort array using specified collator
Basic usage of this extension
Collator::asort
intl


The DateInterval class

Introduction

Representation of date interval.

Class synopsis

DateInterval
DateInterval {
/* Methods */
__construct ( string $interval_spec )
public static DateInterval createFromDateString ( string $time )
public string format ( string $format )
}

Table of Contents

  • DateInterval::__construct — Creates new DateInterval object
  • DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
  • DateInterval::format — Formats the interval
DateTimeZone::listIdentifiers
DateInterval::__construct
Date/Time


The DatePeriod class

Introduction

Representation of date period.

Class synopsis

DatePeriod
DatePeriod implements Traversable {
/* Constants */
const integer DatePeriod::EXCLUDE_START_DATE = 1 ;
/* Methods */
__construct ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
}

Predefined Constants

DatePeriod Node Types

DatePeriod::EXCLUDE_START_DATE

Exclude start date, used in DatePeriod::__construct().

Table of Contents

  • DatePeriod::__construct — Creates new DatePeriod object
DateInterval::format
DatePeriod::__construct
Date/Time


The DateTime class

Introduction

Representation of date and time.

Class synopsis

DateTime
DateTime {
/* Constants */
const string DateTime::ATOM = Y-m-d\TH:i:sP ;
const string DateTime::COOKIE = l, d-M-y H:i:s T ;
const string DateTime::ISO8601 = Y-m-d\TH:i:sO ;
const string DateTime::RFC822 = D, d M y H:i:s O ;
const string DateTime::RFC850 = l, d-M-y H:i:s T ;
const string DateTime::RFC1036 = D, d M y H:i:s O ;
const string DateTime::RFC1123 = D, d M Y H:i:s O ;
const string DateTime::RFC2822 = D, d M Y H:i:s O ;
const string DateTime::RFC3339 = Y-m-d\TH:i:sP ;
const string DateTime::RSS = D, d M Y H:i:s O ;
const string DateTime::W3C = Y-m-d\TH:i:sP ;
/* Methods */
public DateTime add ( DateInterval $interval )
__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
public static DateTime createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
public DateInterval diff ( DateTime $datetime [, bool $absolute = false ] )
public string format ( string $format )
public static array getLastErrors ( void )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( void )
public DateTime modify ( string $modify )
public static DateTime __set_state ( array $array )
public DateTime setDate ( int $year , int $month , int $day )
public DateTime setISODate ( int $year , int $week [, int $day ] )
public DateTime setTime ( int $hour , int $minute [, int $second ] )
public DateTime setTimestamp ( int $unixtimestamp )
public DateTime setTimezone ( DateTimeZone $timezone )
public DateTime sub ( DateInterval $interval )
public DateTime __wakeup ( void )
}

Predefined Constants

DateTime Node Types

DateTime::ATOM
DATE_ATOM
Atom (example: 2005-08-15T15:52:01+00:00)
DateTime::COOKIE
DATE_COOKIE
HTTP Cookies (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTime::ISO8601
DATE_ISO8601
ISO-8601 (example: 2005-08-15T15:52:01+0000)
DateTime::RFC822
DATE_RFC822
RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTime::RFC850
DATE_RFC850
RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTime::RFC1036
DATE_RFC1036
RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTime::RFC1123
DATE_RFC1123
RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::RFC2822
DATE_RFC2822
RFC 2822 (Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::RFC3339
DATE_RFC3339
Same as DATE_ATOM (since PHP 5.1.3)
DateTime::RSS
DATE_RSS
RSS (Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::W3C
DATE_W3C
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

Table of Contents

  • DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::__construct — Returns new DateTime object
  • DateTime::createFromFormat — Returns new DateTime object formatted according to the specified format
  • DateTime::diff — Returns the difference between two DateTime objects
  • DateTime::format — Returns date formatted according to given format
  • DateTime::getLastErrors — Returns the warnings and errors
  • DateTime::getOffset — Returns the timezone offset
  • DateTime::getTimestamp — Gets the Unix timestamp
  • DateTime::getTimezone — Return time zone relative to given DateTime
  • DateTime::modify — Alters the timestamp
  • DateTime::__set_state — The __set_state handler
  • DateTime::setDate — Sets the date
  • DateTime::setISODate — Sets the ISO date
  • DateTime::setTime — Sets the time
  • DateTime::setTimestamp — Sets the date and time based on an Unix timestamp
  • DateTime::setTimezone — Sets the time zone for the DateTime object
  • DateTime::sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::__wakeup — The __wakeup handler
Others
DateTime::add
Date/Time


The DateTimeZone class

Introduction

Representation of time zone.

Class synopsis

DateTimeZone
DateTimeZone {
/* Constants */
const integer DateTimeZone::AFRICA = 1 ;
const integer DateTimeZone::AMERICA = 2 ;
const integer DateTimeZone::ANTARCTICA = 4 ;
const integer DateTimeZone::ARCTIC = 8 ;
const integer DateTimeZone::ASIA = 16 ;
const integer DateTimeZone::ATLANTIC = 32 ;
const integer DateTimeZone::AUSTRALIA = 64 ;
const integer DateTimeZone::EUROPE = 128 ;
const integer DateTimeZone::INDIAN = 256 ;
const integer DateTimeZone::PACIFIC = 512 ;
const integer DateTimeZone::UTC = 1024 ;
const integer DateTimeZone::ALL = 2047 ;
const integer DateTimeZone::ALL_WITH_BC = 4095 ;
const integer DateTimeZone::PER_COUNTRY = 4096 ;
/* Methods */
public __construct ( string $timezone )
public array getLocation ( void )
public string getName ( void )
public int getOffset ( DateTime $datetime )
public array getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )
public static array listAbbreviations ( void )
public static array listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )
}

Predefined Constants

DateTimeZone Node Types

DateTimeZone::AFRICA

Africa time zones.

DateTimeZone::AMERICA

America time zones.

DateTimeZone::ANTARCTICA

Antarctica time zones.

DateTimeZone::ARCTIC

Arctic time zones.

DateTimeZone::ASIA

Asia time zones.

DateTimeZone::ATLANTIC

Atlantic time zones.

DateTimeZone::AUSTRALIA

Australia time zones.

DateTimeZone::EUROPE

Europe time zones.

DateTimeZone::INDIAN

Indian time zones.

DateTimeZone::PACIFIC

Pacific time zones.

DateTimeZone::UTC

UTC time zones.

DateTimeZone::ALL

All time zones.

DateTimeZone::ALL_WITH_BC

All time zones including backwards compatible.

DateTimeZone::PER_COUNTRY

Time zones per country.

Table of Contents

  • DateTimeZone::__construct — Creates new DateTimeZone object
  • DateTimeZone::getLocation — Returns location information for a timezone
  • DateTimeZone::getName — Returns the name of the timezone
  • DateTimeZone::getOffset — Returns the timezone offset from GMT
  • DateTimeZone::getTransitions — Returns all transitions for the timezone
  • DateTimeZone::listAbbreviations — Returns associative array containing dst, offset and the timezone name
  • DateTimeZone::listIdentifiers — Returns numerically index array with all timezone identifiers
DateTime::__wakeup
DateTimeZone::__construct
Date/Time


Return an instance of the Directory class

chroot
closedir
Directory Functions
PHP Manual

dir

(PHP 4, PHP 5)

dir — Return an instance of the Directory class

Description

Directory
Directory {
string $path ;
resource $handle ;
string read ( void )
void rewind ( void )
void close ( void )
}

A pseudo-object oriented mechanism for reading a directory. The given directory is opened. Two properties are available once the directory has been opened. The handle property can be used with other directory functions such as readdir(), rewinddir() and closedir(). The path property is set to path the directory that was opened. Three methods are available: read, rewind and close.

Examples

Example #1 dir() example

Please note the fashion in which dir::read()'s return value is checked in the example below. We are explicitly testing whether the return value is identical to (equal to and of the same type as - see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop.

<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
   echo $entry."\n";
}
$d->close();
?>

The above example will output something similar to:

Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli

Notes

Note: The order in which directory entries are returned by the read method is system-dependent.

chroot
closedir
Directory Functions


ErrorException

Introduction

An Error Exception.

Class synopsis

ErrorException
ErrorException extends Exception {
/* Properties */
protected int $severity ;
/* Methods */
public __construct ([ string $message [, int $code [, int $severity [, string $filename [, int $lineno ]]]]] )
final public int getSeverity ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public int Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Properties

severity

The severity of the exception

Examples

Example #1 Use set_error_handler() to change error messages into ErrorException.

<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

The above example will output something similar to:

Fatal error: Uncaught exception 'ErrorException' with message 'Wrong parameter count for strpos()' in /home/bjori/tmp/ex.php:8
Stack trace:
#0 [internal function]: exception_error_handler(2, 'Wrong parameter...', '/home/bjori/php...', 8, Array)
#1 /home/bjori/php/cleandocs/test.php(8): strpos()
#2 {main}
  thrown in /home/bjori/tmp/ex.php on line 8

Table of Contents

  • ErrorException::__construct — Construct the exception
  • ErrorException::getSeverity — Gets the exception severity
Exception::__clone
ErrorException::__construct
Predefined Exceptions


Exception

Introduction

Exception is the base class for all Exceptions.

Class synopsis

Exception
Exception {
/* Properties */
protected string $message ;
private string $string ;
protected int $code ;
protected string $file ;
protected int $line ;
private array $trace ;
/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
final public string getMessage ( void )
final public Exception getPrevious ( void )
final public int getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )
}

Properties

message

The exception message

string

Internal Exception name

code

The Exception code

file

The filename where the exception was thrown

line

The line where the exception was thrown

trace

The stack trace

Table of Contents

  • Exception::__construct — Construct the exception
  • Exception::getMessage — Gets the Exception message
  • Exception::getPrevious — Returns previous Exception
  • Exception::getCode — Gets the Exception code
  • Exception::getFile — Gets the file in which the exception occurred
  • Exception::getLine — Gets the line in which the exception occurred
  • Exception::getTrace — Gets the stack trace
  • Exception::getTraceAsString — Gets the stack trace as a string
  • Exception::__toString — String representation of the exception
  • Exception::__clone — Clone the exception
Predefined Exceptions
Exception::__construct
Predefined Exceptions


The Gmagick class

Introduction

Description of the class.

Class synopsis

Gmagick
Gmagick {
/* Methods */
public void addimage ( Gmagick $Gmagick )
public void addnoiseimage ( int $NOISE )
public void annotateimage ( GmagickDraw $GmagickDraw , int $x , int $y , float $angle , string $text )
public void blurimage ( float $radius , float $sigma )
public void borderimage ( GmagickPixel $color , int $width , int $height )
public void charcoalimage ( float $radius , float $sigma )
public void chopimage ( int $width , int $height , int $x , int $y )
public void clear ( void )
public void commentimage ( string $comment )
public void compositeimage ( Gmagick $source , int $COMPOSE , int $x , int $y )
__construct ([ string $filename ] )
public void cropimage ( int $width , int $height , int $x , int $y )
public void cropthumbnailimage ( int $width , int $height )
public void current ( void )
public void cyclecolormapimage ( float $displace )
public void deconstructimages ( void )
public void despeckleimage ( void )
public void destroy ( void )
public void drawimage ( GmagickDraw $GmagickDraw )
public void edgeimage ( float $radius )
public void embossimage ( float $radius , float $sigma )
public void enhanceimage ( void )
public void equalizeimage ( void )
public void flipimage ( void )
public void flopimage ( void )
public void frameimage ( GmagickPixel $color , int $width , int $height , int $inner_bevel , int $outer_bevel )
public void gammaimage ( float $gamma )
public void getcopyright ( void )
public void getfilename ( void )
public void getimagebackgroundcolor ( void )
public void getimageblueprimary ( void )
public void getimagebordercolor ( void )
public void getimagechanneldepth ( void )
public void getimagecolors ( void )
public void getimagecolorspace ( void )
public void getimagecompose ( void )
public void getimagedelay ( void )
public void getimagedepth ( void )
public void getimagedispose ( void )
public void getimageextrema ( void )
public void getimagefilename ( void )
public void getimageformat ( void )
public void getimagegamma ( void )
public void getimagegreenprimary ( void )
public void getimageheight ( void )
public void getimagehistogram ( void )
public void getimageindex ( void )
public void getimageinterlacescheme ( void )
public void getimageiterations ( void )
public void getimagematte ( void )
public void getimagemattecolor ( void )
public void getimageprofile ( void )
public void getimageredprimary ( void )
public void getimagerenderingintent ( void )
public void getimageresolution ( void )
public void getimagescene ( void )
public void getimagesignature ( void )
public void getimagetype ( void )
public void getimageunits ( void )
public void getimagewhitepoint ( void )
public void getimagewidth ( void )
public void getpackagename ( void )
public void getquantumdepth ( void )
public void getreleasedate ( void )
public void getsamplingfactors ( void )
public void getsize ( void )
public void getversion ( void )
public void hasnextimage ( void )
public void haspreviousimage ( void )
public void implodeimage ( float $radius )
public void labelimage ( string $label )
public void levelimage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel ] )
public void magnifyimage ( void )
public void mapimage ( gmagick $gmagick , int $dither )
public void medianfilterimage ( float $radius )
public void minifyimage ( void )
public void modulateimage ( float $brightness , float $saturation , float $hue )
public void motionblurimage ( float $radius , float $sigma , float $angle )
public void newimage ( int $width , int $height , mixed $background , string $format )
public void nextimage ( void )
public void normalizeimage ([ int $channel ] )
public void oilpaintimage ( float $radius )
public void previousimage ( void )
public void profileimage ( string $name , string $profile )
public void quantizeimage ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )
public void quantizeimages ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )
public void queryfontmetrics ( void )
public void queryfonts ( void )
public void queryformats ( string $pattern )
public void radialblurimage ( float $angle [, int $channel ] )
public void raiseimage ( int $width , int $height , int $x , int $y , bool $raise )
public void read ( string $filename )
public void readimage ( string $filename )
public void readimageblob ( string $imageContents [, string $filename ] )
public void readimagefile ( string $fp )
public void reducenoiseimage ( float $radius )
public void removeimage ( void )
public void removeimageprofile ( string $name )
public void resampleimage ( float $xResolution , float $yResolution , int $filter , float $blur )
public void resizeimage ( int $width , int $height , int $filter , float $blur [, bool $fit ] )
public void rollimage ( int $x , int $y )
public void rotateimage ( mixed $color , float $degrees )
public void scaleimage ( int $width , int $height )
public void separateimagechannel ( int $channel )
public void setfilename ( string $filename )
public void setimagebackgroundcolor ( GmagickPixel $color )
public void setimageblueprimary ( float $x , float $y )
public void setimagebordercolor ( GmagickPixel $color )
public void setimagechanneldepth ( int $channel , int $depth )
public void setimagecolorspace ( int $colorspace )
public void setimagecompose ( int $composite )
public void setimagedelay ( int $delay )
public void setimagedepth ( float $depth )
public void setimagedispose ( int $disposeType )
public void setimagefilename ( string $filename )
public void setimageformat ( string $imageFormat )
public void setimagegamma ( float $gamma )
public void setimagegreenprimary ( float $x , float $y )
public void setimageindex ( int $index )
public void setimageinterlacescheme ( int $interlace )
public void setimageiterations ( int $iterations )
public void setimageprofile ( string $name , string $profile )
public void setimageredprimary ( float $x , float $y )
public void setimagerenderingintent ( int $rendering_intent )
public void setimageresolution ( float $xResolution , float $yResolution )
public void setimagescene ( string $scene )
public void setimagetype ( string $imgType )
public void setimageunits ( int $resolution )
public void setimagewhitepoint ( float $x , float $y )
public void setsamplingfactors ( array $factors )
public void setsize ( int $columns , int $rows )
public void shearimage ( mixed $color , float $xShear , float $yShear )
public void solarizeimage ( float $threshold )
public void spreadimage ( float $radius )
public void stripimage ( void )
public void swirlimage ( float $degrees )
public void thumbnailimage ( int $width , int $height )
public void trimimage ( float $fuzz )
public void write ( string $filename )
public void writeimage ( string $filename )
}

Table of Contents

  • Gmagick::addimage — Adds new image to Gmagick object image list
  • Gmagick::addnoiseimage — Adds random noise to the image
  • Gmagick::annotateimage — Annotates an image with text
  • Gmagick::blurimage — Adds blur filter to image
  • Gmagick::borderimage — Surrounds the image with a border
  • Gmagick::charcoalimage — Simulates a charcoal drawing
  • Gmagick::chopimage — Removes a region of an image and trims
  • Gmagick::clear — Clears all resources associated to Gmagick object
  • Gmagick::commentimage — Adds a comment to your image
  • Gmagick::compositeimage — Composite one image onto another
  • Gmagick::__construct — The Gmagick constructor
  • Gmagick::cropimage — Extracts a region of the image
  • Gmagick::cropthumbnailimage — Creates a crop thumbnail
  • Gmagick::current — The current purpose
  • Gmagick::cyclecolormapimage — Displaces an image's colormap
  • Gmagick::deconstructimages — Returns certain pixel differences between images
  • Gmagick::despeckleimage — The despeckleimage purpose
  • Gmagick::destroy — The destroy purpose
  • Gmagick::drawimage — Renders the GmagickDraw object on the current image
  • Gmagick::edgeimage — Enhance edges within the image
  • Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect
  • Gmagick::enhanceimage — Improves the quality of a noisy image
  • Gmagick::equalizeimage — Equalizes the image histogram
  • Gmagick::flipimage — Creates a vertical mirror image
  • Gmagick::flopimage — The flopimage purpose
  • Gmagick::frameimage — Adds a simulated three-dimensional border
  • Gmagick::gammaimage — Gamma-corrects an image
  • Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string
  • Gmagick::getfilename — The filename associated with an image sequence
  • Gmagick::getimagebackgroundcolor — Returns the image background color
  • Gmagick::getimageblueprimary — Returns the chromaticy blue primary point
  • Gmagick::getimagebordercolor — Returns the image border color
  • Gmagick::getimagechanneldepth — Gets the depth for a particular image channel
  • Gmagick::getimagecolors — Returns the color of the specified colormap index
  • Gmagick::getimagecolorspace — Gets the image colorspace
  • Gmagick::getimagecompose — Returns the composite operator associated with the image
  • Gmagick::getimagedelay — Gets the image delay
  • Gmagick::getimagedepth — Gets the depth of the image
  • Gmagick::getimagedispose — Gets the image disposal method
  • Gmagick::getimageextrema — Gets the extrema for the image
  • Gmagick::getimagefilename — Returns the filename of a particular image in a sequence
  • Gmagick::getimageformat — Returns the format of a particular image in a sequence
  • Gmagick::getimagegamma — Gets the image gamma
  • Gmagick::getimagegreenprimary — Returns the chromaticy green primary point
  • Gmagick::getimageheight — Returns the image height
  • Gmagick::getimagehistogram — Gets the image histogram
  • Gmagick::getimageindex — Gets the index of the current active image
  • Gmagick::getimageinterlacescheme — Gets the image interlace scheme
  • Gmagick::getimageiterations — Gets the image iterations
  • Gmagick::getimagematte — Return if the image has a matte channel
  • Gmagick::getimagemattecolor — Returns the image matte color
  • Gmagick::getimageprofile — Returns the named image profile.
  • Gmagick::getimageredprimary — Returns the chromaticity red primary point
  • Gmagick::getimagerenderingintent — Gets the image rendering intent
  • Gmagick::getimageresolution — Gets the image X and Y resolution
  • Gmagick::getimagescene — Gets the image scene
  • Gmagick::getimagesignature — Generates an SHA-256 message digest
  • Gmagick::getimagetype — Gets the potential image type.
  • Gmagick::getimageunits — Gets the image units of resolution
  • Gmagick::getimagewhitepoint — Returns the chromaticity white point
  • Gmagick::getimagewidth — Returns the width of the image
  • Gmagick::getpackagename — Returns the GraphicsMagick package name.
  • Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string.
  • Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string.
  • Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor.
  • Gmagick::getsize — Returns the size associated with the Gmagick object
  • Gmagick::getversion — Returns the GraphicsMagick API version
  • Gmagick::hasnextimage — Checks if the object has more images
  • Gmagick::haspreviousimage — Checks if the object has a previous image
  • Gmagick::implodeimage — Creates a new image as a copy
  • Gmagick::labelimage — Adds a label to an image.
  • Gmagick::levelimage — Adjusts the levels of an image
  • Gmagick::magnifyimage — Scales an image proportionally 2x
  • Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image.
  • Gmagick::medianfilterimage — Applies a digital filter
  • Gmagick::minifyimage — Scales an image proportionally to half its size
  • Gmagick::modulateimage — Control the brightness, saturation, and hue
  • Gmagick::motionblurimage — Simulates motion blur
  • Gmagick::newimage — Creates a new image
  • Gmagick::nextimage — Moves to the next image
  • Gmagick::normalizeimage — Enhances the contrast of a color image
  • Gmagick::oilpaintimage — Simulates an oil painting
  • Gmagick::previousimage — Move to the previous image in the object
  • Gmagick::profileimage — Adds or removes a profile from an image
  • Gmagick::quantizeimage — Analyzes the colors within a reference image
  • Gmagick::quantizeimages — The quantizeimages purpose
  • Gmagick::queryfontmetrics — Returns an array representing the font metrics
  • Gmagick::queryfonts — Returns the configured fonts
  • Gmagick::queryformats — Returns formats supported by Gmagick.
  • Gmagick::radialblurimage — Radial blurs an image
  • Gmagick::raiseimage — Creates a simulated 3d button-like effect
  • Gmagick::read — Reads image from filename
  • Gmagick::readimage — Reads image from filename
  • Gmagick::readimageblob — Reads image from a binary string
  • Gmagick::readimagefile — The readimagefile purpose
  • Gmagick::reducenoiseimage — Smooths the contours of an image
  • Gmagick::removeimage — Removes an image from the image list
  • Gmagick::removeimageprofile — Removes the named image profile and returns it
  • Gmagick::resampleimage — Resample image to desired resolution
  • Gmagick::resizeimage — Scales an image
  • Gmagick::rollimage — Offsets an image
  • Gmagick::rotateimage — Rotates an image
  • Gmagick::scaleimage — Scales the size of an image
  • Gmagick::separateimagechannel — Separates a channel from the image
  • Gmagick::setfilename — Sets the filename before you read or write the image
  • Gmagick::setimagebackgroundcolor — Sets the image background color.
  • Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point.
  • Gmagick::setimagebordercolor — Sets the image border color.
  • Gmagick::setimagechanneldepth — Sets the depth of a particular image channel
  • Gmagick::setimagecolorspace — Sets the image colorspace
  • Gmagick::setimagecompose — Sets the image composite operator
  • Gmagick::setimagedelay — Sets the image delay
  • Gmagick::setimagedepth — Sets the image depth
  • Gmagick::setimagedispose — Sets the image disposal method
  • Gmagick::setimagefilename — Sets the filename of a particular image in a sequence
  • Gmagick::setimageformat — Sets the format of a particular image
  • Gmagick::setimagegamma — Sets the image gamma
  • Gmagick::setimagegreenprimary — TSets the image chromaticity green primary point.
  • Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter
  • Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image.
  • Gmagick::setimageiterations — Sets the image iterations.
  • Gmagick::setimageprofile — Adds a named profile to the Gmagick object
  • Gmagick::setimageredprimary — Sets the image chromaticity red primary point.
  • Gmagick::setimagerenderingintent — Sets the image rendering intent
  • Gmagick::setimageresolution — Sets the image resolution
  • Gmagick::setimagescene — Sets the image scene
  • Gmagick::setimagetype — Sets the image type
  • Gmagick::setimageunits — Sets the image units of resolution.
  • Gmagick::setimagewhitepoint — Sets the image chromaticity white point.
  • Gmagick::setsamplingfactors — Sets the image sampling factors.
  • Gmagick::setsize — Sets the size of the Gmagick object
  • Gmagick::shearimage — Creating a parallelogram
  • Gmagick::solarizeimage — Applies a solarizing effect to the image
  • Gmagick::spreadimage — Randomly displaces each pixel in a block
  • Gmagick::stripimage — Strips an image of all profiles and comments
  • Gmagick::swirlimage — Swirls the pixels about the center of the image
  • Gmagick::thumbnailimage — Changes the size of an image
  • Gmagick::trimimage — Remove edges from the image
  • Gmagick::write — Writes an image to the specified filename
  • Gmagick::writeimage — Writes an image to the specified filename
Examples
Gmagick::addimage
Gmagick


The GmagickDraw class

Introduction

Description of the class.

Class synopsis

GmagickDraw
GmagickDraw {
/* Methods */
public void annotate ( float $x , float $y , string $text )
public void arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )
public void bezier ( array $coordinate_array )
public void ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )
public void getfillcolor ( void )
public void getfillopacity ( void )
public void getfont ( void )
public void getfontsize ( void )
public void getfontstyle ( void )
public void getfontweight ( void )
public void getstrokecolor ( void )
public void getstrokeopacity ( void )
public void getstrokewidth ( void )
public void gettextdecoration ( void )
public void gettextencoding ( void )
public void line ( float $sx , float $sy , float $ex , float $ey )
public void point ( float $x , float $y )
public void polygon ( array $coordinates )
public void polyline ( array $coordinate_array )
public void rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )
public void rotate ( float $degrees )
public void roundrectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )
public void scale ( float $x , float $y )
public void setfillcolor ( string $color )
public void setfillopacity ( float $fill_opacity )
public void setfont ( string $font )
public void setfontsize ( float $pointsize )
public void setfontstyle ( string $style )
public void setfontweight ( int $weight )
public void setstrokecolor ( GmagickPixel $color )
public void setstrokeopacity ( float $stroke_opacity )
public void setstrokewidth ( float $width )
public void settextdecoration ( int $decoration )
public void settextencoding ( string $encoding )
}

Table of Contents

  • GmagickDraw::annotate — Draws text on the image
  • GmagickDraw::arc — Draws an arc
  • GmagickDraw::bezier — Draws a bezier curve
  • GmagickDraw::ellipse — Draws an ellipse on the image
  • GmagickDraw::getfillcolor — Returns the fill color
  • GmagickDraw::getfillopacity — Returns the opacity used when drawing
  • GmagickDraw::getfont — Returns the font
  • GmagickDraw::getfontsize — Returns the font pointsize
  • GmagickDraw::getfontstyle — Returns the font style
  • GmagickDraw::getfontweight — Returns the font weight
  • GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines
  • GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines
  • GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines
  • GmagickDraw::gettextdecoration — Returns the text decoration
  • GmagickDraw::gettextencoding — Returns the code set used for text annotations
  • GmagickDraw::line — The line purpose
  • GmagickDraw::point — Draws a point
  • GmagickDraw::polygon — Draws a polygon
  • GmagickDraw::polyline — Draws a polyline
  • GmagickDraw::rectangle — Draws a rectangle
  • GmagickDraw::rotate — Applies the specified rotation to the current coordinate space
  • GmagickDraw::roundrectangle — Draws a rounded rectangle
  • GmagickDraw::scale — Adjusts the scaling factor
  • GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects.
  • GmagickDraw::setfillopacity — The setfillopacity purpose
  • GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text.
  • GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text.
  • GmagickDraw::setfontstyle — Sets the font style to use when annotating with text
  • GmagickDraw::setfontweight — Sets the font weight
  • GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines.
  • GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines.
  • GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines.
  • GmagickDraw::settextdecoration — Specifies a decoration
  • GmagickDraw::settextencoding — Specifies specifies the text code set
Gmagick::writeimage
GmagickDraw::annotate
Gmagick


The GmagickPixel class

Introduction

Description of the class.

Class synopsis

GmagickPixel
GmagickPixel {
/* Methods */
__construct ([ string $color ] )
public void getcolor ([ bool $as_array [, bool $normalize_array ]] )
public void getcolorcount ([ bool $as_array [, bool $normalize_array ]] )
public void getcolorvalue ( int $color )
public void setcolor ( string $color )
public void setcolorvalue ( int $color , float $value )
}

Table of Contents

  • GmagickPixel::__construct — The GmagickPixel constructor
  • GmagickPixel::getcolor — Returns the color
  • GmagickPixel::getcolorcount — Returns the color count associated with this color
  • GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel
  • GmagickPixel::setcolor — Sets the color
  • GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels
GmagickDraw::settextencoding
GmagickPixel::__construct
Gmagick


The HaruAnnotation class

Introduction

Haru PDF Annotation Class.

Class synopsis

HaruAnnotation
HaruAnnotation {
/* Methods */
bool setBorderStyle ( float $width , int $dash_on , int $dash_off )
bool setHighlightMode ( int $mode )
bool setIcon ( int $icon )
bool setOpened ( bool $opened )
}

Predefined Constants

Type | Name | Description
int | HaruAnnotation::NO_HIGHLIGHT |
int | HaruAnnotation::INVERT_BOX |
int | HaruAnnotation::INVERT_BORDER |
int | HaruAnnotation::DOWN_APPEARANCE |
int | HaruAnnotation::ICON_COMMENT |
int | HaruAnnotation::ICON_KEY |
int | HaruAnnotation::ICON_NOTE |
int | HaruAnnotation::ICON_HELP |
int | HaruAnnotation::ICON_NEW_PARAGRAPH |
int | HaruAnnotation::ICON_PARAGRAPH |
int | HaruAnnotation::ICON_INSERT |

Table of Contents

  • HaruAnnotation::setBorderStyle — Set the border style of the annotation
  • HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation
  • HaruAnnotation::setIcon — Set the icon style of the annotation
  • HaruAnnotation::setOpened — Set the initial state of the annotation
HaruOutline::setOpened
HaruAnnotation::setBorderStyle
haru


The HaruDestination class

Introduction

Haru PDF Destination Class.

Class synopsis

HaruDestination
HaruDestination {
/* Methods */
bool setFit ( void )
bool setFitB ( void )
bool setFitBH ( float $top )
bool setFitBV ( float $left )
bool setFitH ( float $top )
bool setFitR ( float $left , float $bottom , float $right , float $top )
bool setFitV ( float $left )
bool setXYZ ( float $left , float $top , float $zoom )
}

Table of Contents

  • HaruDestination::setFit — Set the appearance of the page to fit the window
  • HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window
  • HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box
  • HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box
  • HaruDestination::setFitH — Set the appearance of the page to fit the window width
  • HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle
  • HaruDestination::setFitV — Set the appearance of the page to fit the window height
  • HaruDestination::setXYZ — Set the appearance of the page
HaruAnnotation::setOpened
HaruDestination::setFit
haru


The HaruDoc class

Introduction

Haru PDF Document Class.

Class synopsis

HaruDoc
HaruDoc {
/* Methods */
object addPage ( void )
bool addPageLabel ( int $first_page , int $style , int $first_num [, string $prefix = "" ] )
void __construct ( void )
object createOutline ( string $title [, object $parent_outline [, object $encoder ]] )
object getCurrentEncoder ( void )
object getCurrentPage ( void )
object getEncoder ( string $encoding )
object getFont ( string $fontname [, string $encoding ] )
string getInfoAttr ( int $type )
int getPageLayout ( void )
int getPageMode ( void )
int getStreamSize ( void )
object insertPage ( object $page )
object loadJPEG ( string $filename )
object loadPNG ( string $filename [, bool $deferred = false ] )
object loadRaw ( string $filename , int $width , int $height , int $color_space )
string loadTTC ( string $fontfile , int $index [, bool $embed = false ] )
string loadTTF ( string $fontfile [, bool $embed = false ] )
string loadType1 ( string $afmfile [, string $pfmfile ] )
bool output ( void )
string readFromStream ( int $bytes )
bool resetError ( void )
bool resetStream ( void )
bool save ( string $file )
bool saveToStream ( void )
bool setCompressionMode ( int $mode )
bool setCurrentEncoder ( string $encoding )
bool setEncryptionMode ( int $mode [, int $key_len = 5 ] )
bool setInfoAttr ( int $type , string $info )
bool setInfoDateAttr ( int $type , int $year , int $month , int $day , int $hour , int $min , int $sec , string $ind , int $off_hour , int $off_min )
bool setOpenAction ( object $destination )
bool setPageLayout ( int $layout )
bool setPageMode ( int $mode )
bool setPagesConfiguration ( int $page_per_pages )
bool setPassword ( string $owner_password , string $user_password )
bool setPermission ( int $permission )
bool useCNSEncodings ( void )
bool useCNSFonts ( void )
bool useCNTEncodings ( void )
bool useCNTFonts ( void )
bool useJPEncodings ( void )
bool useJPFonts ( void )
bool useKREncodings ( void )
bool useKRFonts ( void )
}

Predefined Constants

Type | Name | Description
int | HaruDoc::CS_DEVICE_GRAY |
int | HaruDoc::CS_DEVICE_RGB |
int | HaruDoc::CS_DEVICE_CMYK |
int | HaruDoc::CS_CAL_GRAY |
int | HaruDoc::CS_CAL_RGB |
int | HaruDoc::CS_LAB |
int | HaruDoc::CS_ICC_BASED |
int | HaruDoc::CS_SEPARATION |
int | HaruDoc::CS_DEVICE_N |
int | HaruDoc::CS_INDEXED |
int | HaruDoc::CS_PATTERN |
int | HaruDoc::ENABLE_READ |
int | HaruDoc::ENABLE_PRINT |
int | HaruDoc::ENABLE_EDIT_ALL |
int | HaruDoc::ENABLE_COPY |
int | HaruDoc::ENABLE_EDIT |
int | HaruDoc::ENCRYPT_R2 |
int | HaruDoc::ENCRYPT_R3 |
int | HaruDoc::INFO_AUTHOR |
int | HaruDoc::INFO_CREATOR |
int | HaruDoc::INFO_TITLE |
int | HaruDoc::INFO_SUBJECT |
int | HaruDoc::INFO_KEYWORDS |
int | HaruDoc::INFO_CREATION_DATE |
int | HaruDoc::INFO_MOD_DATE |
int | HaruDoc::COMP_NONE |
int | HaruDoc::COMP_TEXT |
int | HaruDoc::COMP_IMAGE |
int | HaruDoc::COMP_METADATA |
int | HaruDoc::COMP_ALL |
int | HaruDoc::PAGE_LAYOUT_SINGLE |
int | HaruDoc::PAGE_LAYOUT_ONE_COLUMN |
int | HaruDoc::PAGE_LAYOUT_TWO_COLUMN_LEFT |
int | HaruDoc::PAGE_LAYOUT_TWO_COLUMN_RIGHT |
int | HaruDoc::PAGE_MODE_USE_NONE |
int | HaruDoc::PAGE_MODE_USE_OUTLINE |
int | HaruDoc::PAGE_MODE_USE_THUMBS |
int | HaruDoc::PAGE_MODE_FULL_SCREEN |

Table of Contents

  • HaruDoc::addPage — Add new page to the document
  • HaruDoc::addPageLabel — Set the numbering style for the specified range of pages
  • HaruDoc::__construct — Construct new HaruDoc instance
  • HaruDoc::createOutline — Create a HaruOutline instance
  • HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document
  • HaruDoc::getCurrentPage — Return current page of the document
  • HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding
  • HaruDoc::getFont — Get HaruFont instance
  • HaruDoc::getInfoAttr — Get current value of the specified document attribute
  • HaruDoc::getPageLayout — Get current page layout
  • HaruDoc::getPageMode — Get current page mode
  • HaruDoc::getStreamSize — Get the size of the temporary stream
  • HaruDoc::insertPage — Insert new page just before the specified page
  • HaruDoc::loadJPEG — Load a JPEG image
  • HaruDoc::loadPNG — Load PNG image and return HaruImage instance
  • HaruDoc::loadRaw — Load a RAW image
  • HaruDoc::loadTTC — Load the font with the specified index from TTC file
  • HaruDoc::loadTTF — Load TTF font file
  • HaruDoc::loadType1 — Load Type1 font
  • HaruDoc::output — Write the document data to the output buffer
  • HaruDoc::readFromStream — Read data from the temporary stream
  • HaruDoc::resetError — Reset error state of the document handle
  • HaruDoc::resetStream — Rewind the temporary stream
  • HaruDoc::save — Save the document into the specified file
  • HaruDoc::saveToStream — Save the document into a temporary stream
  • HaruDoc::setCompressionMode — Set compression mode for the document
  • HaruDoc::setCurrentEncoder — Set the current encoder for the document
  • HaruDoc::setEncryptionMode — Set encryption mode for the document
  • HaruDoc::setInfoAttr — Set the info attribute of the document
  • HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document
  • HaruDoc::setOpenAction — Define which page is shown when the document is opened
  • HaruDoc::setPageLayout — Set how pages should be displayed
  • HaruDoc::setPageMode — Set how the document should be displayed
  • HaruDoc::setPagesConfiguration — Set the number of pages per set of pages
  • HaruDoc::setPassword — Set owner and user passwords for the document
  • HaruDoc::setPermission — Set permissions for the document
  • HaruDoc::useCNSEncodings — Enable Chinese simplified encodings
  • HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts
  • HaruDoc::useCNTEncodings — Enable Chinese traditional encodings
  • HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts
  • HaruDoc::useJPEncodings — Enable Japanese encodings
  • HaruDoc::useJPFonts — Enable builtin Japanese fonts
  • HaruDoc::useKREncodings — Enable Korean encodings
  • HaruDoc::useKRFonts — Enable builtin Korean fonts
HaruException
HaruDoc::addPage
haru


The HaruEncoder class

Introduction

Haru PDF Encoder Class.

Class synopsis

HaruEncoder
HaruEncoder {
/* Methods */
int getByteType ( string $text , int $index )
int getType ( void )
int getUnicode ( int $character )
int getWritingMode ( void )
}

Predefined Constants

Type | Name | Description
int | HaruEncoder::TYPE_SINGLE_BYTE |
int | HaruEncoder::TYPE_DOUBLE_BYTE |
int | HaruEncoder::TYPE_UNINITIALIZED |
int | HaruEncoder::UNKNOWN |
int | HaruEncoder::WMODE_HORIZONTAL |
int | HaruEncoder::WMODE_VERTICAL |
int | HaruEncoder::BYTE_TYPE_SINGLE |
int | HaruEncoder::BYTE_TYPE_LEAD |
int | HaruEncoder::BYTE_TYPE_TRAIL |
int | HaruEncoder::BYTE_TYPE_UNKNOWN |

Table of Contents

  • HaruEncoder::getByteType — Get the type of the byte in the text
  • HaruEncoder::getType — Get the type of the encoder
  • HaruEncoder::getUnicode — Convert the specified character to unicode
  • HaruEncoder::getWritingMode — Get the writing mode of the encoder
HaruImage::setMaskImage
HaruEncoder::getByteType
haru


The HaruException class

Introduction

Haru PDF Exception Class.

Class synopsis

HaruException
HaruException extends Exception {
/* Inherits */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public int Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}
Builtin Encodings
HaruDoc
haru


The HaruFont class

Introduction

Haru PDF Font Class.

Class synopsis

HaruFont
HaruFont {
/* Methods */
int getAscent ( void )
int getCapHeight ( void )
int getDescent ( void )
string getEncodingName ( void )
string getFontName ( void )
array getTextWidth ( string $text )
int getUnicodeWidth ( int $character )
int getXHeight ( void )
int measureText ( string $text , float $width , float $font_size , float $char_space , float $word_space [, bool $word_wrap = false ] )
}

Table of Contents

  • HaruFont::getAscent — Get the vertical ascent of the font
  • HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters
  • HaruFont::getDescent — Get the vertical descent of the font
  • HaruFont::getEncodingName — Get the name of the encoding
  • HaruFont::getFontName — Get the name of the font
  • HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces
  • HaruFont::getUnicodeWidth — Get the width of the character in the font
  • HaruFont::getXHeight — Get the distance from the baseline of lowercase letters
  • HaruFont::measureText — Calculate the number of characters which can be included within the specified width
HaruPage::textRect
HaruFont::getAscent
haru


The HaruImage class

Introduction

Haru PDF Image Class.

Class synopsis

HaruImage
HaruImage {
/* Methods */
int getBitsPerComponent ( void )
string getColorSpace ( void )
int getHeight ( void )
array getSize ( void )
int getWidth ( void )
bool setColorMask ( int $rmin , int $rmax , int $gmin , int $gmax , int $bmin , int $bmax )
bool setMaskImage ( object $mask_image )
}

Table of Contents

  • HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image
  • HaruImage::getColorSpace — Get the name of the color space
  • HaruImage::getHeight — Get the height of the image
  • HaruImage::getSize — Get size of the image
  • HaruImage::getWidth — Get the width of the image
  • HaruImage::setColorMask — Set the color mask of the image
  • HaruImage::setMaskImage — Set the image mask
HaruFont::measureText
HaruImage::getBitsPerComponent
haru


The HaruOutline class

Introduction

Haru PDF Outline Class.

Class synopsis

HaruOutline
HaruOutline {
/* Methods */
bool setDestination ( object $destination )
bool setOpened ( bool $opened )
}

Table of Contents

  • HaruOutline::setDestination — Set the destination for the outline
  • HaruOutline::setOpened — Set the initial state of the outline
HaruEncoder::getWritingMode
HaruOutline::setDestination
haru


The HaruPage class

Introduction

Haru PDF Page Class.

Class synopsis

HaruPage
HaruPage {
/* Methods */
bool arc ( float $x , float $y , float $ray , float $ang1 , float $ang2 )
bool beginText ( void )
bool circle ( float $x , float $y , float $ray )
bool closePath ( void )
bool concat ( float $a , float $b , float $c , float $d , float $x , float $y )
object createDestination ( void )
object createLinkAnnotation ( array $rectangle , object $destination )
object createTextAnnotation ( array $rectangle , string $text [, object $encoder ] )
object createURLAnnotation ( array $rectangle , string $url )
bool curveTo2 ( float $x2 , float $y2 , float $x3 , float $y3 )
bool curveTo3 ( float $x1 , float $y1 , float $x3 , float $y3 )
bool curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )
bool drawImage ( object $image , float $x , float $y , float $width , float $height )
bool ellipse ( float $x , float $y , float $xray , float $yray )
bool endPath ( void )
bool endText ( void )
bool eofill ( void )
bool eoFillStroke ([ bool $close_path = false ] )
bool fill ( void )
bool fillStroke ([ bool $close_path = false ] )
float getCharSpace ( void )
array getCMYKFill ( void )
array getCMYKStroke ( void )
object getCurrentFont ( void )
float getCurrentFontSize ( void )
array getCurrentPos ( void )
array getCurrentTextPos ( void )
array getDash ( void )
int getFillingColorSpace ( void )
float getFlatness ( void )
int getGMode ( void )
float getGrayFill ( void )
float getGrayStroke ( void )
float getHeight ( void )
float getHorizontalScaling ( void )
int getLineCap ( void )
int getLineJoin ( void )
float getLineWidth ( void )
float getMiterLimit ( void )
array getRGBFill ( void )
array getRGBStroke ( void )
int getStrokingColorSpace ( void )
float getTextLeading ( void )
array getTextMatrix ( void )
int getTextRenderingMode ( void )
float getTextRise ( void )
float getTextWidth ( string $text )
array getTransMatrix ( void )
float getWidth ( void )
float getWordSpace ( void )
bool lineTo ( float $x , float $y )
int measureText ( string $text , float $width [, bool $wordwrap = false ] )
bool moveTextPos ( float $x , float $y [, bool $set_leading = false ] )
bool moveTo ( float $x , float $y )
bool moveToNextLine ( void )
bool rectangle ( float $x , float $y , float $width , float $height )
bool setCharSpace ( float $char_space )
bool setCMYKFill ( float $c , float $m , float $y , float $k )
bool setCMYKStroke ( float $c , float $m , float $y , float $k )
bool setDash ( array $pattern , int $phase )
bool setFlatness ( float $flatness )
bool setFontAndSize ( object $font , float $size )
bool setGrayFill ( float $value )
bool setGrayStroke ( float $value )
bool setHeight ( float $height )
bool setHorizontalScaling ( float $scaling )
bool setLineCap ( int $cap )
bool setLineJoin ( int $join )
bool setLineWidth ( float $width )
bool setMiterLimit ( float $limit )
bool setRGBFill ( float $r , float $g , float $b )
bool setRGBStroke ( float $r , float $g , float $b )
bool setRotate ( int $angle )
bool setSize ( int $size , int $direction )
bool setSlideShow ( int $type , float $disp_time , float $trans_time )
bool setTextLeading ( float $text_leading )
bool setTextMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )
bool setTextRenderingMode ( int $mode )
bool setTextRise ( float $rise )
bool setWidth ( float $width )
bool setWordSpace ( float $word_space )
bool showText ( string $text )
bool showTextNextLine ( string $text [, float $word_space [, float $char_space ]] )
bool stroke ([ bool $close_path = false ] )
bool textOut ( float $x , float $y , string $text )
bool textRect ( float $left , float $top , float $right , float $bottom , string $text [, int $align = HaruPage::TALIGN_LEFT ] )
}

Predefined Constants

Type | Name | Description
int | HaruPage::GMODE_PAGE_DESCRIPTION |
int | HaruPage::GMODE_TEXT_OBJECT |
int | HaruPage::GMODE_PATH_OBJECT |
int | HaruPage::GMODE_CLIPPING_PATH |
int | HaruPage::GMODE_SHADING |
int | HaruPage::GMODE_INLINE_IMAGE |
int | HaruPage::GMODE_EXTERNAL_OBJECT |
int | HaruPage::BUTT_END |
int | HaruPage::ROUND_END |
int | HaruPage::PROJECTING_SCUARE_END |
int | HaruPage::MITER_JOIN |
int | HaruPage::ROUND_JOIN |
int | HaruPage::BEVEL_JOIN |
int | HaruPage::FILL |
int | HaruPage::STROKE |
int | HaruPage::FILL_THEN_STROKE |
int | HaruPage::INVISIBLE |
int | HaruPage::FILL_CLIPPING |
int | HaruPage::STROKE_CLIPPING |
int | HaruPage::FILL_STROKE_CLIPPING |
int | HaruPage::CLIPPING |
int | HaruPage::TALIGN_LEFT |
int | HaruPage::TALIGN_RIGHT |
int | HaruPage::TALIGN_CENTER |
int | HaruPage::TALIGN_JUSTIFY |
int | HaruPage::SIZE_LETTER |
int | HaruPage::SIZE_LEGAL |
int | HaruPage::SIZE_A3 |
int | HaruPage::SIZE_A4 |
int | HaruPage::SIZE_A5 |
int | HaruPage::SIZE_B4 |
int | HaruPage::SIZE_B5 |
int | HaruPage::SIZE_EXECUTIVE |
int | HaruPage::SIZE_US4x6 |
int | HaruPage::SIZE_US4x8 |
int | HaruPage::SIZE_US5x7 |
int | HaruPage::SIZE_COMM10 |
int | HaruPage::PORTRAIT |
int | HaruPage::LANDSCAPE |
int | HaruPage::TS_WIPE_LIGHT |
int | HaruPage::TS_WIPE_UP |
int | HaruPage::TS_WIPE_LEFT |
int | HaruPage::TS_WIPE_DOWN |
int | HaruPage::TS_BARN_DOORS_HORIZONTAL_OUT |
int | HaruPage::TS_BARN_DOORS_HORIZONTAL_IN |
int | HaruPage::TS_BARN_DOORS_VERTICAL_OUT |
int | HaruPage::TS_BARN_DOORS_VERTICAL_IN |
int | HaruPage::TS_BOX_OUT |
int | HaruPage::TS_BOX_IN |
int | HaruPage::TS_BLINDS_HORIZONTAL |
int | HaruPage::TS_BLINDS_VERTICAL |
int | HaruPage::TS_DISSOLVE |
int | HaruPage::TS_GLITTER_RIGHT |
int | HaruPage::TS_GLITTER_DOWN |
int | HaruPage::TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT |
int | HaruPage::TS_REPLACE |
int | HaruPage::NUM_STYLE_DECIMAL |
int | HaruPage::NUM_STYLE_UPPER_ROMAN |
int | HaruPage::NUM_STYLE_LOWER_ROMAN |
int | HaruPage::NUM_STYLE_UPPER_LETTERS |
int | HaruPage::NUM_STYLE_LOWER_LETTERS |

Table of Contents

  • HaruPage::arc — Append an arc to the current path
  • HaruPage::beginText — Begin a text object and set the current text position to (0,0)
  • HaruPage::circle — Append a circle to the current path
  • HaruPage::closePath — Append a straight line from the current point to the start point of the path
  • HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix
  • HaruPage::createDestination — Create new HaruDestination instance
  • HaruPage::createLinkAnnotation — Create new HaruAnnotation instance
  • HaruPage::createTextAnnotation — Create new HaruAnnotation instance
  • HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance
  • HaruPage::curveTo2 — Append a Bezier curve to the current path
  • HaruPage::curveTo3 — Append a Bezier curve to the current path
  • HaruPage::curveTo — Append a Bezier curve to the current path
  • HaruPage::drawImage — Show image at the page
  • HaruPage::ellipse — Append an ellipse to the current path
  • HaruPage::endPath — End current path object without filling and painting operations
  • HaruPage::endText — End current text object
  • HaruPage::eofill — Fill current path using even-odd rule
  • HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path
  • HaruPage::fill — Fill current path using nonzero winding number rule
  • HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path
  • HaruPage::getCharSpace — Get the current value of character spacing
  • HaruPage::getCMYKFill — Get the current filling color
  • HaruPage::getCMYKStroke — Get the current stroking color
  • HaruPage::getCurrentFont — Get the currently used font
  • HaruPage::getCurrentFontSize — Get the current font size
  • HaruPage::getCurrentPos — Get the current position for path painting
  • HaruPage::getCurrentTextPos — Get the current position for text printing
  • HaruPage::getDash — Get the current dash pattern
  • HaruPage::getFillingColorSpace — Get the current filling color space
  • HaruPage::getFlatness — Get the flatness of the page
  • HaruPage::getGMode — Get the current graphics mode
  • HaruPage::getGrayFill — Get the current filling color
  • HaruPage::getGrayStroke — Get the current stroking color
  • HaruPage::getHeight — Get the height of the page
  • HaruPage::getHorizontalScaling — Get the current value of horizontal scaling
  • HaruPage::getLineCap — Get the current line cap style
  • HaruPage::getLineJoin — Get the current line join style
  • HaruPage::getLineWidth — Get the current line width
  • HaruPage::getMiterLimit — Get the value of miter limit
  • HaruPage::getRGBFill — Get the current filling color
  • HaruPage::getRGBStroke — Get the current stroking color
  • HaruPage::getStrokingColorSpace — Get the current stroking color space
  • HaruPage::getTextLeading — Get the current value of line spacing
  • HaruPage::getTextMatrix — Get the current text transformation matrix of the page
  • HaruPage::getTextRenderingMode — Get the current text rendering mode
  • HaruPage::getTextRise — Get the current value of text rising
  • HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing
  • HaruPage::getTransMatrix — Get the current transformation matrix of the page
  • HaruPage::getWidth — Get the width of the page
  • HaruPage::getWordSpace — Get the current value of word spacing
  • HaruPage::lineTo — Draw a line from the current point to the specified point
  • HaruPage::measureText — Calculate the number of characters which can be included within the specified width
  • HaruPage::moveTextPos — Move text position to the specified offset
  • HaruPage::moveTo — Set starting point for new drawing path
  • HaruPage::moveToNextLine — Move text position to the start of the next line
  • HaruPage::rectangle — Append a rectangle to the current path
  • HaruPage::setCharSpace — Set character spacing for the page
  • HaruPage::setCMYKFill — Set filling color for the page
  • HaruPage::setCMYKStroke — Set stroking color for the page
  • HaruPage::setDash — Set the dash pattern for the page
  • HaruPage::setFlatness — Set flatness for the page
  • HaruPage::setFontAndSize — Set font and fontsize for the page
  • HaruPage::setGrayFill — Set filling color for the page
  • HaruPage::setGrayStroke — Sets stroking color for the page
  • HaruPage::setHeight — Set height of the page
  • HaruPage::setHorizontalScaling — Set horizontal scaling for the page
  • HaruPage::setLineCap — Set the shape to be used at the ends of lines
  • HaruPage::setLineJoin — Set line join style for the page
  • HaruPage::setLineWidth — Set line width for the page
  • HaruPage::setMiterLimit — Set the current value of the miter limit of the page
  • HaruPage::setRGBFill — Set filling color for the page
  • HaruPage::setRGBStroke — Set stroking color for the page
  • HaruPage::setRotate — Set rotation angle of the page
  • HaruPage::setSize — Set size and direction of the page
  • HaruPage::setSlideShow — Set transition style for the page
  • HaruPage::setTextLeading — Set text leading (line spacing) for the page
  • HaruPage::setTextMatrix — Set the current text transformation matrix of the page
  • HaruPage::setTextRenderingMode — Set text rendering mode for the page
  • HaruPage::setTextRise — Set the current value of text rising
  • HaruPage::setWidth — Set width of the page
  • HaruPage::setWordSpace — Set word spacing for the page
  • HaruPage::showText — Print text at the current position of the page
  • HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text
  • HaruPage::stroke — Paint current path
  • HaruPage::textOut — Print the text on the specified position
  • HaruPage::textRect — Print the text inside the specified region
HaruDoc::useKRFonts
HaruPage::arc
haru


The KTaglib_ID3v2_AttachedPictureFrame class

Introduction

Represents an ID3v2 frame that can hold a picture.

Class synopsis

KTaglib_ID3v2_AttachedPictureFrame
extends KTagLib_ID3v2_Frame {
}

Table of Contents

  • KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame
  • KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture
  • KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image
  • KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file
  • KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture
  • KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image
  • KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image
KTaglib_ID3v2_Frame::__toString
KTaglib_ID3v2_AttachedPictureFrame::getDescription
KTaglib


The KTagLib_ID3v2_Frame class

Introduction

The base class for ID3v2 frames. ID3v2 tags are separated in various specialized frames. Some frames can exists multiple times.

Class synopsis

KTagLib_ID3v2_Frame
extends KTagLib_Tag {
}

Table of Contents

  • KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes
  • KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame
KTaglib_ID3v2_Tag::getFrameList
KTaglib_ID3v2_Frame::getSize
KTaglib


The KTagLib_ID3v2_Tag class

Introduction

Represents and ID3v2 tag. It provides a list of ID3v2 frames and can be used to add and remove additional frames.

Class synopsis

KTagLib_ID3v2_Tag
extends KTagLib_Tag {
}

Table of Contents

  • KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag
  • KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag
KTaglib_Tag::isEmpty
KTaglib_ID3v2_Tag::addFrame
KTaglib


The Imagick class

Class synopsis

Imagick
Imagick implements Iterator , Traversable {
bool adaptiveBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool adaptiveResizeImage ( int $columns , int $rows [, bool $bestfit = false ] )
bool adaptiveSharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool adaptiveThresholdImage ( int $width , int $height , int $offset )
bool addImage ( Imagick $source )
bool addNoiseImage ( int $noise_type [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool affineTransformImage ( ImagickDraw $matrix )
bool animateImages ( string $x_server )
bool annotateImage ( ImagickDraw $draw_settings , float $x , float $y , float $angle , string $text )
Imagick appendImages ( bool $stack )
Imagick averageImages ( void )
bool blackThresholdImage ( mixed $threshold )
bool blurImage ( float $radius , float $sigma [, int $channel ] )
bool borderImage ( mixed $bordercolor , int $width , int $height )
bool charcoalImage ( float $radius , float $sigma )
bool chopImage ( int $width , int $height , int $x , int $y )
bool clear ( void )
bool clipImage ( void )
bool clipPathImage ( string $pathname , bool $inside )
Imagick clone ( void )
bool clutImage ( Imagick $lookup_table [, float $channel = Imagick::CHANNEL_DEFAULT ] )
Imagick coalesceImages ( void )
bool colorFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y )
bool colorizeImage ( mixed $colorize , mixed $opacity )
Imagick combineImages ( int $channelType )
bool commentImage ( string $comment )
array compareImageChannels ( Imagick $image , int $channelType , int $metricType )
Imagick compareImageLayers ( int $method )
array compareImages ( Imagick $compare , int $metric )
bool compositeImage ( Imagick $composite_object , int $composite , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )
Imagick __construct ([ mixed $files ] )
bool contrastImage ( bool $sharpen )
bool contrastStretchImage ( float $black_point , float $white_point [, int $channel = Imagick::CHANNEL_ALL ] )
bool convolveImage ( array $kernel [, int $channel = Imagick::CHANNEL_ALL ] )
bool cropImage ( int $width , int $height , int $x , int $y )
bool cropThumbnailImage ( int $width , int $height )
Imagick current ( void )
bool cycleColormapImage ( int $displace )
bool decipherImage ( string $passphrase )
bool deconstructImages ( void )
public void deskewImage ( float $threshold )
bool despeckleImage ( void )
bool destroy ( void )
bool displayImage ( string $servername )
bool displayImages ( string $servername )
bool distortImage ( int $method , array $arguments , bool $bestfit )
bool drawImage ( ImagickDraw $draw )
bool edgeImage ( float $radius )
bool embossImage ( float $radius , float $sigma )
bool encipherImage ( string $passphrase )
bool enhanceImage ( void )
bool equalizeImage ( void )
bool evaluateImage ( int $op , float $constant [, int $channel = Imagick::CHANNEL_ALL ] )
public array exportImagePixels ( int $x , int $y , int $width , int $height , string $map , int $STORAGE )
bool extentImage ( int $width , int $height , int $x , int $y )
Imagick flattenImages ( void )
bool flipImage ( void )
bool floodFillPaintImage ( mixed $fill , float $fuzz , mixed $target , int $x , int $y , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool flopImage ( void )
bool frameImage ( mixed $matte_color , int $width , int $height , int $inner_bevel , int $outer_bevel )
public boolean functionImage ( integer $function , array $arguments )
Imagick fxImage ( string $expression [, int $channel = Imagick::CHANNEL_ALL ] )
bool gammaImage ( float $gamma [, int $channel = Imagick::CHANNEL_ALL ] )
bool gaussianBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )
int getCompression ( void )
int getCompressionQuality ( void )
string getCopyright ( void )
string getFilename ( void )
string getFont ( void )
string getFormat ( void )
bool getGravity ( void )
string getHomeURL ( void )
Imagick getImage ( void )
int getImageAlphaChannel ( void )
ImagickPixel getImageBackgroundColor ( void )
string getImageBlob ( void )
array getImageBluePrimary ( float $x , float $y )
ImagickPixel getImageBorderColor ( void )
int getImageChannelDepth ( int $channel )
float getImageChannelDistortion ( Imagick $reference , int $channel , int $metric )
double getImageChannelDistortions ( Imagick $reference , int $metric , int $channel )
array getImageChannelExtrema ( int $channel )
public array getImageChannelKurtosis ([ int $channel = Imagick::CHANNEL_DEFAULT ] )
array getImageChannelMean ( int $channel )
bool getImageChannelRange ( int $channel )
array getImageChannelStatistics ( void )
Imagick getImageClipMask ( void )
ImagickPixel getImageColormapColor ( int $index )
int getImageColors ( void )
int getImageColorspace ( void )
int getImageCompose ( void )
int getImageCompression ( void )
int getCompressionQuality ( void )
int getImageDelay ( void )
int getImageDepth ( void )
int getImageDispose ( void )
float getImageDistortion ( MagickWand $reference , int $metric )
array getImageExtrema ( void )
string getImageFilename ( void )
string getImageFormat ( void )
float getImageGamma ( void )
array getImageGeometry ( void )
bool getImageGravity ( void )
array getImageGreenPrimary ( void )
int getImageHeight ( void )
array getImageHistogram ( void )
int getImageIndex ( void )
int getImageInterlaceScheme ( void )
int getImageInterpolateMethod ( void )
int getImageIterations ( void )
int getImageLength ( void )
string getImageMagickLicense ( void )
int getImageMatte ( void )
ImagickPixel getImageMatteColor ( void )
int getImageOrientation ( void )
array getImagePage ( void )
ImagickPixel getImagePixelColor ( int $x , int $y )
string getImageProfile ( string $name )
array getImageProfiles ([ string $pattern = "*" [, bool $only_names = true ]] )
array getImageProperties ([ string $pattern = "*" [, bool $only_names = true ]] )
string getImageProperty ( string $name )
array getImageRedPrimary ( void )
Imagick getImageRegion ( int $width , int $height , int $x , int $y )
int getImageRenderingIntent ( void )
array getImageResolution ( void )
string getImagesBlob ( void )
int getImageScene ( void )
string getImageSignature ( void )
int getImageSize ( void )
int getImageTicksPerSecond ( void )
float getImageTotalInkDensity ( void )
int getImageType ( void )
int getImageUnits ( void )
int getImageVirtualPixelMethod ( void )
array getImageWhitePoint ( void )
int getImageWidth ( void )
int getInterlaceScheme ( void )
int getIteratorIndex ( void )
int getNumberImages ( void )
string getOption ( string $key )
string getPackageName ( void )
array getPage ( void )
ImagickPixelIterator getPixelIterator ( void )
ImagickPixelIterator getPixelRegionIterator ( int $x , int $y , int $columns , int $rows )
string getPointSize ( void )
array getQuantumDepth ( void )
array getQuantumRange ( void )
string getReleaseDate ( void )
int getResource ( int $type )
int getResourceLimit ( int $type )
array getSamplingFactors ( void )
array getSize ( void )
int getSizeOffset ( void )
array getVersion ( void )
public boolean haldClutImage ( Imagick $clut [, int $channel ] )
bool hasNextImage ( void )
bool hasPreviousImage ( void )
array identifyImage ([ bool $appendRawOutput = false ] )
bool implodeImage ( float $radius )
public bool importImagePixels ( int $x , int $y , int $width , int $height , string $map , int $storage , array $pixels )
bool labelImage ( string $label )
bool levelImage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Imagick::CHANNEL_ALL ] )
bool linearStretchImage ( float $blackPoint , float $whitePoint )
bool liquidRescaleImage ( int $width , int $height , float $delta_x , float $rigidity )
bool magnifyImage ( void )
bool mapImage ( Imagick $map , bool $dither )
bool matteFloodfillImage ( float $alpha , float $fuzz , mixed $bordercolor , int $x , int $y )
bool medianFilterImage ( float $radius )
bool mergeImageLayers ( int $layer_method )
bool minifyImage ( void )
bool modulateImage ( float $brightness , float $saturation , float $hue )
Imagick montageImage ( ImagickDraw $draw , string $tile_geometry , string $thumbnail_geometry , int $mode , string $frame )
Imagick morphImages ( int $number_frames )
Imagick mosaicImages ( void )
bool motionBlurImage ( float $radius , float $sigma , float $angle [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool negateImage ( bool $gray [, int $channel = Imagick::CHANNEL_ALL ] )
bool newImage ( int $cols , int $rows , mixed $background [, string $format ] )
bool newPseudoImage ( int $columns , int $rows , string $pseudoString )
bool nextImage ( void )
bool normalizeImage ([ int $channel = Imagick::CHANNEL_ALL ] )
bool oilPaintImage ( float $radius )
bool opaquePaintImage ( mixed $target , mixed $fill , float $fuzz , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool optimizeImageLayers ( void )
bool orderedPosterizeImage ( string $threshold_map [, int $channel = Imagick::CHANNEL_ALL ] )
bool paintFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )
bool paintOpaqueImage ( mixed $target , mixed $fill , float $fuzz [, int $channel = Imagick::CHANNEL_ALL ] )
bool paintTransparentImage ( mixed $target , float $alpha , float $fuzz )
bool pingImage ( string $filename )
bool pingImageBlob ( string $image )
bool pingImageFile ( resource $filehandle [, string $fileName ] )
bool polaroidImage ( ImagickDraw $properties , float $angle )
bool posterizeImage ( int $levels , bool $dither )
bool previewImages ( int $preview )
bool previousImage ( void )
bool profileImage ( string $name , string $profile )
bool quantizeImage ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )
bool quantizeImages ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )
array queryFontMetrics ( ImagickDraw $properties , string $text [, bool $multiline ] )
array queryFonts ([ string $pattern = "*" ] )
array queryFormats ([ string $pattern = "*" ] )
bool radialBlurImage ( float $angle [, int $channel = Imagick::CHANNEL_ALL ] )
bool raiseImage ( int $width , int $height , int $x , int $y , bool $raise )
bool randomThresholdImage ( float $low , float $high [, int $channel = Imagick::CHANNEL_ALL ] )
bool readImage ( string $filename )
bool readImageBlob ( string $image [, string $filename ] )
bool readImageFile ( resource $filehandle [, string $fileName ] )
bool animateImages ( array $matrix )
bool reduceNoiseImage ( float $radius )
public void remapImage ( Imagick $replacement , int $DITHER )
bool removeImage ( void )
string removeImageProfile ( string $name )
bool render ( void )
bool resampleImage ( float $x_resolution , float $y_resolution , int $filter , float $blur )
bool resetImagePage ( string $page )
bool resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )
bool rollImage ( int $x , int $y )
bool rotateImage ( mixed $background , float $degrees )
bool roundCorners ( float $x_rounding , float $y_rounding [, float $stroke_width = 10 [, float $displace = 5 [, float $size_correction = -6 ]]] )
bool sampleImage ( int $columns , int $rows )
bool scaleImage ( int $cols , int $rows [, bool $bestfit = false ] )
public void segmentImage ( int $COLORSPACE , float $cluster_threshold , float $smooth_threshold [, boolean $verbose ] )
bool separateImageChannel ( int $channel )
bool sepiaToneImage ( float $threshold )
bool setBackgroundColor ( mixed $background )
bool setCompression ( int $compression )
bool setCompressionQuality ( int $quality )
bool setFilename ( string $filename )
bool setFirstIterator ( void )
bool setFont ( string $font )
bool setFormat ( string $format )
bool setGravity ( int $gravity )
bool setImage ( Imagick $replace )
bool setImageAlphaChannel ( int $mode )
bool setImageBackgroundColor ( mixed $background )
bool setImageBias ( float $bias )
bool setImageBluePrimary ( float $x , float $y )
bool setImageBorderColor ( mixed $border )
bool setImageChannelDepth ( int $channel , int $depth )
bool setImageClipMask ( Imagick $clip_mask )
bool setImageColormapColor ( int $index , ImagickPixel $color )
bool setImageColorspace ( int $colorspace )
bool setImageCompose ( int $compose )
bool setImageCompression ( int $compression )
bool setImageCompressionQuality ( int $quality )
bool setImageDelay ( int $delay )
bool setImageDepth ( int $depth )
bool setImageDispose ( int $dispose )
bool setImageExtent ( int $columns , int $rows )
bool setImageFilename ( string $filename )
bool setImageFormat ( string $format )
bool setImageGamma ( float $gamma )
bool setImageGravity ( int $gravity )
bool setImageGreenPrimary ( float $x , float $y )
bool setImageIndex ( int $index )
bool setImageInterlaceScheme ( int $interlace_scheme )
bool setImageInterpolateMethod ( int $method )
bool setImageIterations ( int $iterations )
bool setImageMatte ( bool $matte )
bool setImageMatteColor ( mixed $matte )
bool setImageOpacity ( float $opacity )
bool setImageOrientation ( int $orientation )
bool setImagePage ( int $width , int $height , int $x , int $y )
bool setImageProfile ( string $name , string $profile )
bool setImageProperty ( string $name , string $value )
bool setImageRedPrimary ( float $x , float $y )
bool setImageRenderingIntent ( int $rendering_intent )
bool setImageResolution ( float $x_resolution , float $y_resolution )
bool setImageScene ( int $scene )
bool setImageTicksPerSecond ( int $ticks_per-second )
bool setImageType ( int $image_type )
bool setImageUnits ( int $units )
bool setImageVirtualPixelMethod ( int $method )
bool setImageWhitePoint ( float $x , float $y )
bool setInterlaceScheme ( int $interlace_scheme )
bool setIteratorIndex ( int $index )
bool setLastIterator ( void )
bool setOption ( string $key , string $value )
bool setPage ( int $width , int $height , int $x , int $y )
bool setPointSize ( float $point_size )
bool setResolution ( float $x_resolution , float $y_resolution )
bool setResourceLimit ( int $type , int $limit )
bool setSamplingFactors ( array $factors )
bool setSize ( int $columns , int $rows )
bool setSizeOffset ( int $columns , int $rows , int $offset )
bool setType ( int $image_type )
bool shadeImage ( bool $gray , float $azimuth , float $elevation )
bool shadowImage ( float $opacity , float $sigma , int $x , int $y )
bool sharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )
bool shaveImage ( int $columns , int $rows )
bool shearImage ( mixed $background , float $x_shear , float $y_shear )
bool sigmoidalContrastImage ( bool $sharpen , float $alpha , float $beta [, int $channel = Imagick::CHANNEL_ALL ] )
bool sketchImage ( float $radius , float $sigma , float $angle )
bool solarizeImage ( int $threshold )
public boolean sparseColorImage ( int $SPARSE_METHOD , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool spliceImage ( int $width , int $height , int $x , int $y )
bool spreadImage ( float $radius )
Imagick steganoImage ( Imagick $watermark_wand , int $offset )
bool stereoImage ( Imagick $offset_wand )
bool stripImage ( void )
bool swirlImage ( float $degrees )
bool textureImage ( Imagick $texture_wand )
bool thresholdImage ( float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )
bool thumbnailImage ( int $columns , int $rows [, bool $bestfit = false ] )
bool tintImage ( mixed $tint , mixed $opacity )
Imagick transformImage ( string $crop , string $geometry )
bool transparentPaintImage ( mixed $target , float $alpha , float $fuzz , bool $invert )
bool transposeImage ( void )
bool transverseImage ( void )
bool trimImage ( float $fuzz )
bool uniqueImageColors ( void )
bool unsharpMaskImage ( float $radius , float $sigma , float $amount , float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )
bool valid ( void )
bool vignetteImage ( float $blackPoint , float $whitePoint , int $x , int $y )
bool waveImage ( float $amplitude , float $length )
bool whiteThresholdImage ( mixed $threshold )
bool writeImage ([ string $filename ] )
bool writeImageFile ( resource $filehandle )
bool writeImages ( string $filename , bool $adjoin )
bool writeImagesFile ( resource $filehandle )
}

Image methods and global methods

The Imagick class has the ability to hold and operate on multiple images simultaneously. This is achieved through an internal stack. There is always an internal pointer that points at the current image. Some functions operate on all images in the Imagick class, but most operate only on the current image in the internal stack. As a convention, method names can contain the word Image to denote they affect only the current image in the stack.

Class Methods

Because there are so many methods, here is a handy list of methods, somewhat reduced to their general purpose:

Class methods by purpose
Image effects | Get methods | Set methods | Read/write images | Other
Imagick::adaptiveBlurImage | Imagick::getCompression | Imagick::setBackgroundColor | Imagick::__construct | Imagick::clear
Imagick::adaptiveResizeImage | Imagick::getFilename | Imagick::setCompressionQuality | Imagick::addImage | Imagick::clone
Imagick::adaptiveSharpenImage | Imagick::getFormat | Imagick::setCompression | Imagick::appendImages | Imagick::current
Imagick::adaptiveTresholdImage | Imagick::getImageBackgroundColor | Imagick::setFilename | Imagick::getFilename | Imagick::destroy
Imagick::addNoiseImage | Imagick::getImageBlob | Imagick::getImagesBlob | Imagick::setFormat | Imagick::getFormat | Imagick::getCopyright
Imagick::affinetransformimage | Imagick::getImageBluePrimary | Imagick::setImageBackgroundColor | Imagick::getImageFilename | Imagick::getHomeURL
Imagick::annotateImage | Imagick::getImageBorderColor | Imagick::setFirstIterator | Imagick::getImageFormat | Imagick::commentImage
Imagick::averageImages | Imagick::getImageChannelDepth | Imagick::setImageBias | Imagick::getImage | Imagick::getNumberImages
Imagick::blackThresholdImage | Imagick::getImageChannelDistortion | Imagick::setImageBluePrimary | Imagick::setImageFilename | Imagick::getReleaseDate
Imagick::blurImage | Imagick::getImageChannelExtrema | Imagick::setImageBorderColor | Imagick::setImageFormat | Imagick::getVersion
Imagick::borderImage | Imagick::getImageChannelMean | Imagick::setImageChannelDepth | Imagick::readImageFile | Imagick::hasNextImage
Imagick::charcoalImage | Imagick::getImageChannelStatistics | Imagick::setImageColormapColor | Imagick::readImage | Imagick::hasPreviousImage
Imagick::chopImage | Imagick::getImageColormapColor | Imagick::setImageColorSpace | Imagick::writeImages | Imagick::labelImage
Imagick::clipImage | Imagick::getImageColorspace | Imagick::setImageCompose | Imagick::writeImage | Imagick::newImage
Imagick::clipPathImage | Imagick::getImageColors | Imagick::setImageCompression |  | Imagick::newPseudoImage
Imagick::coalesceImages | Imagick::getImageCompose | Imagick::setImageDelay |  | Imagick::nextImage
Imagick::colorFloodFillImage | Imagick::getImageDelay | Imagick::setImageDepth |  | Imagick::pingImageBlob
Imagick::colorizeImage | Imagick::getImageDepth | Imagick::setImageDispose |  | Imagick::pingImageFile
Imagick::combineImages | Imagick::getImageDispose | Imagick::setImageDispose |  | Imagick::pingImage
Imagick::compareImageChannels | Imagick::getImageDistortion | Imagick::setImageExtent |  | Imagick::previousImage
Imagick::compareImageLayers | Imagick::getImageExtrema | Imagick::setImageFilename |  | Imagick::profileImage
Imagick::compositeImage | Imagick::getImageFilename | Imagick::setImageFormat |  | Imagick::queryFormats
Imagick::contrastImage | Imagick::getImageFormat | Imagick::setImageGamma |  | Imagick::removeImageProfile
Imagick::constrastStretchImage | Imagick::getImageGamma | Imagick::setImageGreenPrimary |  | Imagick::removeImage
Imagick::convolveImage | Imagick::getImageGeometry | Imagick::setImageIndex |  | Imagick::setFirstIterator
Imagick::cropImage | Imagick::getImageGreenPrimary | Imagick::setImageInterpolateMethod |  | Imagick::setImageIndex
Imagick::cycleColormapImage | Imagick::getImageHeight | Imagick::setImageIterations |  | Imagick::valid
Imagick::deconstructImages | Imagick::getImageHistogram | Imagick::setImageMatteColor |  |
Imagick::drawImage | Imagick::getImageIndex | Imagick::setImageMatte |  |
Imagick::edgeImage | Imagick::getImageInterlaceScheme | Imagick::setImagePage |  |
Imagick::embossImage | Imagick::getImageInterpolateMethod | Imagick::setImageProfile |  |
Imagick::enhanceImage | Imagick::getImageIterations | Imagick::setImageProperty |  |
Imagick::equalizeImage | Imagick::getImageMatteColor | Imagick::setImageRedPrimary |  |
Imagick::evaluateImage | Imagick::getImageMatte | Imagick::setImageRenderingIntent |  |
Imagick::flattenImages | Imagick::getImagePage | Imagick::setImageResolution |  |
Imagick::flipImage | Imagick::getImagePixelColor | Imagick::setImageScene |  |
Imagick::flopImage | Imagick::getImageProfile | Imagick::setImageTicksPerSecond |  |
Imagick::imageImage | Imagick::getImageProperty | Imagick::setImageType |  |
Imagick::fxImage | Imagick::getImageRedPrimary | Imagick::setImageUnits |  |
Imagick::gammaImage | Imagick::getImageRegion | Imagick::setImageVirtualPixelMethod |  |
Imagick::gaussianBlurImage | Imagick::getImageRenderingIntent | Imagick::setImageWhitepoint |  |
Imagick::implodeImage | Imagick::getImageResolution | Imagick::setInterlaceScheme |  |
Imagick::levelImage | Imagick::getImageScene | Imagick::setOption |  |
Imagick::linearStretchImage | Imagick::getImageSignature | Imagick::setPage |  |
Imagick::magnifyImage | Imagick::getImageTicksPerSecond | Imagick::setResolution |  |
Imagick::matteFloodFilleImage | Imagick::getImageTotalInkDensity | Imagick::setResourceLimit |  |
Imagick::medianFilterImage | Imagick::getImageType | Imagick::setSamplingFactors |  |
Imagick::minifyImage | Imagick::getImageUnits | Imagick::setSizeOffset |  |
Imagick::modulateImage | Imagick::getImageVirtualPixelMethod | Imagick::setSize |  |
Imagick::montageImage | Imagick::getImageWhitepoint | Imagick::setType |  |
Imagick::morphImages | Imagick::getImageWidth |  |  |
Imagick::mosaicImages | Imagick::getImage |  |  |
Imagick::motionBlurImage | Imagick::getInterlaceScheme |  |  |
Imagick::negateImage | Imagick::getNumberImages |  |  |
Imagick::normalizeImage | Imagick::getOption |  |  |
Imagick::oilPaintImage | Imagick::getPackageName |  |  |
Imagick::optimizeImageLayers | Imagick::getPage |  |  |
Imagick::paintOpaqueImage | Imagick::getPixelIterator |  |  |
Imagick::paintTransparentImage | Imagick::getPixelRegionIterator |  |  |
Imagick::posterizeImage | Imagick::getQuantumDepth |  |  |
Imagick::radialBlurImage | Imagick::getQuantumRange |  |  |
Imagick::raiseImage | Imagick::getResourceLimit |  |  |
Imagick::randomThresholdImage | Imagick::getResource |  |  |
Imagick::reduceNoiseImage | Imagick::getSamplingFactors |  |  |
Imagick::render | Imagick::getSizeOffset |  |  |
Imagick::resampleImage | Imagick::getSize |  |  |
Imagick::resizeImage | Imagick::identifyImage |  |  |
Imagick::rollImage | Imagick::getImageSize |  |  |
Imagick::rotateImage |  |  |  |
Imagick::sampleImage |  |  |  |
Imagick::scaleImage |  |  |  |
Imagick::separateImageChannel |  |  |  |
Imagick::sepiaToneImage |  |  |  |
Imagick::shadeImage |  |  |  |
Imagick::shadowImage |  |  |  |
Imagick::sharpenImage |  |  |  |
Imagick::shaveImage |  |  |  |
Imagick::shearImage |  |  |  |
Imagick::sigmoidalContrastImage |  |  |  |
Imagick::sketchImage |  |  |  |
Imagick::solarizeImage |  |  |  |
Imagick::spliceImage |  |  |  |
Imagick::spreadImage |  |  |  |
Imagick::steganoImage |  |  |  |
Imagick::stereoImage |  |  |  |
Imagick::stripImage |  |  |  |
Imagick::swirlImage |  |  |  |
Imagick::textureImage |  |  |  |
Imagick::thresholdImage |  |  |  |
Imagick::thumbnailImage |  |  |  |
Imagick::tintImage |  |  |  |
Imagick::transverseImage |  |  |  |
Imagick::trimImage |  |  |  |
Imagick::uniqueImageColors |  |  |  |
Imagick::unsharpMaskImage |  |  |  |
Imagick::vignetteImage |  |  |  |
Imagick::waveImage |  |  |  |
Imagick::whiteThresholdImage |  |  |  |

Table of Contents

  • Imagick::adaptiveBlurImage — Adds adaptive blur filter to image
  • Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation
  • Imagick::adaptiveSharpenImage — Adaptively sharpen the image
  • Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity
  • Imagick::addImage — Adds new image to Imagick object image list
  • Imagick::addNoiseImage — Adds random noise to the image
  • Imagick::affineTransformImage — Transforms an image
  • Imagick::animateImages — Animates an image or images
  • Imagick::annotateImage — Annotates an image with text
  • Imagick::appendImages — Append a set of images
  • Imagick::averageImages — Average a set of images
  • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
  • Imagick::blurImage — Adds blur filter to image
  • Imagick::borderImage — Surrounds the image with a border
  • Imagick::charcoalImage — Simulates a charcoal drawing
  • Imagick::chopImage — Removes a region of an image and trims
  • Imagick::clear — Clears all resources associated to Imagick object
  • Imagick::clipImage — Clips along the first path from the 8BIM profile
  • Imagick::clipPathImage — Clips along the named paths from the 8BIM profile
  • Imagick::clone — Makes an exact copy of the Imagick object
  • Imagick::clutImage — Replaces colors in the image
  • Imagick::coalesceImages — Composites a set of images
  • Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target
  • Imagick::colorizeImage — Blends the fill color with the image
  • Imagick::combineImages — Combines one or more images into a single image
  • Imagick::commentImage — Adds a comment to your image
  • Imagick::compareImageChannels — Returns the difference in one or more images
  • Imagick::compareImageLayers — Returns the maximum bounding region between images
  • Imagick::compareImages — Compares an image to a reconstructed image
  • Imagick::compositeImage — Composite one image onto another
  • Imagick::__construct — The Imagick constructor
  • Imagick::contrastImage — Change the contrast of the image
  • Imagick::contrastStretchImage — Enhances the contrast of a color image
  • Imagick::convolveImage — Applies a custom convolution kernel to the image
  • Imagick::cropImage — Extracts a region of the image
  • Imagick::cropThumbnailImage — Creates a crop thumbnail
  • Imagick::current — Returns a reference to the current Imagick object
  • Imagick::cycleColormapImage — Displaces an image's colormap
  • Imagick::decipherImage — Deciphers an image
  • Imagick::deconstructImages — Returns certain pixel differences between images
  • Imagick::deskewImage — Removes skew from the image
  • Imagick::despeckleImage — Reduces the speckle noise in an image
  • Imagick::destroy — Destroys the Imagick object
  • Imagick::displayImage — Displays an image
  • Imagick::displayImages — Displays an image or image sequence
  • Imagick::distortImage — Distorts an image using various distortion methods
  • Imagick::drawImage — Renders the ImagickDraw object on the current image
  • Imagick::edgeImage — Enhance edges within the image
  • Imagick::embossImage — Returns a grayscale image with a three-dimensional effect
  • Imagick::encipherImage — Enciphers an image
  • Imagick::enhanceImage — Improves the quality of a noisy image
  • Imagick::equalizeImage — Equalizes the image histogram
  • Imagick::evaluateImage — Applies an expression to an image
  • Imagick::exportImagePixels — Exports raw image pixels
  • Imagick::extentImage — Set image size
  • Imagick::flattenImages — Merges a sequence of images
  • Imagick::flipImage — Creates a vertical mirror image
  • Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target
  • Imagick::flopImage — Creates a horizontal mirror image
  • Imagick::frameImage — Adds a simulated three-dimensional border
  • Imagick::functionImage — Applies a function on the image
  • Imagick::fxImage — Evaluate expression for each pixel in the image
  • Imagick::gammaImage — Gamma-corrects an image
  • Imagick::gaussianBlurImage — Blurs an image
  • Imagick::getCompression — Gets the object compression type
  • Imagick::getCompressionQuality — Gets the object compression quality
  • Imagick::getCopyright — Returns the ImageMagick API copyright as a string
  • Imagick::getFilename — The filename associated with an image sequence
  • Imagick::getFont — Gets font
  • Imagick::getFormat — Returns the format of the Imagick object
  • Imagick::getGravity — Gets the gravity
  • Imagick::getHomeURL — Returns the ImageMagick home URL
  • Imagick::getImage — Returns a new Imagick object
  • Imagick::getImageAlphaChannel — Gets the image alpha channel
  • Imagick::getImageBackgroundColor — Returns the image background color
  • Imagick::getImageBlob — Returns the image sequence as a blob
  • Imagick::getImageBluePrimary — Returns the chromaticy blue primary point
  • Imagick::getImageBorderColor — Returns the image border color
  • Imagick::getImageChannelDepth — Gets the depth for a particular image channel
  • Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image
  • Imagick::getImageChannelDistortions — Gets channel distortions
  • Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
  • Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose
  • Imagick::getImageChannelMean — Gets the mean and standard deviation
  • Imagick::getImageChannelRange — Gets channel range
  • Imagick::getImageChannelStatistics — Returns statistics for each channel in the image
  • Imagick::getImageClipMask — Gets image clip mask
  • Imagick::getImageColormapColor — Returns the color of the specified colormap index
  • Imagick::getImageColors — Gets the number of unique colors in the image
  • Imagick::getImageColorspace — Gets the image colorspace
  • Imagick::getImageCompose — Returns the composite operator associated with the image
  • Imagick::getImageCompression — Gets the current image's compression type
  • Imagick::getImageCompressionQuality — Gets the current image's compression quality
  • Imagick::getImageDelay — Gets the image delay
  • Imagick::getImageDepth — Gets the image depth
  • Imagick::getImageDispose — Gets the image disposal method
  • Imagick::getImageDistortion — Compares an image to a reconstructed image
  • Imagick::getImageExtrema — Gets the extrema for the image
  • Imagick::getImageFilename — Returns the filename of a particular image in a sequence
  • Imagick::getImageFormat — Returns the format of a particular image in a sequence
  • Imagick::getImageGamma — Gets the image gamma
  • Imagick::getImageGeometry — Gets the width and height as an associative array
  • Imagick::getImageGravity — Gets the image gravity
  • Imagick::getImageGreenPrimary — Returns the chromaticy green primary point
  • Imagick::getImageHeight — Returns the image height
  • Imagick::getImageHistogram — Gets the image histogram
  • Imagick::getImageIndex — Gets the index of the current active image
  • Imagick::getImageInterlaceScheme — Gets the image interlace scheme
  • Imagick::getImageInterpolateMethod — Returns the interpolation method
  • Imagick::getImageIterations — Gets the image iterations
  • Imagick::getImageLength — Returns the image length in bytes
  • Imagick::getImageMagickLicense — Returns a string containing the ImageMagick license
  • Imagick::getImageMatte — Return if the image has a matte channel
  • Imagick::getImageMatteColor — Returns the image matte color
  • Imagick::getImageOrientation — Gets the image orientation
  • Imagick::getImagePage — Returns the page geometry
  • Imagick::getImagePixelColor — Returns the color of the specified pixel
  • Imagick::getImageProfile — Returns the named image profile
  • Imagick::getImageProfiles — Returns the image profiles
  • Imagick::getImageProperties — Returns the image properties
  • Imagick::getImageProperty — Returns the named image property
  • Imagick::getImageRedPrimary — Returns the chromaticity red primary point
  • Imagick::getImageRegion — Extracts a region of the image
  • Imagick::getImageRenderingIntent — Gets the image rendering intent
  • Imagick::getImageResolution — Gets the image X and Y resolution
  • Imagick::getImagesBlob — Returns all image sequences as a blob
  • Imagick::getImageScene — Gets the image scene
  • Imagick::getImageSignature — Generates an SHA-256 message digest
  • Imagick::getImageSize — Returns the image length in bytes
  • Imagick::getImageTicksPerSecond — Gets the image ticks-per-second
  • Imagick::getImageTotalInkDensity — Gets the image total ink density
  • Imagick::getImageType — Gets the potential image type
  • Imagick::getImageUnits — Gets the image units of resolution
  • Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method
  • Imagick::getImageWhitePoint — Returns the chromaticity white point
  • Imagick::getImageWidth — Returns the image width
  • Imagick::getInterlaceScheme — Gets the object interlace scheme
  • Imagick::getIteratorIndex — Gets the index of the current active image
  • Imagick::getNumberImages — Returns the number of images in the object
  • Imagick::getOption — Returns a value associated with the specified key
  • Imagick::getPackageName — Returns the ImageMagick package name
  • Imagick::getPage — Returns the page geometry
  • Imagick::getPixelIterator — Returns a MagickPixelIterator
  • Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section
  • Imagick::getPointSize — Gets point size
  • Imagick::getQuantumDepth — Gets the quantum depth
  • Imagick::getQuantumRange — Returns the Imagick quantum range
  • Imagick::getReleaseDate — Returns the ImageMagick release date
  • Imagick::getResource — Returns the specified resource's memory usage
  • Imagick::getResourceLimit — Returns the specified resource limit
  • Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor
  • Imagick::getSize — Returns the size associated with the Imagick object
  • Imagick::getSizeOffset — Returns the size offset
  • Imagick::getVersion — Returns the ImageMagick API version
  • Imagick::haldClutImage — Replaces colors in the image
  • Imagick::hasNextImage — Checks if the object has more images
  • Imagick::hasPreviousImage — Checks if the object has a previous image
  • Imagick::identifyImage — Identifies an image and fetches attributes
  • Imagick::implodeImage — Creates a new image as a copy
  • Imagick::importImagePixels — Imports image pixels
  • Imagick::labelImage — Adds a label to an image
  • Imagick::levelImage — Adjusts the levels of an image
  • Imagick::linearStretchImage — Stretches with saturation the image intensity
  • Imagick::liquidRescaleImage — Animates an image or images
  • Imagick::magnifyImage — Scales an image proportionally 2x
  • Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image.
  • Imagick::matteFloodfillImage — Changes the transparency value of a color
  • Imagick::medianFilterImage — Applies a digital filter
  • Imagick::mergeImageLayers — Merges image layers
  • Imagick::minifyImage — Scales an image proportionally to half its size
  • Imagick::modulateImage — Control the brightness, saturation, and hue
  • Imagick::montageImage — Creates a composite image
  • Imagick::morphImages — Method morphs a set of images
  • Imagick::mosaicImages — Forms a mosaic from images
  • Imagick::motionBlurImage — Simulates motion blur
  • Imagick::negateImage — Negates the colors in the reference image
  • Imagick::newImage — Creates a new image
  • Imagick::newPseudoImage — Creates a new image
  • Imagick::nextImage — Moves to the next image
  • Imagick::normalizeImage — Enhances the contrast of a color image
  • Imagick::oilPaintImage — Simulates an oil painting
  • Imagick::opaquePaintImage — Changes the color value of any pixel that matches target
  • Imagick::optimizeImageLayers — Removes repeated portions of images to optimize
  • Imagick::orderedPosterizeImage — Performs an ordered dither
  • Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target
  • Imagick::paintOpaqueImage — Change any pixel that matches color
  • Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill
  • Imagick::pingImage — Fetch basic attributes about the image
  • Imagick::pingImageBlob — Quickly fetch attributes
  • Imagick::pingImageFile — Get basic image attributes in a lightweight manner
  • Imagick::polaroidImage — Simulates a Polaroid picture
  • Imagick::posterizeImage — Reduces the image to a limited number of color level
  • Imagick::previewImages — Quickly pin-point appropriate parameters for image processing
  • Imagick::previousImage — Move to the previous image in the object
  • Imagick::profileImage — Adds or removes a profile from an image
  • Imagick::quantizeImage — Analyzes the colors within a reference image
  • Imagick::quantizeImages — Analyzes the colors within a sequence of images
  • Imagick::queryFontMetrics — Returns an array representing the font metrics
  • Imagick::queryFonts — Returns the configured fonts
  • Imagick::queryFormats — Returns formats supported by Imagick
  • Imagick::radialBlurImage — Radial blurs an image
  • Imagick::raiseImage — Creates a simulated 3d button-like effect
  • Imagick::randomThresholdImage — Creates a high-contrast, two-color image
  • Imagick::readImage — Reads image from filename
  • Imagick::readImageBlob — Reads image from a binary string
  • Imagick::readImageFile — Reads image from open filehandle
  • Imagick::recolorImage — Recolors image
  • Imagick::reduceNoiseImage — Smooths the contours of an image
  • Imagick::remapImage — Remaps image colors
  • Imagick::removeImage — Removes an image from the image list
  • Imagick::removeImageProfile — Removes the named image profile and returns it
  • Imagick::render — Renders all preceding drawing commands
  • Imagick::resampleImage — Resample image to desired resolution
  • Imagick::resetImagePage — Reset image page
  • Imagick::resizeImage — Scales an image
  • Imagick::rollImage — Offsets an image
  • Imagick::rotateImage — Rotates an image
  • Imagick::roundCorners — Rounds image corners
  • Imagick::sampleImage — Scales an image with pixel sampling
  • Imagick::scaleImage — Scales the size of an image
  • Imagick::segmentImage — Segments an image
  • Imagick::separateImageChannel — Separates a channel from the image
  • Imagick::sepiaToneImage — Sepia tones an image
  • Imagick::setBackgroundColor — Sets the object's default background color
  • Imagick::setCompression — Sets the object's default compression type
  • Imagick::setCompressionQuality — Sets the object's default compression quality
  • Imagick::setFilename — Sets the filename before you read or write the image
  • Imagick::setFirstIterator — Sets the Imagick iterator to the first image
  • Imagick::setFont — Sets font
  • Imagick::setFormat — Sets the format of the Imagick object
  • Imagick::setGravity — Sets the gravity
  • Imagick::setImage — Replaces image in the object
  • Imagick::setImageAlphaChannel — Sets image alpha channel
  • Imagick::setImageBackgroundColor — Sets the image background color
  • Imagick::setImageBias — Sets the image bias for any method that convolves an image
  • Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point
  • Imagick::setImageBorderColor — Sets the image border color
  • Imagick::setImageChannelDepth — Sets the depth of a particular image channel
  • Imagick::setImageClipMask — Sets image clip mask
  • Imagick::setImageColormapColor — Sets the color of the specified colormap index
  • Imagick::setImageColorspace — Sets the image colorspace
  • Imagick::setImageCompose — Sets the image composite operator
  • Imagick::setImageCompression — Sets the image compression
  • Imagick::setImageCompressionQuality — Sets the image compression quality
  • Imagick::setImageDelay — Sets the image delay
  • Imagick::setImageDepth — Sets the image depth
  • Imagick::setImageDispose — Sets the image disposal method
  • Imagick::setImageExtent — Sets the image size
  • Imagick::setImageFilename — Sets the filename of a particular image
  • Imagick::setImageFormat — Sets the format of a particular image
  • Imagick::setImageGamma — Sets the image gamma
  • Imagick::setImageGravity — Sets the image gravity
  • Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point
  • Imagick::setImageIndex — Set the iterator position
  • Imagick::setImageInterlaceScheme — Sets the image compression
  • Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method
  • Imagick::setImageIterations — Sets the image iterations
  • Imagick::setImageMatte — Sets the image matte channel
  • Imagick::setImageMatteColor — Sets the image matte color
  • Imagick::setImageOpacity — Sets the image opacity level
  • Imagick::setImageOrientation — Sets the image orientation
  • Imagick::setImagePage — Sets the page geometry of the image
  • Imagick::setImageProfile — Adds a named profile to the Imagick object
  • Imagick::setImageProperty — Sets an image property
  • Imagick::setImageRedPrimary — Sets the image chromaticity red primary point
  • Imagick::setImageRenderingIntent — Sets the image rendering intent
  • Imagick::setImageResolution — Sets the image resolution
  • Imagick::setImageScene — Sets the image scene
  • Imagick::setImageTicksPerSecond — Sets the image ticks-per-second
  • Imagick::setImageType — Sets the image type
  • Imagick::setImageUnits — Sets the image units of resolution
  • Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method
  • Imagick::setImageWhitePoint — Sets the image chromaticity white point
  • Imagick::setInterlaceScheme — Sets the image compression
  • Imagick::setIteratorIndex — Set the iterator position
  • Imagick::setLastIterator — Sets the Imagick iterator to the last image
  • Imagick::setOption — Set an option
  • Imagick::setPage — Sets the page geometry of the Imagick object
  • Imagick::setPointSize — Sets point size
  • Imagick::setResolution — Sets the image resolution
  • Imagick::setResourceLimit — Sets the limit for a particular resource in megabytes
  • Imagick::setSamplingFactors — Sets the image sampling factors
  • Imagick::setSize — Sets the size of the Imagick object
  • Imagick::setSizeOffset — Sets the size and offset of the Imagick object
  • Imagick::setType — Sets the image type attribute
  • Imagick::shadeImage — Creates a 3D effect
  • Imagick::shadowImage — Simulates an image shadow
  • Imagick::sharpenImage — Sharpens an image
  • Imagick::shaveImage — Shaves pixels from the image edges
  • Imagick::shearImage — Creating a parallelogram
  • Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
  • Imagick::sketchImage — Simulates a pencil sketch
  • Imagick::solarizeImage — Applies a solarizing effect to the image
  • Imagick::sparseColorImage — Interpolates colors
  • Imagick::spliceImage — Splices a solid color into the image
  • Imagick::spreadImage — Randomly displaces each pixel in a block
  • Imagick::steganoImage — Hides a digital watermark within the image
  • Imagick::stereoImage — Composites two images
  • Imagick::stripImage — Strips an image of all profiles and comments
  • Imagick::swirlImage — Swirls the pixels about the center of the image
  • Imagick::textureImage — Repeatedly tiles the texture image
  • Imagick::thresholdImage — Changes the value of individual pixels based on a threshold
  • Imagick::thumbnailImage — Changes the size of an image
  • Imagick::tintImage — Applies a color vector to each pixel in the image
  • Imagick::transformImage — Convenience method for setting crop size and the image geometry
  • Imagick::transparentPaintImage — Paints pixels transparent
  • Imagick::transposeImage — Creates a vertical mirror image
  • Imagick::transverseImage — Creates a horizontal mirror image
  • Imagick::trimImage — Remove edges from the image
  • Imagick::uniqueImageColors — Discards all but one of any pixel color
  • Imagick::unsharpMaskImage — Sharpens an image
  • Imagick::valid — Checks if the current item is valid
  • Imagick::vignetteImage — Adds vignette filter to the image
  • Imagick::waveImage — Applies wave filter to the image
  • Imagick::whiteThresholdImage — Force all pixels above the threshold into white
  • Imagick::writeImage — Writes an image to the specified filename
  • Imagick::writeImageFile — Writes an image to a filehandle
  • Imagick::writeImages — Writes an image or image sequence
  • Imagick::writeImagesFile — Writes frames to a filehandle
Examples
Imagick::adaptiveBlurImage
ImageMagick


The ImagickDraw class

Class synopsis

ImagickDraw
ImagickDraw {
bool affine ( array $affine )
bool annotation ( float $x , float $y , string $text )
bool arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )
bool bezier ( array $coordinates )
bool circle ( float $ox , float $oy , float $px , float $py )
bool clear ( void )
ImagickDraw clone ( void )
bool color ( float $x , float $y , int $paintMethod )
bool comment ( string $comment )
bool composite ( int $compose , float $x , float $y , float $width , float $height , Imagick $compositeWand )
ImagickDraw __construct ( void )
bool destroy ( void )
bool ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )
string getClipPath ( void )
int getClipRule ( void )
int getClipUnits ( void )
ImagickPixel getFillColor ( void )
float getFillOpacity ( void )
int getFillRule ( void )
string getFont ( void )
string getFontFamily ( void )
float getFontSize ( void )
int getFontStyle ( void )
int getFontWeight ( void )
int getGravity ( void )
bool getStrokeAntialias ( void )
ImagickPixel getStrokeColor ( ImagickPixel $stroke_color )
array getStrokeDashArray ( void )
float getStrokeDashOffset ( void )
int getStrokeLineCap ( void )
int getStrokeLineJoin ( void )
int getStrokeMiterLimit ( void )
float getStrokeOpacity ( void )
float getStrokeWidth ( void )
int getTextAlignment ( void )
bool getTextAntialias ( void )
int getTextDecoration ( void )
string getTextEncoding ( void )
ImagickPixel getTextUnderColor ( void )
string getVectorGraphics ( void )
bool line ( float $sx , float $sy , float $ex , float $ey )
bool matte ( float $x , float $y , int $paintMethod )
bool pathClose ( void )
bool pathCurveToAbsolute ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
bool pathCurveToQuadraticBezierAbsolute ( float $x1 , float $y1 , float $x , float $y )
bool pathCurveToQuadraticBezierRelative ( float $x1 , float $y1 , float $x , float $y )
bool pathCurveToQuadraticBezierSmoothAbsolute ( float $x , float $y )
bool pathCurveToQuadraticBezierSmoothRelative ( float $x , float $y )
bool pathCurveToRelative ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
bool pathCurveToSmoothAbsolute ( float $x2 , float $y2 , float $x , float $y )
bool pathCurveToSmoothRelative ( float $x2 , float $y2 , float $x , float $y )
bool pathEllipticArcAbsolute ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
bool pathEllipticArcRelative ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
bool pathFinish ( void )
bool pathLineToAbsolute ( float $x , float $y )
bool pathLineToHorizontalAbsolute ( float $x )
bool pathLineToHorizontalRelative ( float $x )
bool pathLineToRelative ( float $x , float $y )
bool pathLineToVerticalAbsolute ( float $y )
bool pathLineToVerticalRelative ( float $y )
bool pathMoveToAbsolute ( float $x , float $y )
bool pathMoveToRelative ( float $x , float $y )
bool pathStart ( void )
bool point ( float $x , float $y )
bool polygon ( array $coordinates )
bool polyline ( array $coordinates )
bool pop ( void )
bool popClipPath ( void )
bool popDefs ( void )
bool popPattern ( void )
bool push ( void )
bool pushClipPath ( string $clip_mask_id )
bool pushDefs ( void )
bool pushPattern ( string $pattern_id , float $x , float $y , float $width , float $height )
bool rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )
bool render ( void )
bool rotate ( float $degrees )
bool roundRectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )
bool scale ( float $x , float $y )
bool setClipPath ( string $clip_mask )
bool setClipRule ( int $fill_rule )
bool setClipUnits ( int $clip_units )
bool setFillAlpha ( float $opacity )
bool setFillColor ( ImagickPixel $fill_pixel )
bool setFillOpacity ( float $fillOpacity )
bool setFillPatternURL ( string $fill_url )
bool setFillRule ( int $fill_rule )
bool setFont ( string $font_name )
bool setFontFamily ( string $font_family )
bool setFontSize ( float $pointsize )
bool setFontStretch ( int $fontStretch )
bool setFontStyle ( int $style )
bool setFontWeight ( int $font_weight )
bool setGravity ( int $gravity )
bool setStrokeAlpha ( float $opacity )
bool setStrokeAntialias ( bool $stroke_antialias )
bool setStrokeColor ( ImagickPixel $stroke_pixel )
bool setStrokeDashArray ( array $dashArray )
bool setStrokeDashOffset ( float $dash_offset )
bool setStrokeLineCap ( int $linecap )
bool setStrokeLineJoin ( int $linejoin )
bool setStrokeMiterLimit ( int $miterlimit )
bool setStrokeOpacity ( float $stroke_opacity )
bool setStrokePatternURL ( string $stroke_url )
bool setStrokeWidth ( float $stroke_width )
bool setTextAlignment ( int $alignment )
bool setTextAntialias ( bool $antiAlias )
bool setTextDecoration ( int $decoration )
bool setTextEncoding ( string $encoding )
bool setTextUnderColor ( ImagickPixel $under_color )
bool setVectorGraphics ( string $xml )
bool setViewbox ( int $x1 , int $y1 , int $x2 , int $y2 )
bool skewX ( float $degrees )
bool skewY ( float $degrees )
bool translate ( float $x , float $y )
}

Table of Contents

  • ImagickDraw::affine — Adjusts the current affine transformation matrix
  • ImagickDraw::annotation — Draws text on the image
  • ImagickDraw::arc — Draws an arc
  • ImagickDraw::bezier — Draws a bezier curve
  • ImagickDraw::circle — Draws a circle
  • ImagickDraw::clear — Clears the ImagickDraw
  • ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object
  • ImagickDraw::color — Draws color on image
  • ImagickDraw::comment — Adds a comment
  • ImagickDraw::composite — Composites an image onto the current image
  • ImagickDraw::__construct — The ImagickDraw constructor
  • ImagickDraw::destroy — Frees all associated resources
  • ImagickDraw::ellipse — Draws an ellipse on the image
  • ImagickDraw::getClipPath — Obtains the current clipping path ID
  • ImagickDraw::getClipRule — Returns the current polygon fill rule
  • ImagickDraw::getClipUnits — Returns the interpretation of clip path units
  • ImagickDraw::getFillColor — Returns the fill color
  • ImagickDraw::getFillOpacity — Returns the opacity used when drawing
  • ImagickDraw::getFillRule — Returns the fill rule
  • ImagickDraw::getFont — Returns the font
  • ImagickDraw::getFontFamily — Returns the font family
  • ImagickDraw::getFontSize — Returns the font pointsize
  • ImagickDraw::getFontStyle — Returns the font style
  • ImagickDraw::getFontWeight — Returns the font weight
  • ImagickDraw::getGravity — Returns the text placement gravity
  • ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting
  • ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines
  • ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths
  • ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash
  • ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked
  • ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked
  • ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit
  • ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines
  • ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines
  • ImagickDraw::getTextAlignment — Returns the text alignment
  • ImagickDraw::getTextAntialias — Returns the current text antialias setting
  • ImagickDraw::getTextDecoration — Returns the text decoration
  • ImagickDraw::getTextEncoding — Returns the code set used for text annotations
  • ImagickDraw::getTextUnderColor — Returns the text under color
  • ImagickDraw::getVectorGraphics — Returns a string containing vector graphics
  • ImagickDraw::line — Draws a line
  • ImagickDraw::matte — Paints on the image's opacity channel
  • ImagickDraw::pathClose — Adds a path element to the current path
  • ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve
  • ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc
  • ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc
  • ImagickDraw::pathFinish — Terminates the current path
  • ImagickDraw::pathLineToAbsolute — Draws a line path
  • ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path
  • ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line
  • ImagickDraw::pathLineToRelative — Draws a line path
  • ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line
  • ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path
  • ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
  • ImagickDraw::pathMoveToRelative — Starts a new sub-path
  • ImagickDraw::pathStart — Declares the start of a path drawing list
  • ImagickDraw::point — Draws a point
  • ImagickDraw::polygon — Draws a polygon
  • ImagickDraw::polyline — Draws a polyline
  • ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
  • ImagickDraw::popClipPath — Terminates a clip path definition
  • ImagickDraw::popDefs — Terminates a definition list
  • ImagickDraw::popPattern — Terminates a pattern definition
  • ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack
  • ImagickDraw::pushClipPath — Starts a clip path definition
  • ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing
  • ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
  • ImagickDraw::rectangle — Draws a rectangle
  • ImagickDraw::render — Renders all preceding drawing commands onto the image
  • ImagickDraw::rotate — Applies the specified rotation to the current coordinate space
  • ImagickDraw::roundRectangle — Draws a rounded rectangle
  • ImagickDraw::scale — Adjusts the scaling factor
  • ImagickDraw::setClipPath — Associates a named clipping path with the image
  • ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path
  • ImagickDraw::setClipUnits — Sets the interpretation of clip path units
  • ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture
  • ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects
  • ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
  • ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
  • ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons
  • ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text
  • ImagickDraw::setFontFamily — Sets the font family to use when annotating with text
  • ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text
  • ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text
  • ImagickDraw::setFontStyle — Sets the font style to use when annotating with text
  • ImagickDraw::setFontWeight — Sets the font weight
  • ImagickDraw::setGravity — Sets the text placement gravity
  • ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines
  • ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased
  • ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines
  • ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths
  • ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
  • ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked
  • ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked
  • ImagickDraw::setStrokeMiterLimit — Specifies the miter limit
  • ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines
  • ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines
  • ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines
  • ImagickDraw::setTextAlignment — Specifies a text alignment
  • ImagickDraw::setTextAntialias — Controls whether text is antialiased
  • ImagickDraw::setTextDecoration — Specifies a decoration
  • ImagickDraw::setTextEncoding — Specifies specifies the text code set
  • ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle
  • ImagickDraw::setVectorGraphics — Sets the vector graphics
  • ImagickDraw::setViewbox — Sets the overall canvas size
  • ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction
  • ImagickDraw::skewY — Skews the current coordinate system in the vertical direction
  • ImagickDraw::translate — Applies a translation to the current coordinate system
Imagick::writeImagesFile
ImagickDraw::affine
ImageMagick


The ImagickPixel class

Class synopsis

ImagickPixel
ImagickPixel {
bool clear ( void )
ImagickPixel __construct ([ string $color ] )
bool destroy ( void )
array getColor ([ bool $normalized = false ] )
string getColorAsString ( void )
int getColorCount ( void )
float getColorValue ( int $color )
array getHSL ( void )
bool isSimilar ( ImagickPixel $color , float $fuzz )
bool setColor ( string $color )
bool setColorValue ( int $color , float $value )
bool setHSL ( float $hue , float $saturation , float $luminosity )
}

Table of Contents

  • ImagickPixel::clear — Clears resources associated with this object
  • ImagickPixel::__construct — The ImagickPixel constructor
  • ImagickPixel::destroy — Deallocates resources associated with this object
  • ImagickPixel::getColor — Returns the color
  • ImagickPixel::getColorAsString — Returns the color as a string
  • ImagickPixel::getColorCount — Returns the color count associated with this color
  • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
  • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
  • ImagickPixel::isSimilar — Check the distance between this color and another
  • ImagickPixel::setColor — Sets the color
  • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
  • ImagickPixel::setHSL — Sets the normalized HSL color
ImagickDraw::translate
ImagickPixel::clear
ImageMagick


The ImagickPixelIterator class

Class synopsis

ImagickPixelIterator
ImagickPixelIterator {
bool clear ( void )
ImagickPixelIterator __construct ( Imagick $wand )
bool destroy ( void )
array getCurrentIteratorRow ( void )
int getIteratorRow ( void )
array getNextIteratorRow ( void )
array getPreviousIteratorRow ( void )
bool newPixelIterator ( Imagick $wand )
bool newPixelRegionIterator ( Imagick $wand , int $x , int $y , int $columns , int $rows )
bool resetIterator ( void )
bool setIteratorFirstRow ( void )
bool setIteratorLastRow ( void )
bool setIteratorRow ( int $row )
bool syncIterator ( void )
}

Table of Contents

  • ImagickPixelIterator::clear — Clear resources associated with a PixelIterator
  • ImagickPixelIterator::__construct — The ImagickPixelIterator constructor
  • ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator
  • ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects
  • ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row
  • ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator
  • ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row
  • ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator
  • ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator
  • ImagickPixelIterator::resetIterator — Resets the pixel iterator
  • ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row
  • ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row
  • ImagickPixelIterator::setIteratorRow — Set the pixel iterator row
  • ImagickPixelIterator::syncIterator — Syncs the pixel iterator
ImagickPixel::setHSL
ImagickPixelIterator::clear
ImageMagick


The IntlDateFormatter class

Introduction

Date Formatter is a concrete class that enables locale-dependent formatting/parsing of dates using pattern strings and/or canned patterns.

This class represents the ICU date formatting functionality. It allows users to display dates in a localized format or to parse strings into PHP date values using pattern strings and/or canned patterns.

Class synopsis

IntlDateFormatter
IntlDateFormatter {
/* Methods */
__construct ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )
static IntlDateFormatter create ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )
string format ( mixed $value )
int getCalendar ( void )
int getDateType ( void )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ([ int $which ] )
string getPattern ( void )
int getTimeType ( void )
string getTimeZoneId ( void )
bool isLenient ( void )
array localtime ( string $value [, int &$position ] )
int parse ( string $value [, int &$position ] )
bool setCalendar ( int $which )
bool setLenient ( bool $lenient )
bool setPattern ( string $pattern )
bool setTimeZoneId ( string $zone )
}

See Also

  • » ICU Date formatter

  • » ICU Date formats

Predefined Constants

These constants are used to specify different formats in the constructor for DateType and TimeType.

IntlDateFormatter::NONE (string)
Do not include this element
IntlDateFormatter::FULL (string)
Completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST)
IntlDateFormatter::LONG (string)
Long style (January 12, 1952 or 3:30:32pm)
IntlDateFormatter::MEDIUM (string)
Medium style (Jan 12, 1952)
IntlDateFormatter::SHORT (string)
Most abbreviated style, only essential data (12/13/52 or 3:30pm)

The following int constants are used to specify the calendar. These calendars are all based directly on the Gregorian calendar. Non-Gregorian calendars need to be specified in locale. Examples might include locale="hi@calendar=BUDDHIST".

IntlDateFormatter::TRADITIONAL (string)
Non-Gregorian Calendar
IntlDateFormatter::GREGORIAN (string)
Gregorian Calendar

Table of Contents

  • IntlDateFormatter::create — Create a date formatter
  • IntlDateFormatter::format — Format the date/time value as a string
  • IntlDateFormatter::getCalendar — Get the calendar used for the IntlDateFormatter
  • IntlDateFormatter::getDateType — Get the datetype used for the IntlDateFormatter
  • IntlDateFormatter::getErrorCode — Get the error code from last operation
  • IntlDateFormatter::getErrorMessage — Get the error text from the last operation.
  • IntlDateFormatter::getLocale — Get the locale used by formatter
  • IntlDateFormatter::getPattern — Get the pattern used for the IntlDateFormatter
  • IntlDateFormatter::getTimeType — Get the timetype used for the IntlDateFormatter
  • IntlDateFormatter::getTimeZoneId — Get the timezone-id used for the IntlDateFormatter
  • IntlDateFormatter::isLenient — Get the lenient used for the IntlDateFormatter
  • IntlDateFormatter::localtime — Parse string to a field-based time value
  • IntlDateFormatter::parse — Parse string to a timestamp value
  • IntlDateFormatter::setCalendar — sets the calendar used to the appropriate calendar, which must be
  • IntlDateFormatter::setLenient — Set the leniency of the parser
  • IntlDateFormatter::setPattern — Set the pattern used for the IntlDateFormatter
  • IntlDateFormatter::setTimeZoneId — Sets the time zone to use
MessageFormatter::setPattern
IntlDateFormatter::create
intl


The Iterator interface

Introduction

Interface for external iterators or objects that can be iterated themselves internally.

Interface synopsis

Iterator
Iterator extends Traversable {
/* Methods */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )
}

Example #1 Basic usage

This example demonstrates in which order methods are called when using foreach with an iterator.

<?php
class myIterator implements Iterator {
    private $position = 0;
    private $array = array(
        "firstelement",
        "secondelement",
        "lastelement",
    );

    public function __construct() {
        $this->position = 0;
    }

    function rewind() {
        var_dump(__METHOD__);
        $this->position = 0;
    }

    function current() {
        var_dump(__METHOD__);
        return $this->array[$this->position];
    }

    function key() {
        var_dump(__METHOD__);
        return $this->position;
    }

    function next() {
        var_dump(__METHOD__);
        ++$this->position;
    }

    function valid() {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
}

$it = new myIterator;

foreach($it as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

The above example will output something similar to:

string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(0)
string(12) "firstelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(1)
string(13) "secondelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(2)
string(11) "lastelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"

Table of Contents

  • Iterator::current — Return the current element
  • Iterator::key — Return the key of the current element
  • Iterator::next — Move forward to next element
  • Iterator::rewind — Rewind the Iterator to the first element
  • Iterator::valid — Checks if current position is valid
Traversable
Iterator::current
Predefined Interfaces


The IteratorAggregate interface

Introduction

Interface to create an external Iterator.

Interface synopsis

IteratorAggregate
IteratorAggregate extends Traversable {
/* Methods */
abstract public Traversable getIterator ( void )
}

Example #1 Basic usage

<?php
class myData implements IteratorAggregate {
    public $property1 = "Public property one";
    public $property2 = "Public property two";
    public $property3 = "Public property three";

    public function __construct() {
        $this->property4 = "last property";
    }

    public function getIterator() {
        return new ArrayIterator($this);
    }
}

$obj = new myData;

foreach($obj as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

The above example will output something similar to:

string(9) "property1"
string(19) "Public property one"

string(9) "property2"
string(19) "Public property two"

string(9) "property3"
string(21) "Public property three"

string(9) "property4"
string(13) "last property"

Table of Contents

  • IteratorAggregate::getIterator — Retrieve an external iterator
Iterator::valid
IteratorAggregate::getIterator
Predefined Interfaces


The Locale class

Introduction

A "Locale" is an identifier used to get language, culture, or regionally-specific behavior from an API. PHP locales are organized and identified the same way that the CLDR locales used by ICU (and many vendors of Unix-like operating systems, the Mac, Java, and so forth) use. Locales are identified using RFC 4646 language tags (which use hyphen, not underscore) in addition to the more traditional underscore-using identifiers. Unless otherwise noted the functions in this class are tolerant of both formats.

Examples of identifiers include:

  • en-US (English, United States)
  • zh-Hant-TW (Chinese, Traditional Script, Taiwan)
  • fr-CA, fr-FR (French for Canada and France respectively)

The Locale class (and related procedural functions) are used to interact with locale identifiers--to verify that an ID is well-formed, valid, etc. The extensions used by CLDR in UAX #35 (and inherited by ICU) are valid and used wherever they would be in ICU normally.

Locales cannot be instantiated as objects. All of the functions/methods provided are static.

The null or empty string obtains the "root" locale. The "root" locale is equivalent to "en_US_POSIX" in CLDR. Language tags (and thus locale identifiers) are case insensitive. There exists a canonicalization function to make case match the specification.

Class synopsis

Locale
Locale {
/* Methods */
static string acceptFromHttp ( string $header )
static string composeLocale ( array $subtags )
static bool filterMatches ( string $langtag , string $locale [, bool $canonicalize = false ] )
static array getAllVariants ( string $locale )
static string getDefault ( void )
static string getDisplayLanguage ( string $locale [, string $in_locale ] )
static string getDisplayName ( string $locale [, string $in_locale ] )
static string getDisplayRegion ( string $locale [, string $in_locale ] )
static string getDisplayScript ( string $locale [, string $in_locale ] )
static string getDisplayVariant ( string $locale [, string $in_locale ] )
static array getKeywords ( string $locale )
static string getPrimaryLanguage ( string $locale )
static string getRegion ( string $locale )
static string getScript ( string $locale )
static string lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )
static array parseLocale ( string $locale )
static bool setDefault ( string $locale )
}

Predefined Constants

Locale::DEFAULT_LOCALE (null)
Used as locale parameter with the methods of the various locale affected classes, such as NumberFormatter. This constant would make the methods to use default locale.

These constants describe the choice of the locale for getLocalte method of different classes.

Locale::ACTUAL_LOCALE (string)
This is locale the data actually comes from.
Locale::VALID_LOCALE (string)
This is the most specific locale supported by ICU.

These constants define how the Locales are parsed or composed. They should be used as keys in the argument array to locale_compose() and are returned from locale_parse() as keys of the returned associative array.

Locale::LANG_TAG (string)
Language subtag
Locale::EXTLANG_TAG (string)
Extended language subtag
Locale::SCRIPT_TAG (string)
Script subtag
Locale::REGION_TAG (string)
Region subtag
Locale::VARIANT_TAG (string)
Variant subtag
Locale::GRANDFATHERED_LANG_TAG (string)
Grandfathered Language subtag
Locale::PRIVATE_TAG (string)
Private subtag

See Also

  • » RFC 4646 - Tags for Identifying Languages
  • » RFC 4647 - Matching of Language Tags
  • » Unicode CLDR Project:Common Locale Data Repository
  • » IANA Language Subtags Registry
  • » ICU User Guide - Locale
  • » ICU Locale api

Table of Contents

  • Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
  • Locale::composeLocale — Returns a correctly ordered and delimited locale ID
  • Locale::filterMatches — Checks if a language tag filter matches with locale
  • Locale::getAllVariants — Gets the variants for the input locale
  • Locale::getDefault — Gets the default locale value from the INTL global 'default_locale'
  • Locale::getDisplayLanguage — Returns an appropriately localized display name for language of the inputlocale
  • Locale::getDisplayName — Returns an appropriately localized display name for the input locale
  • Locale::getDisplayRegion — Returns an appropriately localized display name for region of the input locale
  • Locale::getDisplayScript — Returns an appropriately localized display name for script of the input locale
  • Locale::getDisplayVariant — Returns an appropriately localized display name for variants of the input locale
  • Locale::getKeywords — Gets the keywords for the input locale
  • Locale::getPrimaryLanguage — Gets the primary language for the input locale
  • Locale::getRegion — Gets the region for the input locale
  • Locale::getScript — Gets the script for the input locale
  • Locale::lookup — Searches the language tag list for the best match to the language
  • Locale::parseLocale — Returns a key-value array of locale ID subtag elements.
  • Locale::setDefault — sets the default runtime locale
NumberFormatter::setTextAttribute
Locale::acceptFromHttp
intl


The MessageFormatter class

Introduction

MessageFormatter is a concrete class that enables users to produce concatenated, language-neutral messages. The methods supplied in this class are used to build all the messages that are seen by end users.

The MessageFormatter class assembles messages from various fragments (such as text fragments, numbers, and dates) supplied by the program. Because of the MessageFormatter class, the program does not need to know the order of the fragments. The class uses the formatting specifications for the fragments to assemble them into a message that is contained in a single string within a resource bundle. For example, MessageFormatter enables you to print the phrase "Finished printing x out of y files..." in a manner that still allows for flexibility in translation.

Previously, an end user message was created as a sentence and handled as a string. This procedure created problems for localizers because the sentence structure, word order, number format and so on are very different from language to language. The language-neutral way to create messages keeps each part of the message separate and provides keys to the data. Using these keys, the MessageFormatter class can concatenate the parts of the message, localize them, and display a well-formed string to the end user.

MessageFormatter takes a set of objects, formats them, and then inserts the formatted strings into the pattern at the appropriate places. Choice formats can be used in conjunction with MessageFormatter to handle plurals, match numbers, and select from an array of items. Typically, the message format will come from resources and the arguments will be dynamically set at runtime.

Class synopsis

MessageFormatter
MessageFormatter {
/* Methods */
__construct ( string $locale , string $pattern )
MessageFormatter create ( string $locale , string $pattern )
static string formatMessage ( string $locale , string $pattern , array $args )
string format ( array $args )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ( void )
string getPattern ( void )
static array parseMessage ( string $locale , string $value )
array parse ( string $value )
bool setPattern ( string $pattern )
}

See Also

  • » ICU formatting documentation
  • » ICU message formatting description
  • » ICU message formatters
  • » ICU choice formatters

Table of Contents

  • MessageFormatter::create — Constructs a new Message Formatter
  • MessageFormatter::formatMessage — Quick format message
  • MessageFormatter::format — Format the message
  • MessageFormatter::getErrorCode — Get the error code from last operation
  • MessageFormatter::getErrorMessage — Get the error text from the last operation
  • MessageFormatter::getLocale — Get the locale for which the formatter was created.
  • MessageFormatter::getPattern — Get the pattern used by the formatter
  • MessageFormatter::parseMessage — Quick parse input string
  • MessageFormatter::parse — Parse input string according to pattern
  • MessageFormatter::setPattern — Set the pattern used by the formatter
Normalizer::normalize
MessageFormatter::create
intl


The Mongo class

Introduction

The connection point between MongoDB and PHP.

This class is used to initiate a connection and for database server commands. A typical use is:

<?php

$m = new Mongo(); // connect
$db = $m->foo; // get the database named "foo"

?>

See Mongo::__construct() for more information about creating connections.

Class synopsis

Mongo
Mongo {
/* Constants */
const string Mongo::VERSION ;
const string Mongo::DEFAULT_HOST = "localhost" ;
const int Mongo::DEFAULT_PORT = 27017 ;
/* Fields */
public boolean $connected = FALSE ;
protected string $server = localhost:27017 ;
protected string $username = "" ;
protected string $password = "" ;
protected boolean $persistent = FALSE ;
/* Methods */
public boolean close ( void )
public boolean connect ( void )
protected boolean connectUtil ( string $username , string $password )
__construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) ]] )
public array dropDB ( mixed $db )
public bool forceError ( void )
public MongoDB __get ( string $dbname )
public array lastError ( void )
public array listDBs ( void )
public boolean pairConnect ( void )
public boolean pairPersistConnect ([ string $username = "" [, string $password = "" ]] )
public boolean persistConnect ([ string $username = "" [, string $password = "" ]] )
public array prevError ( void )
public array resetError ( void )
public MongoCollection selectCollection ( string|MongoDB $db , string $collection )
public MongoDB selectDB ( string $dbname )
public string __toString ( void )
}

Predefined Constants

Mongo Constants

Mongo::VERSION
PHP driver version. May be suffixed with "+" or "-" if it is in-between versions.
Mongo::DEFAULT_HOST
"localhost"
Host to connect to if no host is given.
Mongo::DEFAULT_PORT
27017
Port to connect to if no port is given.

See Also

MongoDB core docs on » connecting.

Table of Contents

  • Mongo::close — Closes this database connection
  • Mongo::connect — Connects to a database server
  • Mongo::connectUtil — Connects with a database server
  • Mongo::__construct — Creates a new database connection object
  • Mongo::dropDB — Drops a database
  • Mongo::forceError — Creates a database error on the database [deprecated]
  • Mongo::__get — Gets a database
  • Mongo::lastError — Check if there was an error on the most recent db operation performed [deprecated]
  • Mongo::listDBs — Lists all of the databases available.
  • Mongo::pairConnect — Connects to paired database server [deprecated]
  • Mongo::pairPersistConnect — Creates a persistent connection with paired database servers [deprecated]
  • Mongo::persistConnect — Creates a persistent connection with a database server [deprecated]
  • Mongo::prevError — Checks for the last error thrown during a database operation [deprecated]
  • Mongo::resetError — Clears any flagged errors on the connection [deprecated]
  • Mongo::selectCollection — Gets a database collection
  • Mongo::selectDB — Gets a database
  • Mongo::__toString — String representation of this connection
Core Classes
Mongo::close
Core Classes


The MongoBinData class

Introduction

An object that can be used to store or retrieve binary data from the database.

The maximum size of a single object that can be inserted into the database is 4Mb. For data that is larger than this (movies, music, Henry Kissinger's autobiography), use MongoGridFS. For data that is smaller than 4Mb, it's probably be easier to just embed it into the document using MongoBinData.

For example, to embed an image in a document, one could write:

<?php

$profile = array("username" => "foobity",
    "pic" => new MongoBinData(get_file_contents("gravatar.jpg"));

$users->save($profile);

?>

This class contains a type field, which currently gives no additional functionality in the driver or the database. There are five predefined types (which are the class constants listed below), and the user can create their own (at the risk of the BSON spec catching up with them). By default, the PHP driver always uses type 2: a byte array.

Class synopsis

MongoBinData
MongoBinData {
/* Constants */
const int MongoBinData::FUNC = 1 ;
const int MongoBinData::BYTE_ARRAY = 2 ;
const int MongoBinData::UUID = 3 ;
const int MongoBinData::MD5 = 5 ;
const int MongoBinData::CUSTOM = 128 ;
/* Fields */
public string $bin ;
public int $type = 2 ;
/* Methods */
public __construct ( string $data [, int $type ] )
public string __toString ( void )
}

Predefined Constants

Binary Data Types

MongoBinData::FUNC
0x01
Function.
MongoBinData::BYTE_ARRAY
0x02
Array of bytes.
MongoBinData::UUID
0x03
Universally unique identifier.
MongoBinData::MD5
0x05
MD5.
MongoBinData::CUSTOM
0xf0
User-defined type.

Table of Contents

  • MongoBinData::__construct — Creates a new binary data object.
  • MongoBinData::__toString — The string representation of this binary data object.
MongoRegex::__toString
MongoBinData::__construct
Types


The MongoCode class

Introduction

Represents JavaScript code for the database.

MongoCode objects are composed of two parts: a string of code and an optional scope. The string of code must be valid JavaScript. The scope is a associative array of variable name/value pairs.

Class synopsis

MongoCode
MongoCode {
/* Methods */
__construct ( string $code [, array $scope = array() ] )
public string __toString ( void )
}

Table of Contents

  • MongoCode::__construct — Creates a new code object
  • MongoCode::__toString — Returns this code as a string
MongoId::__toString
MongoCode::__construct
Types


The MongoCollection class

Introduction

Representations a database collection.

Collection names can use any character in the ASCII set. Some valid collection names are "", "...", "my collection", and "*&#@".

Class synopsis

MongoCollection
MongoCollection {
/* Fields */
public MongoDB $db = NULL ;
/* Methods */
public boolean batchInsert ( array $a )
public __construct ( MongoDB $db , string $name )
public int count ([ mixed $query = array() ] )
public array createDBRef ( array $a )
public array deleteIndex ( string|array $keys )
public array deleteIndexes ( void )
public array drop ( void )
public boolean ensureIndex ( array $keys , array $options )
public MongoCursor find ([ array $query = array() [, array $fields = array() ]] )
public array findOne ([ array $query = array() [, array $fields = array() ]] )
public MongoCollection __get ( string $name )
public array getDBRef ( array $ref )
public array getIndexInfo ( void )
public string getName ( void )
public array group ( array $keys , array $initial , string $reduce [, array $condition = array() ] )
public mixed insert ( array $a [, boolean $safe = false ] )
public boolean remove ( array $criteria [, boolean $justOne = FALSE ] )
public boolean save ( array $a )
public string __toString ( void )
public boolean update ( array $criteria , array $newobj [, array $options = NULL ] )
public array validate ([ bool $scan_data = FALSE ] )
}

See Also

MongoDB core docs on » collections.

Table of Contents

  • MongoCollection::batchInsert — Inserts multiple documents into this collection
  • MongoCollection::__construct — Creates a new collection
  • MongoCollection::count — Counts the number of documents in this collection
  • MongoCollection::createDBRef — Creates a database reference
  • MongoCollection::deleteIndex — Deletes an index from this collection
  • MongoCollection::deleteIndexes — Delete all indices for this collection
  • MongoCollection::drop — Drops this collection
  • MongoCollection::ensureIndex — Creates an index on the given field(s), or does nothing if the index already exists
  • MongoCollection::find — Querys this collection
  • MongoCollection::findOne — Querys this collection, returning a single element
  • MongoCollection::__get — Gets a collection
  • MongoCollection::getDBRef — Fetches the document pointed to by a database reference
  • MongoCollection::getIndexInfo — Returns an array of index names for this collection
  • MongoCollection::getName — Returns this collection's name
  • MongoCollection::group — Performs an operation similar to SQL's GROUP BY command
  • MongoCollection::insert — Inserts an array into the collection
  • MongoCollection::remove — Remove records from this collection
  • MongoCollection::save — Saves an object to this collection
  • MongoCollection::__toString — String representation of this collection
  • MongoCollection::update — Update records based on a given criteria
  • MongoCollection::validate — Validates this collection
MongoDB::__toString
MongoCollection::batchInsert
Core Classes


The MongoConnectionException class

Introduction

Thrown when the driver fails to connect to the database.

There are a number of possible error messages to help you diagnose the connection problem. These are:

  • No server name given.

    This error occurs if you pass in "" as the server name, probably because of an typo with string interpolation, e.g., "$servr" instead of "$server".

  • failed to get left host [hostname] or port [portnum] from [server].

    failed to get right host [hostname] or port [portnum] from [server].

    This indicated that the first or second server respectively in a "server1,server2" connection string was malformed. "[hostname]" and "[portnum]" will be as much as the driver could dicipher of it.

  • failed to get host [hostname] or port [portnum] from [server].

    This indicated that the server string was malformed. "[hostname]" and "[portnum]" will be as much as the driver could dicipher of it.

  • paired connection, but no right host given

    The user attempted to create a paired connection but passed a string that only listed one server to connect to.

  • Operation in progress

    Connecting to the database timed out.

  • More links than your body has room for: N of M

    N is the number of open connections and M is the maximum number of connections allowed. By default, the driver allows unlimited simultaneous connections to the database. If you wish to limit them, you can set mongo.max_connections and/or mongo.max_persistent (for limiting perisistent connections). If you try to create more than that number of connections, you will get this error.

  • couldn't determine master

    Neither server in a paired connection appeared to be master.

  • couldn't get host info for [server]

    This indicated that DNS could not resolve the server address you gave. This could easily be caused by a typo, for example, "server" instead of "$server".

If the error message is not listed above, it is probably an error from the C socket, and you can search the web for its usual cause.

Class synopsis

MongoConnectionException
extends MongoException {
}
MongoCursorTimeoutException
MongoGridFSException
Exceptions


The MongoCursor class

Introduction

Result object for database query.

A MongoCursor has two "life stages": pre- and post- query. A cursor can be created manually by calling the constructor, but it is most often created by calling MongoCollection::find(). When a cursor is created, it has not yet contacted the database, so it is in its pre-query state. In this state, the client can further specify what they want the query to do, including adding limits, skips, sorts, and more advanced options.

When the client attempts to get a result (by calling MongoCursor::next(), directly or indirectly), the cursor moves into the post-query stage. At this point, the query has been executed by the database and cannot be modified anymore. At this point, the only functions available are the Iterator functions, MongoCursor::hasNext(), and MongoCursor::getNext().

<?php
$cursor = $collection->find()->limit(10);

// database has not yet been queried, so more search options can be added
$cursor = $cursor->sort(array("a" => 1));

var_dump($cursor->getNext());
// now database has been queried and more options cannot be added

// so this will throw an exception:
$cursor->skip(4);
?>

Class synopsis

MongoCursor
implements Iterator {
/* Static Fields */
static boolean $slaveOkay = FALSE ;
/* Methods */
public MongoCursor addOption ( string $key , mixed $value )
__construct ( resource $connection , string $ns [, array $query = array() [, array $fields = array() ]] )
public int count ([ boolean $all = FALSE ] )
public array current ( void )
public boolean dead ( void )
protected void doQuery ( void )
public array explain ( void )
public array getNext ( void )
public boolean hasNext ( void )
public MongoCursor hint ( array $key_pattern )
public MongoCursor immortal ([ boolean $liveForever = true ] )
public string key ( void )
public MongoCursor limit ( int $num )
public void next ( void )
public void reset ( void )
public void rewind ( void )
public MongoCursor skip ( int $num )
public MongoCursor slaveOkay ([ boolean $okay = true ] )
public MongoCursor snapshot ( void )
public MongoCursor sort ( array $fields )
public MongoCursor tailable ([ boolean $tail = true ] )
public MongoCursor timeout ( int $ms )
public boolean valid ( void )
}

See Also

MongoDB core docs on » cursors.

Table of Contents

  • MongoCursor::addOption — Adds a top-level key/value pair to a query
  • MongoCursor::__construct — Create a new cursor
  • MongoCursor::count — Counts the number of results for this query
  • MongoCursor::current — Returns the current element
  • MongoCursor::dead — Checks if there are documents that have not been sent yet from the database for this cursor
  • MongoCursor::doQuery — Execute the query.
  • MongoCursor::explain — Return an explanation of the query, often useful for optimization and debugging
  • MongoCursor::getNext — Return the next object to which this cursor points, and advance the cursor
  • MongoCursor::hasNext — Checks if there are any more elements in this cursor
  • MongoCursor::hint — Gives the database a hint about the query
  • MongoCursor::immortal — Sets whether this cursor will timeout
  • MongoCursor::key — Returns the current result's _id
  • MongoCursor::limit — Limits the number of results returned
  • MongoCursor::next — Advances the cursor to the next result
  • MongoCursor::reset — Clears the cursor
  • MongoCursor::rewind — Returns the cursor to the beginning of the result set
  • MongoCursor::skip — Skips a number of results
  • MongoCursor::slaveOkay — Sets whether this query can be done on a slave
  • MongoCursor::snapshot — Use snapshot mode for the query
  • MongoCursor::sort — Sorts the results by given fields
  • MongoCursor::tailable — Sets whether this cursor will be left open after fetching the last results
  • MongoCursor::timeout — Sets a client-side timeout for this query
  • MongoCursor::valid — Checks if the cursor is reading a valid result.
MongoCollection::validate
MongoCursor::addOption
Core Classes


The MongoCursorException class

Introduction

Caused by accessing a cursor incorrectly or a error receiving a reply.

If there is an error receiving a reply, there will be a more specific error message to help diagnose the problem:

  • could not establish db connection

    A database reply could not be recieved because a connection with the database could not be established.

  • no db response

    This may not even be an error, for example, the database command "shutdown" returns no response. However, if you were expecting a response, this means the database didn't give one.

  • bad response length: %d, max: %d, did the db assert?

    This means that the database said that its response was greater than 4Mb or less than 0. Generally, a number greater than 5Mb should be reported to the developers as a potential database bug (max response length is 4Mb). A response of less than 0 often means a database assertion occured.

  • incomplete response

    Occurs if the database response started out correctly, but broke off in the middle.

  • error getting database response: errstr

    WSA error getting database response: errstr

    "errstr" is an io error reported directly from the C socket subsystem. On Windows, the error message is prefixed with "WSA".

Class synopsis

MongoCursorException
extends MongoException {
}
MongoException
MongoCursorTimeoutException
Exceptions


The MongoCursorTimeoutException class

Introduction

Caused by a query timing out. At the moment, the only way a query will not wait indefinitely for a database response is if MongoCursor::timeout() is called on the cursor.

Class synopsis

MongoCursorTimeoutException
extends MongoCursorException {
}
MongoCursorException
MongoConnectionException
Exceptions


The MongoDate class

Introduction

Represent date objects for the database. This class should be used to save dates to the database and to query for dates. For example:

<?php

// save a date to the database
$collection->save(array("ts" => new MongoDate());

$start = new MongoDate(strtotime("2010-01-15 00:00:00"));
$end = new MongoDate(strtotime("2010-01-30 00:00:00"));

// find dates between 1/15/2010 and 1/30/2010
$collection->find(array("ts" => array('$gt' => $start, '$lte' => $end)));

?>

Class synopsis

MongoDate
MongoDate {
/* Fields */
public int $sec ;
public int $usec ;
/* Methods */
__construct ([ long $sec [, long $usec ]] )
publicstring __toString ( void )
}

Table of Contents

  • MongoDate::__construct — Creates a new date.
  • MongoDate::__toString — Returns a string representation of this date
MongoCode::__toString
MongoDate::__construct
Types


The MongoDB class

Introduction

Instances of this class are used to interact with a database. To get a database:

<?php
$m = new Mongo(); // connect
$db = $m->selectDB("example");
?>
Database names can use almost any character in the ASCII range. However, they cannot contain " ", "." or be the empty string.

A few unusual, but valid, database names: "null", "[x,y]", "3", "\"", "/".

Unlike collection names, database names may contain "$".

Class synopsis

MongoDB
MongoDB {
/* Constants */
const int MongoDB::PROFILING_OFF = 0 ;
const int MongoDB::PROFILING_SLOW = 1 ;
const int MongoDB::PROFILING_ON = 2 ;
/* Methods */
public array authenticate ( string $username , string $password )
public array command ( array $data )
__construct ( Mongo $conn , string $name )
public MongoCollection createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )
public array createDBRef ( string $collection , mixed $a )
public array drop ( void )
public array dropCollection ( mixed $coll )
public array execute ( mixed $code [, array $args = array() ] )
public bool forceError ( void )
public MongoCollection __get ( string $name )
public array getDBRef ( array $ref )
public MongoGridFS getGridFS ([ string $prefix = "fs" ] )
public int getProfilingLevel ( void )
public array lastError ( void )
public array listCollections ( void )
public array prevError ( void )
public array repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] )
public array resetError ( void )
public MongoCollection selectCollection ( string $name )
public int setProfilingLevel ( int $level )
public string __toString ( void )
}

Predefined Constants

MongoDB Log Levels

MongoDB::PROFILING_OFF
0
Profiling is off.
MongoDB::PROFILING_SLOW
1
Profiling is on for slow operations (>100 ms).
MongoDB::PROFILING_ON
2
Profiling is on for all operations.

See Also

MongoDB core docs on » databases.

Table of Contents

  • MongoDB::authenticate — Log in to this database
  • MongoDB::command — Execute a database command
  • MongoDB::__construct — Creates a new database
  • MongoDB::createCollection — Creates a collection
  • MongoDB::createDBRef — Creates a database reference
  • MongoDB::drop — Drops this database
  • MongoDB::dropCollection — Drops a collection
  • MongoDB::execute — Runs JavaScript code on the database server.
  • MongoDB::forceError — Creates a database error
  • MongoDB::__get — Gets a collection
  • MongoDB::getDBRef — Fetches the document pointed to by a database reference
  • MongoDB::getGridFS — Fetches toolkit for dealing with files stored in this database
  • MongoDB::getProfilingLevel — Gets this database's profiling level
  • MongoDB::lastError — Check if there was an error on the most recent db operation performed
  • MongoDB::listCollections — Get a list of collections in this database
  • MongoDB::prevError — Checks for the last error thrown during a database operation
  • MongoDB::repair — Repairs and compacts this database
  • MongoDB::resetError — Clears any flagged errors on the database
  • MongoDB::selectCollection — Gets a collection
  • MongoDB::setProfilingLevel — Sets this database's profiling level
  • MongoDB::__toString — The name of this database
Mongo::__toString
MongoDB::authenticate
Core Classes


The MongoDBRef class

Introduction

This class can be used to create lightweight links between objects in different collections.

Motivation: Suppose we need to refer to a document in another collection. The easiest way is to create a field in the current document. For example, if we had a "people" collection and an "addresses" collection, we might want to create a link between each person document and and address document:

<?php

$people = $db->people;
$addresses = $db->addresses;

$myAddress = array("line 1" => "123 Main Street",
    "line 2" => null,
    "city" => "Springfield",
    "state" => "Vermont",
    "country" => "USA");

// save the address
$addresses->insert($myAddress);

// save a person with a reference to the address
$me = array("name" => "Fred", "address" => $myAddress['_id']);
$people->insert($me);

?>

Then, later on, we can find the person's address by querying the "addresses" collection with the MongoId we saved in the "people" collection.

Suppose now that we have a more general case, where we don't know which collection (or even which database) contains the referenced document. MongoDBRef is a good choice for this case, as it is a common format that all of the drivers and the database understand.

If each person had a list of things they liked which could come from multiple collections, such as "hobbies", "sports", "books", etc., we could use MongoDBRefs to keep track of what "like" went with what collection:

<?php

$people = $db->selectCollection("people");

// model trains are in the "hobbies" collection
$trainRef = MongoDBRef::create("hobbies", $modelTrains['_id']);
// soccer is in the "sports" collection
$soccerRef = MongoDBRef::create("sports", $soccer['_id']);

// now we'll know what collections the items in the "likes" array came from when
// we retrieve this document
$people->insert(array("name" => "Fred", "likes" => array($trainRef, $soccerRef)));

?>

Class synopsis

MongoDBRef
MongoDBRef {
/* Methods */
public static array create ( string $collection , mixed $id [, string $database ] )
public static array get ( MongoDB $db , array $ref )
public static boolean isRef ( mixed $ref )
}

See Also

MongoDB core docs on » databases references.

Table of Contents

  • MongoDBRef::create — Creates a new database reference
  • MongoDBRef::get — Fetches the object pointed to by a reference
  • MongoDBRef::isRef — Checks if an array is a database reference
MongoBinData::__toString
MongoDBRef::create
Types


The MongoException class

Introduction

Default Mongo exception.

Class synopsis

MongoException
extends Exception {
}
Exceptions
MongoCursorException
Exceptions


The MongoGridFS class

Introduction

Utilities for storing and retrieving files from the database.

GridFS is a storage specification all supported drivers implement. Basically, it defines two collections: files, for file metadata, and chunks, for file content. If the file is large, it will automatically be split into smaller chunks and each chunk will be saved as a document in the chunks collection.

Each document in the files collection contains the filename, upload date, and md5 hash. It also contains a unique _id field, which can be used to query the chunks collection for the file's content. Each document in the chunks collection contains a chunk of binary data, a files_id field that matches its file's _id, and the position of this chunk in the overall file.

For example, the files document is something like:

array("_id" => 123456789, "filename" => "foo.txt", "chunkSize" => 3, "length" => 12)

and the chunks documents look like:

array("files_id" => 123456789, "n" => 0, "data" => new MongoBinData("abc"));
array("files_id" => 123456789, "n" => 1, "data" => new MongoBinData("def"));
array("files_id" => 123456789, "n" => 2, "data" => new MongoBinData("ghi"));
array("files_id" => 123456789, "n" => 3, "data" => new MongoBinData("jkl"));

Of course, the default chunk size is thousands of bytes, but that makes an unweildy example.

The MongoGridFS Family

MongoGridFS represents the files and chunks collections. MongoGridFS extends MongoCollection, and an instance of MongoGridFS has access to all of MongoCollection methods, which act on the files collection:

<?php

$grid = $db->getGridFS();
$grid->update(array("filename" => "foo"), $newObj)); // update on the files collection

?>

Another example of manipulating metadata:

<?php

// save a file
$id = $grid->storeFile("game.tgz");
$game = $grid->findOne();

// add a downloads counter
$game->file['downloads'] = 0;
$grid->save($game->file);

// increment the counter
$grid->update(array("_id" => $id), array('$inc' => array("downloads" => 1)));

?>

You can also access the chunks collection from an instance of MongoGridFS:

<?php

  $chunks = $grid->chunks; // $chunks is a normal MongoCollection
$chunks->insert(array("x" => 4));

?>

There are some methods for MongoGridFS with the same name as MongoCollection methods, that behave slightly differently. For example, MongoGridFS::remove() will remove any objects that match the criteria from the files collection and their content from the chunks collection.

To store something new in GridFS, there are a couple options. If you have a filename, you can say:

<?php

$grid->storeFile($filename, array("whatever" => "metadata", "you" => "want"));

?>

If you have a string of bytes that isn't a file, you can also store that using MongoGridFS::storeBytes():

<?php

$grid->storeBytes($bytes, array("whatever" => "metadata", "you" => "want");

?>

Querying a MongoGridFS collection returns a MongoGridFSCursor, which behaves like a normal MongoCursor except that it returns MongoGridFSFiles instead of associative arrays.

MongoGridFSFiles can be written back to disc using MongoGridFSFile::write() or retrieved in memory using MongoGridFSFile::getBytes(). There is currently no method that automatically streams chunks, but it would be fairly easy to write by querying the $grid->chunks collection.

MongoGridFSFile objects contain a field file which contains any file metadata.

Class synopsis

MongoGridFS
extends MongoCollection {
/* Fields */
public MongoCollection $chunks = NULL ;
protected string $filesName = NULL ;
protected string $chunksName = NULL ;
/* Methods */
__construct ( MongoDB $db [, string $prefix = "fs" ] )
public array drop ( void )
public MongoGridFSCursor find ([ array $query = array() [, array $fields = array() ]] )
public MongoGridFSFile findOne ([ mixed $query = array() ] )
public boolean remove ([ array $criteria = array() [, boolean $just_one = FALSE ]] )
public mixed storeBytes ( string $bytes [, array $extra = array() ] )
public mixed storeFile ( string $filename [, array $extra = array() ] )
public mixed storeUpload ( string $name [, string $filename ] )
}

See Also

MongoDB core docs on » GridFS.

Table of Contents

  • MongoGridFS::__construct — Creates new file collections
  • MongoGridFS::drop — Drops the files and chunks collections
  • MongoGridFS::find — Queries for files
  • MongoGridFS::findOne — Returns a single file matching the criteria
  • MongoGridFS::remove — Removes files from the collections
  • MongoGridFS::storeBytes — Chunkifies and stores bytes in the database
  • MongoGridFS::storeFile — Stores a file in the database
  • MongoGridFS::storeUpload — Saves an uploaded file to the database
GridFS Classes
MongoGridFS::__construct
GridFS Classes


The MongoGridFSCursor class

Introduction

Cursor for database file results.

Class synopsis

MongoGridFSCursor
extends MongoCursor {
/* Fields */
protected MongoGridFS $gridfs = NULL ;
/* Methods */
__construct ( MongoGridFS $gridfs , resource $connection , string $ns [, array $query = array() [, array $fields = array() ]] )
public MongoGridFSFile current ( void )
public MongoGridFSFile getNext ( void )
public string key ( void )
}

Table of Contents

  • MongoGridFSCursor::__construct — Create a new cursor
  • MongoGridFSCursor::current — Returns the current file
  • MongoGridFSCursor::getNext — Return the next file to which this cursor points, and advance the cursor
  • MongoGridFSCursor::key — Returns the current result's filename
MongoGridFSFile::write
MongoGridFSCursor::__construct
GridFS Classes


The MongoGridFSException class

Introduction

Thrown when there are errors reading or writing files to or from the database.

Class synopsis

MongoGridFSException
extends MongoException {
}
MongoConnectionException
mSQL
Exceptions


The MongoGridFSFile class

Introduction

A database file object.

Class synopsis

MongoGridFSFile
MongoGridFSFile {
/* Fields */
public array $file = NULL ;
protected MongoGridFS $gridfs = NULL ;
/* Methods */
MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )
public string getBytes ( void )
public string getFilename ( void )
public int getSize ( void )
public int write ([ string $filename = NULL ] )
}

Table of Contents

  • MongoGridfsFile::__construct — Create a new GridFS file
  • MongoGridFSFile::getBytes — Returns this file's contents as a string of bytes
  • MongoGridFSFile::getFilename — Returns this file's filename
  • MongoGridFSFile::getSize — Returns this file's size
  • MongoGridFSFile::write — Writes this file to the filesystem
MongoGridFS::storeUpload
MongoGridfsFile::__construct
GridFS Classes


The MongoId class

Introduction

A unique identifier created for database objects. If an object is inserted into the database without an _id field, an _id field will be added to it with a MongoId instance as its value. If the data has a naturally occuring unique field (say, a username or timestamp) it is fine to use this as the _id field instead, and it will not be replaced with a MongoId.

Instances of the MongoId class fulfill the role that autoincrementing does in a relational database: to provide a unique key if the data does not natually have one. Autoincrementing does not work well with a sharded database, as it is impossible to find what the next number should be quickly. This class fulfills the constraints of quickly generating a value that is unique across shards.

Each MongoId is 12 bytes (making its string form 24 hexidecimal characters). The first four bytes are a timestamp, the next three are a hash of the client machine's hostname, the next two are the two least significant bytes of the process id running the script, and the last three bytes are an incrementing value.

MongoIds are serializable/unserializable. Their serialized form is similar to their string form:

C:7:"MongoId":24:{4af9f23d8ead0e1d32000000}

Class synopsis

MongoId
MongoId {
/* Methods */
__construct ([ string $id = NULL ] )
public int getTimestamp ( void )
public string __toString ( void )
}

See Also

MongoDB core docs on » ids.

Table of Contents

  • MongoId::__construct — Creates a new id
  • MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created
  • MongoId::__toString — Returns a hexidecimal representation of this id
Types
MongoId::__construct
Types


The MongoMaxKey class

Introduction

MongoMaxKey is a special type used by the database that evaluates to greater than any other type. Thus, if a query is sorted by a given field in ascending order, any document with a MongoMaxKey as its value will be returned last.

MongoMaxKey has no associated fields, methods, or constants. It is merely the "largest" thing that can be inserted into the database.

Class synopsis

MongoMaxKey
MongoMaxKey {
}

Using MongoMaxKey as a value

<?php

$collection->insert(array("task" => "dishes", "do by" => new MongoMaxKey));
$collection->insert(array("task" => "staff meeting", "do by" => new MongoDate(strtotime("+4 days")));

$cursor = $collection->find()->sort(array("do by" => 1));

?>

The cursor will contain the staff meeting document, then the dishes document. The dishes document will always be returned last, regardless of what else is added to the collection (unless other documents are added with MongoMaxKey in the "do by" field).

MongoMinKey
MongoTimestamp
Types


The MongoMinKey class

Introduction

MongoMinKey is a special type used by the database that evaluates to less than any other type. Thus, if a query is sorted by a given field in ascending order, any document with a MongoMinKey as its value will be returned first.

MongoMinKey has no associated fields, methods, or constants. It is merely the "smallest" thing that can be inserted into the database.

Class synopsis

MongoMinKey
MongoMinKey {
}

Using MongoMinKey as a value

<?php

$collection->insert(array("task" => "lunch", "do by" => new MongoMinKey));
$collection->insert(array("task" => "staff meeting", "do by" => new MongoDate(strtotime("+4 days")));

$cursor = $collection->find()->sort(array("do by" => 1));

?>

The cursor will contain the lunch document, then the staff meeting document. The lunch document will always be returned first, regardless of what else is added to the collection (unless other documents are added with MongoMinKey in the "do by" field).

MongoDBRef::isRef
MongoMaxKey
Types


The MongoRegex class

Introduction

This class can be used to create regular expressions. Typically, these expressions will be used to query the database and find matching strings. More unusually, they can be saved to the database and retrieved.

Mongo recognizes six regular expression flags:

  • i

    Case insensitive

  • m

    Multiline

  • x

    Can contain comments

  • l

    locale

  • s

    dotall, "." matches everything, including newlines

  • u

    match unicode

Class synopsis

MongoRegex
MongoRegex {
/* Fields */
public string $regex ;
public string $flags ;
/* Methods */
__construct ( string $regex )
public string __toString ( void )
}

Table of Contents

  • MongoRegex::__construct — Creates a new regular expression
  • MongoRegex::__toString — A string representation of this regular expression
MongoDate::__toString
MongoRegex::__construct
Types


The MongoTimestamp class

Introduction

MongoTimestamp is used by sharding. If you're not looking to write sharding tools, what you probably want is MongoDate.

MongoTimestamp is 4 bytes of timestamp (seconds since the epoch) and 4 bytes of increment.

This class is not for measuring time, creating a timestamp on a document or automatically adding or updating a timestamp on a document. Unless you are writing something that interacts with the sharding internals, stop, go directly to MongoDate, do not pass go, do not collect 200 dollars. This is not the class you are looking for.

If you are writing sharding tools, read on.

Class synopsis

MongoTimestamp
MongoTimestamp {
/* Fields */
public int $sec = 0 ;
public int $inc = 0 ;
/* Methods */
__construct ([ long $sec [, long $inc ]] )
publicstring __toString ( void )
}

Table of Contents

  • MongoTimestamp::__construct — Creates a new timestamp.
  • MongoTimestamp::__toString — Returns a string representation of this timestamp
MongoMaxKey
MongoTimestamp::__construct
Types


The KTagLib_MPEG_File class

Introduction

Represents an MPEG file. MPEG files can have ID3v1, ID3v2 tags and audio properties.

Class synopsis

KTagLib_MPEG_File
KTagLib_MPEG_File {
}

Table of Contents

  • KTaglib_MPEG_File::__construct — Opens a new file
  • KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties
  • KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag
  • KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object
Predefined Constants
KTaglib_MPEG_File::__construct
KTaglib


The MySQLi class

Introduction

Represents a connection between PHP and a MySQL database.

Class synopsis

MySQLi
MySQLi {
/* Properties */
int $affected_rows;
string $client_info;
int $client_version;
string $connect_errno;
string $connect_error;
int $errno;
string $error;
int $field_count;
int $client_version;
string $host_info;
string $protocol_version;
string $server_info;
int $server_version;
string $info;
mixed $insert_id;
string $sqlstate;
int $thread_id;
int $warning_count;
/* Methods */
int mysqli_affected_rows ( mysqli $link )
bool mysqli::autocommit ( bool $mode )
bool mysqli::change_user ( string $user , string $password , string $database )
string mysqli::character_set_name ( void )
string mysqli_get_client_info ( mysqli $link )
int mysqli_get_client_version ( mysqli $link )
bool mysqli::close ( void )
bool mysqli::commit ( void )
int mysqli_connect_errno ( void )
string mysqli_connect_error ( void )
 mysqli mysqli_connect
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] )
bool mysqli::debug ( string $message )
bool mysqli::dump_debug_info ( void )
int mysqli_errno ( mysqli $link )
string mysqli_error ( mysqli $link )
int mysqli_field_count ( mysqli $link )
object mysqli::get_charset ( void )
string mysqli::get_client_info ( void )
int mysqli_get_client_version ( mysqli $link )
bool mysqli::get_connection_stats ( void )
string mysqli_get_host_info ( mysqli $link )
int mysqli_get_proto_info ( mysqli $link )
string mysqli_get_server_info ( mysqli $link )
int mysqli_get_server_version ( mysqli $link )
mysqli_warnings mysqli::get_warnings ( void )
string mysqli_info ( mysqli $link )
mysqli mysqli::init ( void )
mixed mysqli_insert_id ( mysqli $link )
bool mysqli::kill ( int $processid )
bool mysqli::more_results ( void )
bool mysqli::multi_query ( string $query )
bool mysqli::next_result ( void )
bool mysqli::options ( int $option , mixed $value )
bool mysqli::ping ( void )
public int mysqli::poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )
mysqli_stmt mysqli::prepare ( string $query )
mixed mysqli::query ( string $query [, int $resultmode ] )
bool mysqli::real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )
string mysqli::escape_string ( string $escapestr )
bool mysqli::real_query ( string $query )
public mysqli_result mysqli::reap_async_query ( void )
bool mysqli::rollback ( void )
bool mysqli::select_db ( string $dbname )
bool mysqli::set_charset ( string $charset )
void mysqli_set_local_infile_default ( mysqli $link )
bool mysqli_set_local_infile_handler ( mysqli $link , callback $read_func )
string mysqli_sqlstate ( mysqli $link )
bool mysqli::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )
string mysqli::stat ( void )
mysqli_stmt stmt_init ( void )
mysqli_result mysqli::store_result ( void )
int mysqli_thread_id ( mysqli $link )
bool mysqli_thread_safe ( void )
mysqli_result mysqli::use_result ( void )
int mysqli_warning_count ( mysqli $link )
}

Table of Contents

  • mysqli->affected_rows — Gets the number of affected rows in a previous MySQL operation
  • mysqli::autocommit — Turns on or off auto-commiting database modifications
  • mysqli::change_user — Changes the user of the specified database connection
  • mysqli::character_set_name — Returns the default character set for the database connection
  • mysqli->client_info — Returns the MySQL client version as a string
  • mysqli->client_version — Get MySQL client info
  • mysqli::close — Closes a previously opened database connection
  • mysqli::commit — Commits the current transaction
  • mysqli->connect_errno — Returns the error code from last connect call
  • mysqli->connect_error — Returns a string description of the last connect error
  • mysqli::__construct — Open a new connection to the MySQL server
  • mysqli::debug — Performs debugging operations
  • mysqli::dump_debug_info — Dump debugging information into the log
  • mysqli->errno — Returns the error code for the most recent function call
  • mysqli->error — Returns a string description of the last error
  • mysqli->field_count — Returns the number of columns for the most recent query
  • mysqli::get_charset — Returns a character set object
  • mysqli->get_client_info — Returns the MySQL client version as a string
  • mysqli->client_version — Get MySQL client info
  • mysqli::get_connection_stats — Returns statistics about the client connection
  • mysqli->host_info — Returns a string representing the type of connection used
  • mysqli->protocol_version — Returns the version of the MySQL protocol used
  • mysqli->server_info — Returns the version of the MySQL server
  • mysqli->server_version — Returns the version of the MySQL server as an integer
  • mysqli::get_warnings — Get result of SHOW WARNINGS
  • mysqli->info — Retrieves information about the most recently executed query
  • mysqli::init — Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli->insert_id — Returns the auto generated id used in the last query
  • mysqli::kill — Asks the server to kill a MySQL thread
  • mysqli::more_results — Check if there are any more query results from a multi query
  • mysqli::multi_query — Performs a query on the database
  • mysqli::next_result — Prepare next result from multi_query
  • mysqli::options — Set options
  • mysqli::ping — Pings a server connection, or tries to reconnect if the connection has gone down
  • mysqli::poll — Poll connections
  • mysqli::prepare — Prepare a SQL statement for execution
  • mysqli::query — Performs a query on the database
  • mysqli::real_connect — Opens a connection to a mysql server
  • mysqli::real_escape_string — Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
  • mysqli::real_query — Execute an SQL query
  • mysqli::reap_async_query — Get result from async query
  • mysqli::rollback — Rolls back current transaction
  • mysqli::select_db — Selects the default database for database queries
  • mysqli::set_charset — Sets the default client character set
  • mysqli::set_local_infile_default — Unsets user defined handler for load local infile command
  • mysqli::set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command
  • mysqli->sqlstate — Returns the SQLSTATE error from previous MySQL operation
  • mysqli::ssl_set — Used for establishing secure connections using SSL
  • mysqli::stat — Gets the current system status
  • mysqli::stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare
  • mysqli::store_result — Transfers a result set from the last query
  • mysqli::thread_id — Returns the thread ID for the current connection
  • mysqli::thread_safe — Returns whether thread safety is given or not
  • mysqli::use_result — Initiate a result set retrieval
  • mysqli::warning_count — Returns the number of warnings from the last query for the given link
The MySQLi Extension Function Summary
mysqli->affected_rows
Mysqli


The MySQLi_Driver class

Introduction

MySQLi Driver.

Class synopsis

MySQLi_Driver
MySQLi_Driver {
/* Properties */
public readonly string $client_info ;
public readonly string $client_version ;
public readonly string $driver_version ;
public readonly string $embedded ;
public bool $reconnect ;
public int $report_mode ;
/* Methods */
void mysqli_driver::embedded_server_end ( void )
bool mysqli_driver::embedded_server_start ( bool $start , array $arguments , array $groups )
}

Properties

client_info

The Client API header version

client_version

The Client version

driver_version

The MySQLi Driver version

embedded

Wether MySQLi Embedded support is enabled

reconnect

Allow or prevent reconnect (see the mysqli.reconnect INI directive)

report_mode

Set to MYSQLI_REPORT_OFF, MYSQLI_REPORT_ALL or any combination of MYSQLI_REPORT_STRICT (throw Exceptions for errors), MYSQLI_REPORT_ERROR (report errors) and MYSQLI_REPORT_INDEX (errors regarding indexes).

Table of Contents

  • mysqli_driver::embedded_server_end — Stop embedded server
  • mysqli_driver::embedded_server_start — Initialize and start embedded server
mysqli_result->num_rows
mysqli_driver::embedded_server_end
Mysqli


The MySQLi_Result class

Introduction

Represents the result set obtained from a query against the database.

Class synopsis

MySQLi_Result
MySQLi_Result {
/* Properties */
int $current_field ;
int $field_count;
array $lengths;
int $num_rows;
/* Methods */
int mysqli_field_tell ( mysqli_result $result )
bool mysqli_result::data_seek ( int $offset )
mixed mysqli_result::fetch_all ([ int $resulttype = MYSQLI_NUM ] )
mixed mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] )
array mysqli_result::fetch_assoc ( void )
object mysqli_result::fetch_field_direct ( int $fieldnr )
object mysqli_result::fetch_field ( void )
array mysqli_result::fetch_fields ( void )
object mysqli_result::fetch_object ([ string $class_name [, array $params ]] )
mixed mysqli_result::fetch_row ( void )
int mysqli_num_fields ( mysqli_result $result )
bool mysqli_result::field_seek ( int $fieldnr )
void mysqli_result::free ( void )
array mysqli_fetch_lengths ( mysqli_result $result )
int mysqli_num_rows ( mysqli_result $result )
}

Table of Contents

  • mysqli_result->current_field — Get current field offset of a result pointer
  • mysqli_result::data_seek — Adjusts the result pointer to an arbitary row in the result
  • mysqli_result::fetch_all — Fetches all result rows as an associative array, a numeric array, or both
  • mysqli_result::fetch_array — Fetch a result row as an associative, a numeric array, or both
  • mysqli_result::fetch_assoc — Fetch a result row as an associative array
  • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
  • mysqli_result::fetch_field — Returns the next field in the result set
  • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
  • mysqli_result::fetch_object — Returns the current row of a result set as an object
  • mysqli_result::fetch_row — Get a result row as an enumerated array
  • mysqli_result->field_count — Get the number of fields in a result
  • mysqli_result::field_seek — Set result pointer to a specified field offset
  • mysqli_result::free — Frees the memory associated with a result
  • mysqli_result->lengths — Returns the lengths of the columns of the current row in the result set
  • mysqli_result->num_rows — Gets the number of rows in a result
mysqli_stmt::store_result
mysqli_result->current_field
Mysqli


The MySQLi_STMT class

Introduction

Represents a prepared statement.

Class synopsis

MySQLi_STMT
MySQLi_STMT {
/* Properties */
int $affected_rows;
int $errno;
string $error;
int $field_count;
int $insert_id;
int $num_rows;
int $param_count;
string $sqlstate;
/* Methods */
int mysqli_stmt_affected_rows ( mysqli_stmt $stmt )
int mysqli_stmt::attr_get ( int $attr )
bool mysqli_stmt::attr_set ( int $attr , int $mode )
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
bool mysqli_stmt::bind_result ( mixed &$var1 [, mixed &$... ] )
bool mysqli_stmt::close ( void )
void mysqli_stmt::data_seek ( int $offset )
int mysqli_stmt_errno ( mysqli_stmt $stmt )
string mysqli_stmt_error ( mysqli_stmt $stmt )
bool mysqli_stmt::execute ( void )
bool mysqli_stmt::fetch ( void )
int mysqli_stmt_field_count ( mysqli_stmt $stmt )
void mysqli_stmt::free_result ( void )
object mysqli_stmt::get_warnings ( mysqli_stmt $stmt )
mixed mysqli_stmt_insert_id ( mysqli_stmt $stmt )
int mysqli_stmt_num_rows ( mysqli_stmt $stmt )
int mysqli_stmt_param_count ( mysqli_stmt $stmt )
mixed mysqli_stmt::prepare ( string $query )
bool mysqli_stmt::reset ( void )
mysqli_result mysqli_stmt::result_metadata ( void )
bool mysqli_stmt::send_long_data ( int $param_nr , string $data )
string mysqli_stmt_sqlstate ( mysqli_stmt $stmt )
bool mysqli_stmt::store_result ( void )
}

Table of Contents

  • mysqli_stmt->affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • mysqli_stmt::attr_get — Used to get the current value of a statement attribute
  • mysqli_stmt::attr_set — Used to modify the behavior of a prepared statement
  • mysqli_stmt::bind_param — Binds variables to a prepared statement as parameters
  • mysqli_stmt::bind_result — Binds variables to a prepared statement for result storage
  • mysqli_stmt::close — Closes a prepared statement
  • mysqli_stmt::data_seek — Seeks to an arbitrary row in statement result set
  • mysqli_stmt->errno — Returns the error code for the most recent statement call
  • mysqli_stmt->error — Returns a string description for last statement error
  • mysqli_stmt::execute — Executes a prepared Query
  • mysqli_stmt::fetch — Fetch results from a prepared statement into the bound variables
  • mysqli_stmt->field_count — Returns the number of field in the given statement
  • mysqli_stmt::free_result — Frees stored result memory for the given statement handle
  • mysqli_stmt::get_warnings — Get result of SHOW WARNINGS
  • mysqli_stmt->insert_id — Get the ID generated from the previous INSERT operation
  • mysqli_stmt::num_rows — Return the number of rows in statements result set
  • mysqli_stmt->param_count — Returns the number of parameter for the given statement
  • mysqli_stmt::prepare — Prepare a SQL statement for execution
  • mysqli_stmt::reset — Resets a prepared statement
  • mysqli_stmt::result_metadata — Returns result set metadata from a prepared statement
  • mysqli_stmt::send_long_data — Send data in blocks
  • mysqli_stmt::sqlstate — Returns SQLSTATE error from previous statement operation
  • mysqli_stmt::store_result — Transfers a result set from a prepared statement
mysqli::warning_count
mysqli_stmt->affected_rows
Mysqli


The MySQLi_Warning class

Introduction

Represents a MySQL warning.

Class synopsis

mysqli_warning
mysqli_warning {
/* Properties */
public $message ;
public $sqlstate ;
public $errno ;
/* Methods */
__construct ( void )
public void next ( void )
}

Properties

message

Message string

sqlstate

SQL state

errno

Error number

Table of Contents

  • mysqli_warning::__construct — The __construct purpose
  • mysqli_warning::next — The next purpose
mysqli_driver::embedded_server_start
mysqli_warning::__construct
Mysqli


The Normalizer class

Introduction

Normalization is a process that involves transforming characters and sequences of characters into a formally-defined underlying representation. This process is most important when text needs to be compared for sorting and searching, but it is also used when storing text to ensure that the text is stored in a consistent representation.

The Unicode Consortium has defined a number of normalization forms reflecting the various needs of applications:

  • Normalization Form D (NFD) - Canonical Decomposition
  • Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
  • Normalization Form KD (NFKD) - Compatibility Decomposition
  • Normalization Form KC (NFKC) - Compatibility Decomposition followed by Canonical Composition

The different forms are defined in terms of a set of transformations on the text, transformations that are expressed by both an algorithm and a set of data files.

Class synopsis

Normalizer
Normalizer {
/* Methods */
static bool isNormalized ( string $input [, string $form = Normalizer::FORM_C ] )
static string normalize ( string $input [, string $form = Normalizer::FORM_C ] )
}

Predefined Constants

The following constants define the normalization form used by the normalizer:

Normalizer::FORM_C (string)
Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
Normalizer::FORM_D (string)
Normalization Form D (NFD) - Canonical Decomposition
Normalizer::FORM_KC (string)
Normalization Form KC (NFKC) - Compatibility Decomposition, followed by Canonical Composition
Normalizer::FORM_KD (string)
Normalization Form KD (NFKD) - Compatibility Decomposition
Normalizer::NONE (string)
No decomposition/composition
Normalizer::OPTION_DEFAULT (string)
Default normalization options

See Also

  • » Unicode Normalization
  • » Unicode Normalization FAQ
  • » ICU User Guide - Normalization
  • » ICU API Reference - Normalization

Table of Contents

  • Normalizer::isNormalized — Checks if the provided string is already in the specified normalization form.
  • Normalizer::normalize — Normalizes the input provided and returns the normalized string
Locale::setDefault
Normalizer::isNormalized
intl


The NumberFormatter class

Introduction

Programs store and operate on numbers using a locale-independent binary representation. When displaying or printing a number it is converted to a locale-specific string. For example, the number 12345.67 is "12,345.67" in the US, "12 345,67" in France and "12.345,67" in Germany.

By invoking the methods provided by the NumberFormatter class, you can format numbers, currencies, and percentages according to the specified or default locale. NumberFormatter is locale-sensitive so you need to create a new NumberFormatter for each locale. NumberFormatter methods format primitive-type numbers, such as double and output the number as a locale-specific string.

For currencies you can use currency format type to create a formatter that returns a string with the formatted number and the appropriate currency sign. Of course, the NumberFormatter class is unaware of exchange rates so, the number output is the same regardless of the specified currency. This means that the same number has different monetary values depending on the currency locale. If the number is 9988776.65 the results will be:

  • 9 988 776,65 € in France
  • 9.988.776,65 € in Germany
  • $9,988,776.65 in the United States

In order to format percentages, create a locale-specific formatter with percentage format type. With this formatter, a decimal fraction such as 0.75 is displayed as 75%.

For more complex formatting, like spelled-out numbers, the rule-based number formatters are used.

Class synopsis

NumberFormatter
NumberFormatter {
/* Methods */
__construct ( string $locale , int $style [, string $pattern ] )
static NumberFormatter create ( string $locale , int $style [, string $pattern ] )
string formatCurrency ( float $value , string $currency )
string format ( number $value [, int $type ] )
int getAttribute ( int $attr )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ([ int $type ] )
string getPattern ( void )
string getSymbol ( int $attr )
string getTextAttribute ( int $attr )
float parseCurrency ( string $value , string &$currency [, int &$position ] )
mixed parse ( string $value [, int $type [, int &$position ]] )
bool setAttribute ( int $attr , int $value )
bool setPattern ( string $pattern )
bool setSymbol ( int $attr , string $value )
bool setTextAttribute ( int $attr , string $value )
}

Predefined Constants

These styles are used by the numfmt_create() to define the type of the formatter.

NumberFormatter::PATTERN_DECIMAL (integer)
Decimal format defined by pattern
NumberFormatter::DECIMAL (integer)
Decimal format
NumberFormatter::CURRENCY (integer)
Currency format
NumberFormatter::PERCENT (integer)
Percent format
NumberFormatter::SCIENTIFIC (integer)
Scientific format
NumberFormatter::SPELLOUT (integer)
Spellout rule-based format
NumberFormatter::ORDINAL (integer)
Ordinal rule-based format
NumberFormatter::DURATION (integer)
Duration rule-based format
NumberFormatter::PATTERN_RULEBASED (integer)
Rule-based format defined by pattern
NumberFormatter::DEFAULT_STYLE (integer)
Default format for the locale
NumberFormatter::IGNORE (integer)
Alias for PATTERN_DECIMAL

These constants define how the numbers are parsed or formatted. They should be used as arguments to numfmt_format() and numfmt_parse().

NumberFormatter::TYPE_DEFAULT (integer)
Derive the type from variable type
NumberFormatter::TYPE_INT32 (integer)
Format/parse as 32-bit integer
NumberFormatter::TYPE_INT64 (integer)
Format/parse as 64-bit integer
NumberFormatter::TYPE_DOUBLE (integer)
Format/parse as floating point value
NumberFormatter::TYPE_CURRENCY (integer)
Format/parse as currency value

Number format attribute used by numfmt_get_attribute() and numfmt_set_attribute() .

NumberFormatter::PARSE_INT_ONLY (integer)
Parse integers only.
NumberFormatter::GROUPING_USED (integer)
Use grouping separator.
NumberFormatter::DECIMAL_ALWAYS_SHOWN (integer)
Always show decimal point.
NumberFormatter::MAX_INTEGER_DIGITS (integer)
Maximum integer digits.
NumberFormatter::MIN_INTEGER_DIGITS (integer)
Minimum integer digits.
NumberFormatter::INTEGER_DIGITS (integer)
Integer digits.
NumberFormatter::MAX_FRACTION_DIGITS (integer)
Maximum fraction digits.
NumberFormatter::MIN_FRACTION_DIGITS (integer)
Minimum fraction digits.
NumberFormatter::FRACTION_DIGITS (integer)
Fraction digits.
NumberFormatter::MULTIPLIER (integer)
Multiplier.
NumberFormatter::GROUPING_SIZE (integer)
Grouping size.
NumberFormatter::ROUNDING_MODE (integer)
Rounding Mode.
NumberFormatter::ROUNDING_INCREMENT (integer)
Rounding increment.
NumberFormatter::FORMAT_WIDTH (integer)
The width to which the output of format() is padded.
NumberFormatter::PADDING_POSITION (integer)
The position at which padding will take place. See pad position constants for possible argument values.
NumberFormatter::SECONDARY_GROUPING_SIZE (integer)
Secondary grouping size.
NumberFormatter::SIGNIFICANT_DIGITS_USED (integer)
Use significant digits.
NumberFormatter::MIN_SIGNIFICANT_DIGITS (integer)
Minimum significant digits.
NumberFormatter::MAX_SIGNIFICANT_DIGITS (integer)
Maximum significant digits.
NumberFormatter::LENIENT_PARSE (integer)
Lenient parse mode used by rule-based formats.

Number format text attribute used by numfmt_get_text_attribute() and numfmt_set_text_attribute().

NumberFormatter::POSITIVE_PREFIX (integer)
Positive prefix.
NumberFormatter::POSITIVE_SUFFIX (integer)
Positive suffix.
NumberFormatter::NEGATIVE_PREFIX (integer)
Negative prefix.
NumberFormatter::NEGATIVE_SUFFIX (integer)
Negative suffix.
NumberFormatter::PADDING_CHARACTER (integer)
The character used to pad to the format width.
NumberFormatter::CURRENCY_CODE (integer)
The ISO currency code.
NumberFormatter::DEFAULT_RULESET (integer)
The default rule set. This is only available with rule-based formatters.
NumberFormatter::PUBLIC_RULESETS (integer)
The public rule sets. This is only available with rule-based formatters. This is a read-only attribute. The public rulesets are returned as a single string, with each ruleset name delimited by ';' (semicolon).

Number format symbols used by numfmt_get_symbol() and numfmt_set_symbol().

NumberFormatter::DECIMAL_SEPARATOR_SYMBOL (integer)
The decimal separator.
NumberFormatter::GROUPING_SEPARATOR_SYMBOL (integer)
The grouping separator.
NumberFormatter::PATTERN_SEPARATOR_SYMBOL (integer)
The pattern separator.
NumberFormatter::PERCENT_SYMBOL (integer)
The percent sign.
NumberFormatter::ZERO_DIGIT_SYMBOL (integer)
Zero.
NumberFormatter::DIGIT_SYMBOL (integer)
Character representing a digit in the pattern.
NumberFormatter::MINUS_SIGN_SYMBOL (integer)
The minus sign.
NumberFormatter::PLUS_SIGN_SYMBOL (integer)
The plus sign.
NumberFormatter::CURRENCY_SYMBOL (integer)
The currency symbol.
NumberFormatter::INTL_CURRENCY_SYMBOL (integer)
The international currency symbol.
NumberFormatter::MONETARY_SEPARATOR_SYMBOL (integer)
The monetary separator.
NumberFormatter::EXPONENTIAL_SYMBOL (integer)
The exponential symbol.
NumberFormatter::PERMILL_SYMBOL (integer)
Per mill symbol.
NumberFormatter::PAD_ESCAPE_SYMBOL (integer)
Escape padding character.
NumberFormatter::INFINITY_SYMBOL (integer)
Infinity symbol.
NumberFormatter::NAN_SYMBOL (integer)
Not-a-number symbol.
NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL (integer)
Significant digit symbol.
NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL (integer)
The monetary grouping separator.

Rounding mode values used by numfmt_get_attribute()
and numfmt_set_attribute() with
NumberFormatter::ROUNDING_MODE attribute.

NumberFormatter::ROUND_CEILING (integer)
Rounding mode to round towards positive infinity.
NumberFormatter::ROUND_DOWN (integer)
Rounding mode to round towards zero.
NumberFormatter::ROUND_FLOOR (integer)
Rounding mode to round towards negative infinity.
NumberFormatter::ROUND_HALFDOWN (integer)
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
NumberFormatter::ROUND_HALFEVEN (integer)
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
NumberFormatter::ROUND_HALFUP (integer)
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
NumberFormatter::ROUND_UP (integer)
Rounding mode to round away from zero.

Pad position values used by numfmt_get_attribute()
and numfmt_set_attribute() with
NumberFormatter::PADDING_POSITION attribute.

NumberFormatter::PAD_AFTER_PREFIX (integer)
Pad characters inserted after the prefix.
NumberFormatter::PAD_AFTER_SUFFIX (integer)
Pad characters inserted after the suffix.
NumberFormatter::PAD_BEFORE_PREFIX (integer)
Pad characters inserted before the prefix.
NumberFormatter::PAD_BEFORE_SUFFIX (integer)
Pad characters inserted before the suffix.

See Also

  • » ICU formatting documentation
  • » ICU number formatters
  • » ICU decimal formatters
  • » ICU rule-based number formatters

Table of Contents

  • NumberFormatter::create — Create a number formatter
  • NumberFormatter::formatCurrency — Format a currency value
  • NumberFormatter::format — Format a number
  • NumberFormatter::getAttribute — Get an attribute
  • NumberFormatter::getErrorCode — Get formatter's last error code.
  • NumberFormatter::getErrorMessage — Get formatter's last error message.
  • NumberFormatter::getLocale — Get formatter locale
  • NumberFormatter::getPattern — Get formatter pattern
  • NumberFormatter::getSymbol — Get a symbol value
  • NumberFormatter::getTextAttribute — Get a text attribute
  • NumberFormatter::parseCurrency — Parse a currency number
  • NumberFormatter::parse — Parse a number
  • NumberFormatter::setAttribute — Set an attribute
  • NumberFormatter::setPattern — Set formatter pattern
  • NumberFormatter::setSymbol — Set a symbol value
  • NumberFormatter::setTextAttribute — Set a text attribute
Collator::sort
NumberFormatter::create
intl


The PDO class

Introduction

Represents a connection between PHP and a database server.

Class synopsis

PDO
PDO {
__construct ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )
bool beginTransaction ( void )
bool commit ( void )
mixed errorCode ( void )
array errorInfo ( void )
int exec ( string $statement )
mixed getAttribute ( int $attribute )
array getAvailableDrivers ( void )
string lastInsertId ([ string $name = NULL ] )
PDOStatement prepare ( string $statement [, array $driver_options = array() ] )
PDOStatement query ( string $statement )
string quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )
bool rollBack ( void )
bool setAttribute ( int $attribute , mixed $value )
}

Table of Contents

  • PDO::beginTransaction — Initiates a transaction
  • PDO::commit — Commits a transaction
  • PDO::__construct — Creates a PDO instance representing a connection to a database
  • PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
  • PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
  • PDO::exec — Execute an SQL statement and return the number of affected rows
  • PDO::getAttribute — Retrieve a database connection attribute
  • PDO::getAvailableDrivers — Return an array of available PDO drivers
  • PDO::lastInsertId — Returns the ID of the last inserted row or sequence value
  • PDO::prepare — Prepares a statement for execution and returns a statement object
  • PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object
  • PDO::quote — Quotes a string for use in a query.
  • PDO::rollBack — Rolls back a transaction
  • PDO::setAttribute — Set an attribute
Large Objects (LOBs)
PDO::beginTransaction
PDO


The PDOException class

Introduction

Represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about Exceptions in PHP.

Class synopsis

PDOException
PDOException extends RuntimeException {
/* Properties */
public array $errorInfo ;
protected string $message ;
protected string $code ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public int Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Properties

errorInfo

Corresponds to PDO::errorInfo() or PDOStatement::errorInfo()

message

Textual error message. Exception::getMessage() to access it.

code

SQLSTATE error code. Use Exception::getCode() to access it.

PDOStatement->setFetchMode
PDO Drivers
PDO


The PDOStatement class

Introduction

Represents a prepared statement and, after the statement is executed, an associated result set.

Class synopsis

PDOStatement
PDOStatement implements Traversable {
/* Properties */
readonlystring $queryString;
/* Methods */
bool bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] )
bool bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
bool bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )
bool closeCursor ( void )
int columnCount ( void )
bool debugDumpParams ( void )
string errorCode ( void )
array errorInfo ( void )
bool execute ([ array $input_parameters = array() ] )
mixed fetch ([ int $fetch_style = PDO::FETCH_BOTH [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )
array fetchAll ([ int $fetch_style = PDO::FETCH_BOTH [, int $column_index = 0 [, array $ctor_args = array() ]]] )
string fetchColumn ([ int $column_number = 0 ] )
mixed fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )
mixed getAttribute ( int $attribute )
array getColumnMeta ( int $column )
bool nextRowset ( void )
int rowCount ( void )
bool setAttribute ( int $attribute , mixed $value )
bool setFetchMode ( int $mode )
}

Properties

queryString

Used query string.

Table of Contents

  • PDOStatement->bindColumn — Bind a column to a PHP variable
  • PDOStatement->bindParam — Binds a parameter to the specified variable name
  • PDOStatement->bindValue — Binds a value to a parameter
  • PDOStatement->closeCursor — Closes the cursor, enabling the statement to be executed again.
  • PDOStatement->columnCount — Returns the number of columns in the result set
  • PDOStatement->debugDumpParams — Dump a SQL prepared command
  • PDOStatement->errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle
  • PDOStatement->errorInfo — Fetch extended error information associated with the last operation on the statement handle
  • PDOStatement->execute — Executes a prepared statement
  • PDOStatement->fetch — Fetches the next row from a result set
  • PDOStatement->fetchAll — Returns an array containing all of the result set rows
  • PDOStatement->fetchColumn — Returns a single column from the next row of a result set
  • PDOStatement->fetchObject — Fetches the next row and returns it as an object.
  • PDOStatement->getAttribute — Retrieve a statement attribute
  • PDOStatement->getColumnMeta — Returns metadata for a column in a result set
  • PDOStatement->nextRowset — Advances to the next rowset in a multi-rowset statement handle
  • PDOStatement->rowCount — Returns the number of rows affected by the last SQL statement
  • PDOStatement->setAttribute — Set a statement attribute
  • PDOStatement->setFetchMode — Set the default fetch mode for this statement
PDO::setAttribute
PDOStatement->bindColumn
PDO


The Phar class

Introduction

The Phar class provides a high-level interface to accessing and creating phar archives.

Class synopsis

Phar
Phar extends RecursiveDirectoryIterator implements Countable , ArrayAccess {
/* Properties */
/* Methods */
void addEmptyDir ( string $dirname )
void addFile ( string $file [, string $localname ] )
void addFromString ( string $localname , string $contents )
string apiVersion ( void )
array buildFromDirectory ( string $base_dir [, string $regex ] )
array buildFromIterator ( Iterator $iter [, string $base_directory ] )
bool canCompress ([ int $type = 0 ] )
bool canWrite ( void )
object compress ( int $compression [, string $extension ] )
bool compressAllFilesBZIP2 ( void )
bool compressAllFilesGZ ( void )
void compressFiles ( int $compression )
void __construct ( string $fname [, int $flags [, string $alias ]] )
PharData convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
Phar convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
bool copy ( string $oldfile , string $newfile )
int count ( void )
string createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
object decompress ([ string $extension ] )
bool decompressFiles ( void )
bool delMetadata ( void )
bool delete ( string $entry )
bool extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
mixed getMetaData ( void )
bool getModified ( void )
array getSignature ( void )
string getStub ( void )
array getSupportedCompression ( void )
array getSupportedSignatures ( void )
string getVersion ( void )
bool hasMetadata ( void )
void interceptFileFuncs ( void )
bool isBuffering ( void )
mixed isCompressed ( void )
bool isFileFormat ( int $format )
bool isValidPharFilename ( string $filename [, bool $executable = true ] )
bool isWritable ( void )
bool loadPhar ( string $filename [, string $alias ] )
bool mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
void mount ( string $pharpath , string $externalpath )
void mungServer ( array $munglist )
bool offsetExists ( string $offset )
int offsetGet ( string $offset )
void offsetSet ( string $offset , string $value )
bool offsetUnset ( string $offset )
string running ([ bool $retphar = true ] )
bool setAlias ( string $alias )
bool setDefaultStub ([ string $index [, string $webindex ]] )
void setMetadata ( mixed $metadata )
void setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
bool setStub ( string $stub )
void startBuffering ( void )
void stopBuffering ( void )
bool uncompressAllFiles ( void )
bool unlinkArchive ( string $archive )
void webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, array $rewrites ]]]]] )
}

Table of Contents

  • Phar::addEmptyDir — Add an empty directory to the phar archive
  • Phar::addFile — Add a file from the filesystem to the phar archive
  • Phar::addFromString — Add a file from the filesystem to the phar archive
  • Phar::apiVersion — Returns the api version
  • Phar::buildFromDirectory — Construct a phar archive from the files within a directory.
  • Phar::buildFromIterator — Construct a phar archive from an iterator.
  • Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::canWrite — Returns whether phar extension supports writing and creating phars
  • Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip compression
  • Phar::compressFiles — Compresses all files in the current Phar archive
  • Phar::__construct — Construct a Phar archive object
  • Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
  • Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
  • Phar::copy — Copy a file internal to the phar archive to another new file within the phar
  • Phar::count — Returns the number of entries (files) in the Phar archive
  • Phar::createDefaultStub — Create a phar-file format specific stub
  • Phar::decompress — Decompresses the entire Phar archive
  • Phar::decompressFiles — Decompresses all files in the current Phar archive
  • Phar::delMetadata — Deletes the global metadata of the phar
  • Phar::delete — Delete a file within a phar archive
  • Phar::extractTo — Extract the contents of a phar archive to a directory
  • Phar::getMetaData — Returns phar archive meta-data
  • Phar::getModified — Return whether phar was modified
  • Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
  • Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
  • Phar::getSupportedCompression — Return array of supported compression algorithms
  • Phar::getSupportedSignatures — Return array of supported signature types
  • Phar::getVersion — Return version info of Phar archive
  • Phar::hasMetaData — Returns whether phar has global meta-data
  • Phar::interceptFileFuncs — instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
  • Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
  • Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
  • Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
  • Phar::isWritable — Returns true if the phar archive can be modified
  • Phar::loadPhar — Loads any phar archive with an alias
  • Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
  • Phar::mount — Mount an external path or file to a virtual location within the phar archive
  • Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
  • Phar::offsetExists — determines whether a file exists in the phar
  • Phar::offsetGet — Gets a PharFileInfo object for a specific file
  • Phar::offsetSet — set the contents of an internal file to those of an external file
  • Phar::offsetUnset — remove a file from a phar
  • Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
  • Phar::setAlias — Set the alias for the Phar archive
  • Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
  • Phar::setMetadata — Sets phar archive meta-data
  • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it.
  • Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
  • Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive
  • Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
  • Phar::webPhar — mapPhar for web-based phars. front controller for web applications
Phar Signature format
Phar::addEmptyDir
Phar


The PharData class

Introduction

The PharData class provides a high-level interface to accessing and creating non-executable tar and zip archives. Because these archives do not contain a stub and cannot be executed by the phar extension, it is possible to create and manipulate regular zip and tar files using the PharData class even if phar.readonly php.ini setting is 1.

Class synopsis

PharData
PharData extends Phar {
/* Properties */
/* Methods */
bool addEmptyDir ( string $dirname )
void Phar::addFile ( string $file [, string $localname ] )
bool addFromString ( string $localname , string $contents )
array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
array buildFromIterator ( Iterator $iter [, string $base_directory ] )
object compress ( int $compression , string $extension )
bool compressFiles ( int $compression )
void __construct ( string $fname [, int $flags ] )
PharData convertToData ([ int $format [, int $compression [, string $extension ]]] )
Phar convertToExecutable ([ int $format [, int $compression [, string $extension ]]] )
bool copy ( string $oldfile , string $newfile )
object decompress ([ string $extension ] )
bool decompressFiles ( void )
int delMetadata ( void )
int delete ( string $entry )
int extractTo ( string $pathto [, string|array $files [, bool $overwrite ]] )
bool isWritable ( void )
void offsetSet ( string $offset , string $value )
bool offsetUnset ( string $offset )
bool setAlias ( string $alias )
void setDefaultStub ([ string $index [, string $webindex ]] )
void Phar::setMetadata ( mixed $metadata )
void Phar::setSignatureAlgorithm ( int $sigtype )
void setStub ( string $stub )
/* Inherited methods */
void Phar::addEmptyDir ( string $dirname )
void Phar::addFile ( string $file [, string $localname ] )
void Phar::addFromString ( string $localname , string $contents )
string Phar::apiVersion ( void )
array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )
bool Phar::canCompress ([ int $type = 0 ] )
bool Phar::canWrite ( void )
object Phar::compress ( int $compression [, string $extension ] )
bool Phar::compressAllFilesBZIP2 ( void )
bool Phar::compressAllFilesGZ ( void )
void Phar::compressFiles ( int $compression )
void Phar::__construct ( string $fname [, int $flags [, string $alias ]] )
PharData Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
bool Phar::copy ( string $oldfile , string $newfile )
int Phar::count ( void )
string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
object Phar::decompress ([ string $extension ] )
bool Phar::decompressFiles ( void )
bool Phar::delMetadata ( void )
bool Phar::delete ( string $entry )
bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
mixed Phar::getMetaData ( void )
bool Phar::getModified ( void )
array Phar::getSignature ( void )
string Phar::getStub ( void )
array Phar::getSupportedCompression ( void )
array Phar::getSupportedSignatures ( void )
string Phar::getVersion ( void )
bool Phar::hasMetadata ( void )
void Phar::interceptFileFuncs ( void )
bool Phar::isBuffering ( void )
mixed Phar::isCompressed ( void )
bool Phar::isFileFormat ( int $format )
bool Phar::isValidPharFilename ( string $filename [, bool $executable = true ] )
bool Phar::isWritable ( void )
bool Phar::loadPhar ( string $filename [, string $alias ] )
bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
void Phar::mount ( string $pharpath , string $externalpath )
void Phar::mungServer ( array $munglist )
bool Phar::offsetExists ( string $offset )
int Phar::offsetGet ( string $offset )
void Phar::offsetSet ( string $offset , string $value )
bool Phar::offsetUnset ( string $offset )
string Phar::running ([ bool $retphar = true ] )
bool Phar::setAlias ( string $alias )
bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )
void Phar::setMetadata ( mixed $metadata )
void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
bool Phar::setStub ( string $stub )
void Phar::startBuffering ( void )
void Phar::stopBuffering ( void )
bool Phar::uncompressAllFiles ( void )
bool Phar::unlinkArchive ( string $archive )
void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, array $rewrites ]]]]] )
}

Table of Contents

  • PharData::addEmptyDir — Add an empty directory to the tar/zip archive
  • PharData::addFile — Add a file from the filesystem to the tar/zip archive
  • PharData::addFromString — Add a file from the filesystem to the tar/zip archive
  • PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory.
  • PharData::buildFromIterator — Construct a tar or zip archive from an iterator.
  • PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::compressFiles — Compresses all files in the current tar/zip archive
  • PharData::__construct — Construct a non-executable tar or zip archive object
  • PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::copy — Copy a file internal to the phar archive to another new file within the phar
  • PharData::decompress — Decompresses the entire Phar archive
  • PharData::decompressFiles — Decompresses all files in the current zip archive
  • PharData::delMetadata — Deletes the global metadata of a zip archive
  • PharData::delete — Delete a file within a tar/zip archive
  • PharData::extractTo — Extract the contents of a tar/zip archive to a directory
  • PharData::isWritable — Returns true if the tar/zip archive can be modified
  • PharData::offsetSet — set the contents of a file within the tar/zip to those of an external file or string
  • PharData::offsetUnset — remove a file from a tar/zip archive
  • PharData::setAlias — dummy function (Phar::setAlias is not valid for PharData)
  • PharData::setDefaultStub — dummy function (Phar::setDefaultStub is not valid for PharData)
  • Phar::setMetadata — Sets phar archive meta-data
  • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it. The
  • PharData::setStub — dummy function (Phar::setStub is not valid for PharData)
Phar::webPhar
PharData::addEmptyDir
Phar


The PharException class

Introduction

The PharException class provides a phar-specific exception class for try/catch blocks.

Class synopsis

PharException
PharException extends Exception {
/* Properties */
}

Table of Contents

  • PharException — The PharException class provides a phar-specific exception class for try/catch blocks.
PharFileInfo::setUncompressed
PharException
Phar


The PharFileInfo class

Introduction

The PharFileInfo class provides a high-level interface to the contents and attributes of a single file within a phar archive.

Class synopsis

PharFileInfo
PharFileInfo extends SplFileInfo {
/* Properties */
/* Methods */
void chmod ( int $permissions )
bool compress ( int $compression )
void __construct ( string $entry )
bool decompress ( void )
bool delMetadata ( void )
int getCRC32 ( void )
int getCompressedSize ( void )
mixed getMetaData ( void )
int getPharFlags ( void )
bool hasMetadata ( void )
bool isCRCChecked ( void )
bool isCompressed ([ int $compression_type = 9021976 ] )
bool isCompressedBZIP2 ( void )
bool isCompressedGZ ( void )
bool setCompressedBZIP2 ( void )
bool setCompressedGZ ( void )
void setMetaData ( mixed $metadata )
bool setUncompressed ( void )
}

Table of Contents

  • PharFileInfo::chmod — Sets file-specific permission bits
  • PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::__construct — Construct a Phar entry object
  • PharFileInfo::decompress — Decompresses the current Phar entry within the phar
  • PharFileInfo::delMetadata — Deletes the metadata of the entry
  • PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
  • PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::getMetaData — Returns file-specific meta-data saved with a file
  • PharFileInfo::getPharFlags — Returns the Phar file entry flags
  • PharFileInfo::hasMetadata — Returns the metadata of the entry
  • PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
  • PharFileInfo::isCompressed — Returns whether the entry is compressed
  • PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2 — Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setCompressedGZ — Compresses the current Phar entry within the phar using gz compression
  • PharFileInfo::setMetaData — Sets file-specific meta-data saved with a file
  • PharFileInfo::setUncompressed — Uncompresses the current Phar entry within the phar, if it is compressed
PharData::setStub
PharFileInfo::chmod
Phar


The RarArchive class

Introduction

This class represents a RAR archive, which may be formed by several volumes (parts) and which contains a number of RAR entries (i.e., files, directories and other special objects such as symbolic links).

Objects of this class can be traversed, yielding the entries stored in the respective RAR archive. Those entries can also be obtained through RarArchive::getEntry and RarArchive::list.

Class synopsis

RarArchive
final RarArchive implements Traversable {
/* Methods */
public bool close ( void )
public string getComment ( void )
public RarEntry getEntry ( string $entryname )
public bool isSolid ( void )
public array list ( void )
public static RarArchive open ( string $filename [, string $password ] )
public void __toString ( void )
}

Table of Contents

  • RarArchive::close — Close RAR archive and free all resources.
  • RarArchive::getComment — Get comment text from the RAR archive.
  • RarArchive::getEntry — Get entry object from the RAR archive.
  • RarArchive::isSolid — Check whether the RAR archive is solid.
  • RarArchive::list — Get entries full list from the RAR archive.
  • RarArchive::open — Open RAR archive.
  • RarArchive::__toString — Get text representation.
Examples
RarArchive::close
Rar


The RarEntry class

Introduction

A RAR entry, representing a directory or a compressed file inside a RAR archive.

Class synopsis

RarEntry
final RarEntry {
/* Constants */
const integer RarEntry::HOST_MSDOS = 0 ;
const integer RarEntry::HOST_OS2 = 1 ;
const integer RarEntry::HOST_WIN32 = 2 ;
const integer RarEntry::HOST_UNIX = 3 ;
const integer RarEntry::HOST_MACOS = 4 ;
const integer RarEntry::HOST_BEOS = 5 ;
const integer RarEntry::ATTRIBUTE_WIN_READONLY = 1 ;
const integer RarEntry::ATTRIBUTE_WIN_HIDDEN = 2 ;
const integer RarEntry::ATTRIBUTE_WIN_SYSTEM = 4 ;
const integer RarEntry::ATTRIBUTE_WIN_DIRECTORY = 16 ;
const integer RarEntry::ATTRIBUTE_WIN_ARCHIVE = 32 ;
const integer RarEntry::ATTRIBUTE_WIN_DEVICE = 64 ;
const integer RarEntry::ATTRIBUTE_WIN_NORMAL = 128 ;
const integer RarEntry::ATTRIBUTE_WIN_TEMPORARY = 256 ;
const integer RarEntry::ATTRIBUTE_WIN_SPARSE_FILE = 512 ;
const integer RarEntry::ATTRIBUTE_WIN_REPARSE_POINT = 1024 ;
const integer RarEntry::ATTRIBUTE_WIN_COMPRESSED = 2048 ;
const integer RarEntry::ATTRIBUTE_WIN_OFFLINE = 4096 ;
const integer RarEntry::ATTRIBUTE_WIN_NOT_CONTENT_INDEXED = 8192 ;
const integer RarEntry::ATTRIBUTE_WIN_ENCRYPTED = 16384 ;
const integer RarEntry::ATTRIBUTE_WIN_VIRTUAL = 65536 ;
const integer RarEntry::ATTRIBUTE_UNIX_WORLD_EXECUTE = 1 ;
const integer RarEntry::ATTRIBUTE_UNIX_WORLD_WRITE = 2 ;
const integer RarEntry::ATTRIBUTE_UNIX_WORLD_READ = 4 ;
const integer RarEntry::ATTRIBUTE_UNIX_GROUP_EXECUTE = 8 ;
const integer RarEntry::ATTRIBUTE_UNIX_GROUP_WRITE = 16 ;
const integer RarEntry::ATTRIBUTE_UNIX_GROUP_READ = 32 ;
const integer RarEntry::ATTRIBUTE_UNIX_OWNER_EXECUTE = 64 ;
const integer RarEntry::ATTRIBUTE_UNIX_OWNER_WRITE = 128 ;
const integer RarEntry::ATTRIBUTE_UNIX_OWNER_READ = 256 ;
const integer RarEntry::ATTRIBUTE_UNIX_STICKY = 512 ;
const integer RarEntry::ATTRIBUTE_UNIX_SETGID = 1024 ;
const integer RarEntry::ATTRIBUTE_UNIX_SETUID = 2048 ;
const integer RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET = 61440 ;
const integer RarEntry::ATTRIBUTE_UNIX_FIFO = 4096 ;
const integer RarEntry::ATTRIBUTE_UNIX_CHAR_DEV = 8192 ;
const integer RarEntry::ATTRIBUTE_UNIX_DIRECTORY = 16384 ;
const integer RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV = 24576 ;
const integer RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE = 32768 ;
const integer RarEntry::ATTRIBUTE_UNIX_SYM_LINK = 40960 ;
const integer RarEntry::ATTRIBUTE_UNIX_SOCKET = 49152 ;
/* Properties */
private $rarfile ;
private $name ;
private $unpacked_size ;
private $packed_size ;
private $host_os ;
private $file_time ;
private $crc ;
private $attr ;
private $version ;
private $method ;
private $flags ;
/* Methods */
public bool extract ( string $dir [, string $filepath [, string $password ]] )
public int getAttr ( void )
public string getCrc ( void )
public string getFileTime ( void )
public int getHostOs ( void )
public int getMethod ( void )
public string getName ( void )
public int getPackedSize ( void )
public resource getStream ([ string $password ] )
public int getUnpackedSize ( void )
public int getVersion ( void )
public bool isDirectory ( void )
public bool isEncrypted ( void )
public string __toString ( void )
}

Properties

rarfile

Used internally to hold a reference to the RAR file resource. It is not part of the contract.

name

Used internally to store the UTF-8 encoded entry name. It is not part of the contract.

unpacked_size

Used internally to store the unpacked entry size. It is not part of the contract.

packed_size

Used internally to store the packed entry size. It is not part of the contract.

host_os

Used internally to store the host OS. It is not part of the contract.

file_time

Used internally to store the last modification time of the entry. It is not part of the contract.

crc

Used internally to store the entry's hexadecimal string representation of its CRC. It is not part of the contract.

attr

Used internally to store the entry's attributes. It is not part of the contract.

version

Used internally to store the minimum RAR version needed to unpack the entry. It is encoded as 10 * Major version + minor version. This property is not part of the contract.

method

Used internally to store the method used to pack the entry. It is not part of the contract.

flags

Used internally to store several entry properties, such as dictionary size, whether it's a directory, is encrypted, is continued in the previous or next volume, is solid or has a comment. Again, not part of the contract.

Predefined Constants

RarEntry Node Types

RarEntry::HOST_MSDOS

If the return value of RarEntry::getHostOs equals this constant, MS-DOS was used to add this entry. Use instead of RAR_HOST_MSDOS.

RarEntry::HOST_OS2

If the return value of RarEntry::getHostOs equals this constant, OS/2 was used to add this entry. Intended to replace RAR_HOST_OS2.

RarEntry::HOST_WIN32

If the return value of RarEntry::getHostOs equals this constant, Microsoft Windows was used to add this entry. Intended to replace RAR_HOST_WIN32.

RarEntry::HOST_UNIX

If the return value of RarEntry::getHostOs equals this constant, an unspecified UNIX OS was used to add this entry. Intended to replace RAR_HOST_UNIX.

RarEntry::HOST_MACOS

If the return value of RarEntry::getHostOs equals this constant, Mac OS was used to add this entry.

RarEntry::HOST_BEOS

If the return value of RarEntry::getHostOs equals this constant, BeOS was used to add this entry. Intended to replace RAR_HOST_BEOS.

RarEntry::ATTRIBUTE_WIN_READONLY

Bit that represents a Windows entry with a read-only attribute. To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_HIDDEN

Bit that represents a Windows entry with a hidden attribute. To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_SYSTEM

Bit that represents a Windows entry with a system attribute. To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_DIRECTORY

Bit that represents a Windows entry with a directory attribute (entry is a directory). To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows. See also RarEntry::isDirectory, which also works with entries that were not added in WinRAR.

RarEntry::ATTRIBUTE_WIN_ARCHIVE

Bit that represents a Windows entry with an archive attribute. To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_DEVICE

Bit that represents a Windows entry with a device attribute. To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_NORMAL

Bit that represents a Windows entry with a normal file attribute (entry is NOT a directory). To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows. See also RarEntry::isDirectory, which also works with entries that were not added in WinRAR.

RarEntry::ATTRIBUTE_WIN_TEMPORARY

Bit that represents a Windows entry with a temporary attribute. To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_SPARSE_FILE

Bit that represents a Windows entry with a sparse file attribute (file is an NTFS sparse file). To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_REPARSE_POINT

Bit that represents a Windows entry with a reparse point attribute (entry is an NTFS reparse point, e.g. a directory junction or a mount file system). To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_COMPRESSED

Bit that represents a Windows entry with a compressed attribute (NTFS only). To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_OFFLINE

Bit that represents a Windows entry with an offline attribute (entry is offline and not accessible). To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_NOT_CONTENT_INDEXED

Bit that represents a Windows entry with a not content indexed attribute (entry is to be indexed). To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_ENCRYPTED

Bit that represents a Windows entry with an encrypted attribute (NTFS only). To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_VIRTUAL

Bit that represents a Windows entry with a virtual attribute. To be used with RarEntry::getAttr on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_UNIX_WORLD_EXECUTE

Bit that represents a UNIX entry that is world executable. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_WORLD_WRITE

Bit that represents a UNIX entry that is world writable. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_WORLD_READ

Bit that represents a UNIX entry that is world readable. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_EXECUTE

Bit that represents a UNIX entry that is group executable. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_WRITE

Bit that represents a UNIX entry that is group writable. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_READ

Bit that represents a UNIX entry that is group readable. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_EXECUTE

Bit that represents a UNIX entry that is owner executable. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_WRITE

Bit that represents a UNIX entry that is owner writable. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_READ

Bit that represents a UNIX entry that is owner readable. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_STICKY

Bit that represents the UNIX sticky bit. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_SETGID

Bit that represents the UNIX setgid attribute. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_SETUID

Bit that represents the UNIX setuid attribute. To be used with RarEntry::getAttr on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET

Mask to isolate the last four bits of UNIX attributes. To be used with
        RarEntry::getAttr on entries whose host OS is UNIX and with the
       constants RarEntry::ATTRIBUTE_UNIX_FIFO,
       RarEntry::ATTRIBUTE_UNIX_CHAR_DEV,
       RarEntry::ATTRIBUTE_UNIX_DIRECTORY,
       RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV,
       RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE,
       RarEntry::ATTRIBUTE_UNIX_SYM_LINK and
       RarEntry::ATTRIBUTE_UNIX_SOCKET.

RarEntry::ATTRIBUTE_UNIX_FIFO

Unix FIFOs will have attributes whose last four bits have this value. To be used with RarEntry::getAttr on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_CHAR_DEV

Unix character devices will have attributes whose last four bits have this value. To be used with RarEntry::getAttr on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_DIRECTORY

Unix directories will have attributes whose last four bits have this value. To be used with RarEntry::getAttr on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET. See also RarEntry::isDirectory, which also works with entries that were added in other operating systems.

RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV

Unix block devices will have attributes whose last four bits have this value. To be used with RarEntry::getAttr on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE

Unix regular files (not directories) will have attributes whose last four bits have this value. To be used with RarEntry::getAttr on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET. See also RarEntry::isDirectory, which also works with entries that were added in other operating systems.

RarEntry::ATTRIBUTE_UNIX_SYM_LINK

Unix symbolic links will have attributes whose last four bits have this value. To be used with RarEntry::getAttr on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_SOCKET

Unix sockets will have attributes whose last four bits have this value. To be used with RarEntry::getAttr on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

Table of Contents

  • RarEntry::extract — Extract entry from the archive.
  • RarEntry::getAttr — Get attributes of the entry.
  • RarEntry::getCrc — Get CRC of the entry.
  • RarEntry::getFileTime — Get entry last modification time.
  • RarEntry::getHostOs — Get entry host OS.
  • RarEntry::getMethod — Get pack method of the entry.
  • RarEntry::getName — Get name of the entry.
  • RarEntry::getPackedSize — Get packed size of the entry.
  • RarEntry::getStream — Get file handler for entry.
  • RarEntry::getUnpackedSize — Get unpacked size of the entry.
  • RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry.
  • RarEntry::isDirectory — Test whether an entry represents a directory.
  • RarEntry::isEncrypted — Test whether an entry is encrypted.
  • RarEntry::__toString — Get text representation of entry.
RarArchive::__toString
RarEntry::extract
Rar


The RarException class

Introduction

This class serves two purposes: it is the type of the exceptions thrown by the RAR extension functions and methods and it allows, through static methods to query and define the error behaviour of the extension, i.e., whether exceptions are thrown or only warnings are emitted.

The following error codes are used:

  • -1 - error outside UnRAR library
  • 11 - insufficient memory
  • 12 - bad data
  • 13 - bad archive
  • 14 - unknown format
  • 15 - file open error
  • 16 - file create error
  • 17 - file close error
  • 18 - read error
  • 19 - write error
  • 20 - buffer too small
  • 21 - unkown RAR error
  • 22 - password required but not given

Class synopsis

RarException
final RarException extends Exception {
/* Properties */
private static $usingExceptions ;
/* Methods */
public static bool isUsingExceptions ( void )
public static void setUsingExceptions ( bool $using_exceptions )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public int Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Properties

message

Not part of the contract. Use RarException::getMessage.

code

Not part of the contract. Use RarException::getCode.

file

Not part of the contract. Use RarException::getFile.

line

Not part of the contract. Use RarException::getLine.

usingExceptions

Not part of the contract. Use RarException::isUsingExceptions and RarException::setUsingExceptions.

Table of Contents

  • RarException::isUsingExceptions — Check whether error handling with exceptions is in use.
  • RarException::setUsingExceptions — Activate and deactivate error handling with exceptions.
RarEntry::__toString
RarException::isUsingExceptions
Rar


The ResourceBundle class

Introduction

Localized software products often require sets of data that are to be customized depending on current locale, e.g.: messages, labels, formatting patterns. ICU resource mechanism allows to define sets of resources that the application can load on locale basis, while accessing them in unified locale-independent fashion.

This class implements access to ICU resource data files. These files are binary data arrays which ICU uses to store the localized data.

ICU resource bundle can hold simple resources and complex resources. Complex resources are containers which can be either integer-indexed or string-indexed (just like PHP arrays). Simple resources can be of the following typos: string, integer, binary data field or integer array.

ResourceBundle supports direct access to the data through array access pattern and iteration via foreach, as well as access via class methods. The result will be PHP value for simple resources and ResourceBundle object for complex ones. All resources are read-only.

Class synopsis

ResourceBundle
ResourceBundle {
/* Methods */
__construct ( string $locale , string $bundlename [, bool $fallback ] )
int count ( void )
static ResourceBundle create ( string $locale , string $bundlename [, bool $fallback ] )
int getErrorCode ( void )
string getErrorMessage ( void )
mixed get ( string|int $index )
array getLocales ( void )
}

See Also

  • » ICU Resource Management
  • » ICU Data

Table of Contents

  • ResourceBundle::count — Get number of elements in the bundle
  • ResourceBundle::create — Create a resource bundle
  • ResourceBundle::getErrorCode — Get bundle's last error code.
  • ResourceBundle::getErrorMessage — Get bundle's last error message.
  • ResourceBundle::get — Get data from the bundle
  • ResourceBundle::getLocales — Get supported locales
IntlDateFormatter::setTimeZoneId
ResourceBundle::count
intl


The Serializable interface

Introduction

Interface for customized serializing.

Classes that implement this interface no longer support __sleep() and __wakeup(). The method serialize is called whenever an instance needs to be serialized. This does not invoke __destruct() or has any other side effect unless programmed inside the method. When the data is unserialized the class is known and the appropriate unserialize() method is called as a constructor instead of calling __construct(). If you need to execute the standard constructor you may do so in the method.

Interface synopsis

Serializable
Serializable {
/* Methods */
abstract public string serialize ( void )
abstract public mixed unserialize ( string $serialized )
}

Example #1 Basic usage

<?php
class obj implements Serializable {
    private $data;
    public function __construct() {
        $this->data = "My private data";
    }
    public function serialize() {
        return serialize($this->data);
    }
    public function unserialize($data) {
        $this->data = unserialize($data);
    }
    public function getData() {
        return $this->data;
    }
}

$obj = new obj;
$ser = serialize($obj);

$newobj = unserialize($ser);

var_dump($newobj->getData());
?>

The above example will output something similar to:

string(15) "My private data"

Table of Contents

  • Serializable::serialize — String representation of object
  • Serializable::unserialize — Constructs the object
ArrayAccess::offsetUnset
Serializable::serialize
Predefined Interfaces


The SplDoublyLinkedList class

Introduction

The SplDoublyLinkedList class provides the main functionalities of a doubly linked list.

Class synopsis

SplDoublyLinkedList
SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Methods */
__construct ( void )
mixed bottom ( void )
int count ( void )
mixed current ( void )
int getIteratorMode ( void )
bool isEmpty ( void )
mixed key ( void )
void next ( void )
bool offsetExists ( mixed $index )
mixed offsetGet ( mixed $index )
void offsetSet ( mixed $index , mixed $newval )
void offsetUnset ( mixed $index )
mixed pop ( void )
void prev ( void )
void push ( mixed $value )
void rewind ( void )
void setIteratorMode ( int $mode )
mixed shift ( void )
mixed top ( void )
void unshift ( mixed $value )
bool valid ( void )
}

Table of Contents

  • SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list
  • SplDoublyLinkedList::__construct — Constructs a new doubly linked list
  • SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list.
  • SplDoublyLinkedList::current — Return current array entry
  • SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration
  • SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty.
  • SplDoublyLinkedList::key — Return current node index
  • SplDoublyLinkedList::next — Move to next entry
  • SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists
  • SplDoublyLinkedList::offsetGet — Returns the value at the specified $index
  • SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $newval
  • SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index
  • SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list
  • SplDoublyLinkedList::prev — Move to previous entry
  • SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list
  • SplDoublyLinkedList::rewind — Rewind iterator back to the start
  • SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration
  • SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list
  • SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list
  • SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element
  • SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes
Datastructures
SplDoublyLinkedList::bottom
Datastructures


The SplHeap class

Introduction

The SplHeap class provides the main functionalities of an Heap.

Class synopsis

SplHeap
abstract SplHeap implements Iterator , Countable {
/* Methods */
__construct ( void )
abstract int compare ( mixed $value1 , mixed $value2 )
int count ( void )
mixed current ( void )
mixed extract ( void )
void insert ( mixed $value )
bool isEmpty ( void )
mixed key ( void )
void next ( void )
void recoverFromCorruption ( void )
void rewind ( void )
mixed top ( void )
bool valid ( void )
}

Table of Contents

  • SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.
  • SplHeap::__construct — Constructs a new empty heap
  • SplHeap::count — Counts the number of elements in the heap.
  • SplHeap::current — Return current node pointed by the iterator
  • SplHeap::extract — Extracts a node from top of the heap and sift up.
  • SplHeap::insert — Inserts an element in the heap by sifting it up.
  • SplHeap::isEmpty — Checks whether the heap is empty.
  • SplHeap::key — Return current node index
  • SplHeap::next — Move to the next node
  • SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap.
  • SplHeap::rewind — Rewind iterator back to the start (no-op)
  • SplHeap::top — Peaks at the node from the top of the heap
  • SplHeap::valid — Check whether the heap contains more nodes
SplQueue::setIteratorMode
SplHeap::compare
Datastructures


The SplQueue class

Introduction

The SplQueue class provides the main functionalities of a queue implemented using a doubly linked list.

Class synopsis

SplQueue
SplQueue extends SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Methods */
__construct ( void )
mixed dequeue ( void )
void enqueue ( mixed $value )
void setIteratorMode ( int $mode )
/* Inherited methods */
mixed SplDoublyLinkedList::bottom ( void )
int SplDoublyLinkedList::count ( void )
mixed SplDoublyLinkedList::current ( void )
int SplDoublyLinkedList::getIteratorMode ( void )
bool SplDoublyLinkedList::isEmpty ( void )
mixed SplDoublyLinkedList::key ( void )
void SplDoublyLinkedList::next ( void )
bool SplDoublyLinkedList::offsetExists ( mixed $index )
mixed SplDoublyLinkedList::offsetGet ( mixed $index )
void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )
void SplDoublyLinkedList::offsetUnset ( mixed $index )
mixed SplDoublyLinkedList::pop ( void )
void SplDoublyLinkedList::prev ( void )
void SplDoublyLinkedList::push ( mixed $value )
void SplDoublyLinkedList::rewind ( void )
void SplDoublyLinkedList::setIteratorMode ( int $mode )
mixed SplDoublyLinkedList::shift ( void )
mixed SplDoublyLinkedList::top ( void )
void SplDoublyLinkedList::unshift ( mixed $value )
bool SplDoublyLinkedList::valid ( void )
}

Table of Contents

  • SplQueue::__construct — Constructs a new queue implemented using a doubly linked list
  • SplQueue::dequeue — Dequeues a node from the queue
  • SplQueue::enqueue — Adds an element to the queue.
  • SplQueue::setIteratorMode — Sets the mode of iteration
SplStack::setIteratorMode
SplQueue::__construct
Datastructures


The SplStack class

Introduction

The SplStack class provides the main functionalities of a stack implemented using a doubly linked list.

Class synopsis

SplStack
SplStack extends SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Methods */
__construct ( void )
void setIteratorMode ( int $mode )
/* Inherited methods */
mixed SplDoublyLinkedList::bottom ( void )
int SplDoublyLinkedList::count ( void )
mixed SplDoublyLinkedList::current ( void )
int SplDoublyLinkedList::getIteratorMode ( void )
bool SplDoublyLinkedList::isEmpty ( void )
mixed SplDoublyLinkedList::key ( void )
void SplDoublyLinkedList::next ( void )
bool SplDoublyLinkedList::offsetExists ( mixed $index )
mixed SplDoublyLinkedList::offsetGet ( mixed $index )
void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )
void SplDoublyLinkedList::offsetUnset ( mixed $index )
mixed SplDoublyLinkedList::pop ( void )
void SplDoublyLinkedList::prev ( void )
void SplDoublyLinkedList::push ( mixed $value )
void SplDoublyLinkedList::rewind ( void )
void SplDoublyLinkedList::setIteratorMode ( int $mode )
mixed SplDoublyLinkedList::shift ( void )
mixed SplDoublyLinkedList::top ( void )
void SplDoublyLinkedList::unshift ( mixed $value )
bool SplDoublyLinkedList::valid ( void )
}

Table of Contents

  • SplStack::__construct — Constructs a new stack implemented using a doubly linked list
  • SplStack::setIteratorMode — Sets the mode of iteration
SplDoublyLinkedList::valid
SplStack::__construct
Datastructures


The SQLite3 class

Introduction

A class that interfaces SQLite 3 databases.

Class synopsis

SQLite3
SQLite3 {
/* Methods */
public int changes ( void )
public bool close ( void )
__construct ( string $filename [, int $flags [, string $encryption_key ]] )
public bool createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -1 ] )
public bool createFunction ( string $name , mixed $callback [, int $argument_count = -1 ] )
public string escapeString ( string $value )
public bool exec ( string $query )
public int lastErrorCode ( void )
public string lastErrorMsg ( void )
public int lastInsertRowID ( void )
public bool loadExtension ( string $shared_library )
public bool open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key ]] )
public SQLite3Stmt prepare ( string $query )
public SQLite3Result query ( string $query )
public mixed querySingle ( string $query [, bool $entire_row = false ] )
public array version ( void )
}

Table of Contents

  • SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
  • SQLite3::close — Closes the database connection
  • SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database
  • SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
  • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
  • SQLite3::escapeString — Returns a string that has been properly escaped
  • SQLite3::exec — Executes a result-less query against a given database
  • SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
  • SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
  • SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
  • SQLite3::loadExtension — Attempts to load an SQLite extension library
  • SQLite3::open — Opens an SQLite database
  • SQLite3::prepare — Prepares an SQL statement for execution
  • SQLite3::query — Executes an SQL query
  • SQLite3::querySingle — Executes a query and returns a single result
  • SQLite3::version — Returns the SQLite3 library version as a string constant and as a number
Predefined Constants
SQLite3::changes
SQLite3


The SQLite3Result class

Introduction

A class that handles result sets for the SQLite 3 extension.

Class synopsis

SQLite3Result
SQLite3Result {
/* Methods */
public string columnName ( int $column_number )
public int columnType ( int $column_number )
public array fetchArray ([ int $mode = SQLITE3_BOTH ] )
public bool finalize ( void )
public int numColumns ( void )
public bool reset ( void )
}

Table of Contents

  • SQLite3Result::columnName — Returns the name of the nth column
  • SQLite3Result::columnType — Returns the type of the nth column
  • SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
  • SQLite3Result::finalize — Closes the result set
  • SQLite3Result::numColumns — Returns the number of columns in the result set
  • SQLite3Result::reset — Resets the result set back to the first row
SQLite3Stmt::reset
SQLite3Result::columnName
SQLite3


The SQLite3Stmt class

Introduction

A class that handles prepared statements for the SQLite 3 extension.

Class synopsis

SQLite3Stmt
SQLite3Stmt {
/* Methods */
public bool bindParam ( string $sql_param , mixed &$param [, int $type ] )
public bool bindValue ( string $sql_param , mixed $value [, int $type ] )
public bool clear ( void )
public bool close ( void )
public SQLite3Result execute ( void )
public int paramCount ( void )
public bool reset ( void )
}

Table of Contents

  • SQLite3Stmt::bindParam — Binds a parameter to a statement variable
  • SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
  • SQLite3Stmt::clear — Clears all current bound parameters
  • SQLite3Stmt::close — Closes the prepared statement
  • SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
  • SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
  • SQLite3Stmt::reset — Resets the prepared statement
SQLite3::version
SQLite3Stmt::bindParam
SQLite3


The SWFAction class

Introduction

SWFAction.

Class synopsis

SWFAction
SWFAction {
/* Methods */
SWFAction __construct ( string $script )
}

Description

The script syntax is based on the C language, but with a lot taken out- the SWF bytecode machine is just too simpleminded to do a lot of things we might like. For instance, we can't implement function calls without a tremendous amount of hackery because the jump bytecode has a hardcoded offset value. No pushing your calling address to the stack and returning- every function would have to know exactly where to return to.

So what's left? The compiler recognises the following tokens:

  • break
  • for
  • continue
  • if
  • else
  • do
  • while

There is no typed data; all values in the SWF action machine are stored as strings. The following functions can be used in expressions:

time()
Returns the number of milliseconds (?) elapsed since the movie started.
random(seed)
Returns a pseudo-random number in the range 0-seed.
length(expr)
Returns the length of the given expression.
int(number)
Returns the given number rounded down to the nearest integer.
concat(expr, expr)
Returns the concatenation of the given expressions.
ord(expr)
Returns the ASCII code for the given character
chr(num)
Returns the character for the given ASCII code
substr(string, location, length)
Returns the substring of length length at location location of the given string string .

Additionally, the following commands may be used:

duplicateClip(clip, name, depth)
Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth .
removeClip(expr)
Removes the named movie clip.
trace(expr)
Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.
startDrag(target, lock, [left, top, right, bottom])
Start dragging the movie clip target . The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1 (TRUE). Optional parameters define a bounding area for the dragging.
stopDrag()
Stop dragging my heart around. And this movie clip, too.
callFrame(expr)
Call the named frame as a function.
getURL(url, target, [method])
Load the given URL into the named target. The target argument corresponds to HTML document targets (such as "_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the server.
loadMovie(url, target)
Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).
nextFrame()
Go to the next frame.
prevFrame()
Go to the last (or, rather, previous) frame.
play()
Start playing the movie.
stop()
Stop playing the movie.
toggleQuality()
Toggle between high and low quality.
stopSounds()
Stop playing all sounds.
gotoFrame(num)
Go to frame number num . Frame numbers start at 0.
gotoFrame(name)
Go to the frame named name . Which does a lot of good, since I haven't added frame labels yet.
setTarget(expr)
Sets the context for action. Or so they say- I really have no idea what this does.

And there's one weird extra thing. The expression frameLoaded(num) can be used in if statements and while loops to check if the given frame number has been loaded yet. Well, it's supposed to, anyway, but I've never tested it and I seriously doubt it actually works. You can just use /:framesLoaded instead.

Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of them, and here they are:

  • x
  • y
  • xScale
  • yScale
  • currentFrame - (read-only)
  • totalFrames - (read-only)
  • alpha - transparency level
  • visible - 1=on, 0=off (?)
  • width - (read-only)
  • height - (read-only)
  • rotation
  • target - (read-only) (???)
  • framesLoaded - (read-only)
  • name
  • dropTarget - (read-only) (???)
  • url - (read-only) (???)
  • highQuality - 1=high, 0=low (?)
  • focusRect - (???)
  • soundBufTime - (???)

So, setting a sprite's x position is as simple as /box.x = 100;. Why the slash in front of the box, though? That's how flash keeps track of the sprites in the movie, just like a Unix filesystem- here it shows that box is at the top level. If the sprite named box had another sprite named biff inside of it, you'd set its x position with /box/biff.x = 100;. At least, I think so; correct me if I'm wrong here.

Table of Contents

  • SWFAction->__construct — Creates a new SWFAction
ming_useswfversion
SWFAction->__construct
Ming


The SWFBitmap class

Introduction

SWFBitmap.

Class synopsis

SWFBitmap
SWFBitmap {
/* Methods */
SWFBitmap __construct ( mixed $file [, mixed $alphafile ] )
float getHeight ( void )
float getWidth ( void )
}

Table of Contents

  • SWFBitmap->__construct — Loads Bitmap object
  • SWFBitmap->getHeight — Returns the bitmap's height
  • SWFBitmap->getWidth — Returns the bitmap's width
SWFAction->__construct
SWFBitmap->__construct
Ming


The SWFButton class

Introduction

SWFButton.

Class synopsis

SWFButton
SWFButton {
/* Methods */
void addAction ( SWFAction $action , int $flags )
SWFSoundInstance addASound ( SWFSound $sound , int $flags )
void addShape ( SWFShape $shape , int $flags )
SWFButton __construct ( void )
void setAction ( SWFAction $action )
void setDown ( SWFShape $shape )
void setHit ( SWFShape $shape )
void setMenu ( int $flag )
void setOver ( SWFShape $shape )
void setUp ( SWFShape $shape )
}

Table of Contents

  • SWFButton->addAction — Adds an action
  • SWFButton->addASound — Associates a sound with a button transition
  • SWFButton->addShape — Adds a shape to a button
  • SWFButton->__construct — Creates a new Button
  • SWFButton->setAction — Sets the action
  • SWFButton->setDown — Alias for addShape(shape, SWFBUTTON_DOWN)
  • SWFButton->setHit — Alias for addShape(shape, SWFBUTTON_HIT)
  • SWFButton->setMenu — enable track as menu button behaviour
  • SWFButton->setOver — Alias for addShape(shape, SWFBUTTON_OVER)
  • SWFButton->setUp — Alias for addShape(shape, SWFBUTTON_UP)
SWFBitmap->getWidth
SWFButton->addAction
Ming


The SWFDisplayItem class

Introduction

SWFDisplayItem.

Class synopsis

SWFDisplayItem
SWFDisplayItem {
/* Methods */
void addAction ( SWFAction $action , int $flags )
void addColor ( int $red , int $green , int $blue [, int $a ] )
void endMask ( void )
float getRot ( void )
float getX ( void )
float getXScale ( void )
float getXSkew ( void )
float getY ( void )
float getYScale ( void )
float getYSkew ( void )
void move ( float $dx , float $dy )
void moveTo ( float $x , float $y )
void multColor ( float $red , float $green , float $blue [, float $a ] )
void remove ( void )
void rotate ( float $angle )
void rotateTo ( float $angle )
void scale ( float $dx , float $dy )
void scaleTo ( float $x [, float $y ] )
void setDepth ( int $depth )
void setMaskLevel ( int $level )
void setMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )
void setName ( string $name )
void setRatio ( float $ratio )
void skewX ( float $ddegrees )
void skewXTo ( float $degrees )
void skewY ( float $ddegrees )
void skewYTo ( float $degrees )
}

Table of Contents

  • SWFDisplayItem->addAction — Adds this SWFAction to the given SWFSprite instance
  • SWFDisplayItem->addColor — Adds the given color to this item's color transform
  • SWFDisplayItem->endMask — Another way of defining a MASK layer
  • SWFDisplayItem->getRot — Description
  • SWFDisplayItem->getX — Description
  • SWFDisplayItem->getXScale — Description
  • SWFDisplayItem->getXSkew — Description
  • SWFDisplayItem->getY — Description
  • SWFDisplayItem->getYScale — Description
  • SWFDisplayItem->getYSkew — Description
  • SWFDisplayItem->move — Moves object in relative coordinates
  • SWFDisplayItem->moveTo — Moves object in global coordinates
  • SWFDisplayItem->multColor — Multiplies the item's color transform
  • SWFDisplayItem->remove — Removes the object from the movie
  • SWFDisplayItem->rotate — Rotates in relative coordinates
  • SWFDisplayItem->rotateTo — Rotates the object in global coordinates
  • SWFDisplayItem->scale — Scales the object in relative coordinates
  • SWFDisplayItem->scaleTo — Scales the object in global coordinates
  • SWFDisplayItem->setDepth — Sets z-order
  • SWFDisplayItem->setMaskLevel — Defines a MASK layer at level
  • SWFDisplayItem->setMatrix — Sets the item's transform matrix
  • SWFDisplayItem->setName — Sets the object's name
  • SWFDisplayItem->setRatio — Sets the object's ratio
  • SWFDisplayItem->skewX — Sets the X-skew
  • SWFDisplayItem->skewXTo — Sets the X-skew
  • SWFDisplayItem->skewY — Sets the Y-skew
  • SWFDisplayItem->skewYTo — Sets the Y-skew
SWFButton->setUp
SWFDisplayItem->addAction
Ming


The SWFFill class

Introduction

The SWFFill object allows you to transform (scale, skew, rotate) bitmap and gradient fills.

swffill objects are created by the SWFShape->addFill method.

Class synopsis

SWFFill
SWFFill {
/* Methods */
void moveTo ( float $x , float $y )
void rotateTo ( float $angle )
void scaleTo ( float $x [, float $y ] )
void skewXTo ( float $x )
void skewYTo ( float $y )
}

Table of Contents

  • SWFFill->moveTo — Moves fill origin
  • SWFFill->rotateTo — Sets fill's rotation
  • SWFFill->scaleTo — Sets fill's scale
  • SWFFill->skewXTo — Sets fill x-skew
  • SWFFill->skewYTo — Sets fill y-skew
SWFDisplayItem->skewYTo
SWFFill->moveTo
Ming


The SWFFont class

Introduction

The SWFFont object represent a reference to the font definition, for us with SWFText->setFont and SWFTextField->setFont.

Class synopsis

SWFFont
SWFFont {
/* Methods */
SWFFont __construct ( string $filename )
float getAscent ( void )
float getDescent ( void )
float getLeading ( void )
string getShape ( int $code )
float getUTF8Width ( string $string )
float getWidth ( string $string )
}

Table of Contents

  • SWFFont->__construct — Loads a font definition
  • SWFFont->getAscent — Returns the ascent of the font, or 0 if not available
  • SWFFont->getDescent — Returns the descent of the font, or 0 if not available
  • SWFFont->getLeading — Returns the leading of the font, or 0 if not available
  • SWFFont->getShape — Returns the glyph shape of a char as a text string
  • SWFFont->getUTF8Width — Calculates the width of the given string in this font at full height
  • SWFFont->getWidth — Returns the string's width
SWFFill->skewYTo
SWFFont->__construct
Ming


The SWFFontChar class

Introduction

SWFFontChar.

Class synopsis

SWFFontChar
SWFFontChar {
/* Methods */
void addChars ( string $char )
void addUTF8Chars ( string $char )
}

Table of Contents

  • SWFFontChar->addChars — Adds characters to a font for exporting font
  • SWFFontChar->addUTF8Chars — Adds characters to a font for exporting font
SWFFont->getWidth
SWFFontChar->addChars
Ming


The SWFGradient class

Introduction

SWFGradient.

Class synopsis

SWFGradient
SWFGradient {
/* Methods */
void addEntry ( float $ratio , int $red , int $green , int $blue [, int $alpha = 255 ] )
SWFGradient __construct ( void )
}

Table of Contents

  • SWFGradient->addEntry — Adds an entry to the gradient list
  • SWFGradient->__construct — Creates a gradient object
SWFFontChar->addUTF8Chars
SWFGradient->addEntry
Ming


The SWFMorph class

Introduction

The methods here are sort of weird. It would make more sense to just have newSWFMorph(shape1, shape2);, but as things are now, shape2 needs to know that it's the second part of a morph. (This, because it starts writing its output as soon as it gets drawing commands- if it kept its own description of its shapes and wrote on completion this and some other things would be much easier.)

Class synopsis

SWFMorph
SWFMorph {
/* Methods */
SWFMorph __construct ( void )
SWFShape getShape1 ( void )
SWFShape getShape2 ( void )
}

Table of Contents

  • SWFMorph->__construct — Creates a new SWFMorph object
  • SWFMorph->getShape1 — Gets a handle to the starting shape
  • SWFMorph->getShape2 — Gets a handle to the ending shape
SWFGradient->__construct
SWFMorph->__construct
Ming


The SWFMovie class

Introduction

SWFMovie is a movie object representing an SWF movie.

Class synopsis

SWFMovie
SWFMovie {
/* Methods */
mixed add ( object $instance )
void addExport ( SWFCharacter $char , string $name )
mixed addFont ( SWFFont $font )
SWFMovie __construct ([ int $version ] )
SWFSprite importChar ( string $libswf , string $name )
SWFFontChar importFont ( string $libswf , string $name )
void labelFrame ( string $label )
void nextFrame ( void )
int output ([ int $compression ] )
void remove ( object $instance )
int save ( string $filename [, int $compression ] )
int saveToFile ( resource $x [, int $compression ] )
void setbackground ( int $red , int $green , int $blue )
void setDimension ( float $width , float $height )
void setFrames ( int $number )
void setRate ( float $rate )
SWFSoundInstance startSound ( SWFSound $sound )
void stopSound ( SWFSound $sound )
int streamMP3 ( mixed $mp3file [, float $skip = 0 ] )
void writeExports ( void )
}

Table of Contents

  • SWFMovie->add — Adds any type of data to a movie
  • SWFMovie->addExport — Description
  • SWFMovie->addFont — Description
  • SWFMovie->__construct — Creates a new movie object, representing an SWF version 4 movie
  • SWFMovie->importChar — Description
  • SWFMovie->importFont — Description
  • SWFMovie->labelFrame — Labels a frame
  • SWFMovie->nextFrame — Moves to the next frame of the animation
  • SWFMovie->output — Dumps your lovingly prepared movie out
  • SWFMovie->remove — Removes the object instance from the display list
  • SWFMovie->save — Saves the SWF movie in a file
  • SWFMovie->saveToFile — Description
  • SWFMovie->setbackground — Sets the background color
  • SWFMovie->setDimension — Sets the movie's width and height
  • SWFMovie->setFrames — Sets the total number of frames in the animation
  • SWFMovie->setRate — Sets the animation's frame rate
  • SWFMovie->startSound — Description
  • SWFMovie->stopSound — Description
  • SWFMovie->streamMP3 — Streams a MP3 file
  • SWFMovie->writeExports — Description
SWFMorph->getShape2
SWFMovie->add
Ming


The SWFPrebuiltClip class

Introduction

SWFPrebuiltClip.

Class synopsis

SWFPrebuiltClip
SWFPrebuiltClip {
/* Methods */
SWFPrebuiltClip __construct ( mixed $file )
}

Table of Contents

  • SWFPrebuiltClip->__construct — Returns a SWFPrebuiltClip object
SWFMovie->writeExports
SWFPrebuiltClip->__construct
Ming


The SWFShape class

Introduction

SWFShape.

Class synopsis

SWFShape
SWFShape {
/* Methods */
SWFFill addFill ( int $red , int $green , int $blue [, int $alpha = 255 ] )
SWFShape __construct ( void )
void drawArc ( float $r , float $startAngle , float $endAngle )
void drawCircle ( float $r )
int drawCubic ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
int drawCubicTo ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
int drawCurve ( float $controldx , float $controldy , float $anchordx , float $anchordy [, float $targetdx ], float $targetdy )
int drawCurveTo ( float $controlx , float $controly , float $anchorx , float $anchory [, float $targetx ], float $targety )
void drawGlyph ( SWFFont $font , string $character [, int $size ] )
void drawLine ( float $dx , float $dy )
void drawLineTo ( float $x , float $y )
void movePen ( float $dx , float $dy )
void movePenTo ( float $x , float $y )
void setLeftFill ( SWFGradient $fill )
void setLine ( SWFShape $shape )
void setRightFill ( SWFGradient $fill )
}

Table of Contents

  • SWFShape->addFill — Adds a solid fill to the shape
  • SWFShape->__construct — Creates a new shape object
  • SWFShape->drawArc — Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock
  • SWFShape->drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion
  • SWFShape->drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points
  • SWFShape->drawCubicTo — Draws a cubic bezier curve using the current position and the three given points as control points
  • SWFShape->drawCurve — Draws a curve (relative)
  • SWFShape->drawCurveTo — Draws a curve
  • SWFShape->drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font
  • SWFShape->drawLine — Draws a line (relative)
  • SWFShape->drawLineTo — Draws a line
  • SWFShape->movePen — Moves the shape's pen (relative)
  • SWFShape->movePenTo — Moves the shape's pen
  • SWFShape->setLeftFill — Sets left rasterizing color
  • SWFShape->setLine — Sets the shape's line style
  • SWFShape->setRightFill — Sets right rasterizing color
SWFPrebuiltClip->__construct
SWFShape->addFill
Ming


The SWFSound class

Introduction

SWFSound.

Class synopsis

SWFSound
SWFSound {
/* Methods */
SWFSound __construct ( string $filename [, int $flags = 0 ] )
}

Table of Contents

  • SWFSound — Returns a new SWFSound object from given file
SWFShape->setRightFill
SWFSound
Ming


The SWFSoundInstance class

Introduction

SWFSoundInstance objects are returned by the SWFSprite->startSound and SWFMovie->startSound methods.

Class synopsis

SWFSoundInstance
SWFSoundInstance {
/* Methods */
void loopCount ( int $point )
void loopInPoint ( int $point )
void loopOutPoint ( int $point )
void noMultiple ( void )
}

Table of Contents

  • SWFSoundInstance->loopCount — Description
  • SWFSoundInstance->loopInPoint — Description
  • SWFSoundInstance->loopOutPoint — Description
  • SWFSoundInstance->noMultiple — Description
SWFSound
SWFSoundInstance->loopCount
Ming


The SWFSprite class

Introduction

An SWFSprite is also known as a "movie clip", this allows one to create objects which are animated in their own timelines. Hence, the sprite has most of the same methods as the movie.

Class synopsis

SWFSprite
SWFSprite {
/* Methods */
void add ( object $object )
SWFSprite __construct ( void )
void labelFrame ( string $label )
void nextFrame ( void )
void remove ( object $object )
void setFrames ( int $number )
SWFSoundInstance startSound ( SWFSound $sount )
void stopSound ( SWFSound $sount )
}

Table of Contents

  • SWFSprite->add — Adds an object to a sprite
  • SWFSprite->__construct — Creates a movie clip (a sprite)
  • SWFSprite->labelFrame — Labels frame
  • SWFSprite->nextFrame — Moves to the next frame of the animation
  • SWFSprite->remove — Removes an object to a sprite
  • SWFSprite->setFrames — Sets the total number of frames in the animation
  • SWFSprite->startSound — Description
  • SWFSprite->stopSound — Description
SWFSoundInstance->noMultiple
SWFSprite->add
Ming


The SWFText class

Introduction

SWFText.

Class synopsis

SWFText
SWFText {
/* Methods */
void addString ( string $string )
void addUTF8String ( string $text )
void __construct ( void )
float getAscent ( void )
float getDescent ( void )
float getLeading ( void )
float getUTF8Width ( string $string )
float getWidth ( string $string )
void moveTo ( float $x , float $y )
void setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
void setFont ( SWFFont $font )
void setHeight ( float $height )
void setSpacing ( float $spacing )
}

Table of Contents

  • SWFText->addString — Draws a string
  • SWFText->addUTF8String — Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color
  • SWFText->__construct — Creates a new SWFText object
  • SWFText->getAscent — Returns the ascent of the current font at its current size, or 0 if not available
  • SWFText->getDescent — Returns the descent of the current font at its current size, or 0 if not available
  • SWFText->getLeading — Returns the leading of the current font at its current size, or 0 if not available
  • SWFText->getUTF8Width — calculates the width of the given string in this text objects current font and size
  • SWFText->getWidth — Computes string's width
  • SWFText->moveTo — Moves the pen
  • SWFText->setColor — Sets the current text color
  • SWFText->setFont — Sets the current font
  • SWFText->setHeight — Sets the current font height
  • SWFText->setSpacing — Sets the current font spacing
SWFSprite->stopSound
SWFText->addString
Ming


The SWFTextField class

Introduction

SWFTextField.

Class synopsis

SWFTextField
SWFTextField {
/* Methods */
void addChars ( string $chars )
void addString ( string $string )
void align ( int $alignement )
SWFTextField __construct ([ int $flags ] )
void setBounds ( float $width , float $height )
void setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
void setFont ( SWFFont $font )
void setHeight ( float $height )
void setIndentation ( float $width )
void setLeftMargin ( float $width )
void setLineSpacing ( float $height )
void setMargins ( float $left , float $right )
void setName ( string $name )
void setPadding ( float $padding )
void setRightMargin ( float $width )
}

Table of Contents

  • SWFTextField->addChars — adds characters to a font that will be available within a textfield
  • SWFTextField->addString — Concatenates the given string to the text field
  • SWFTextField->align — Sets the text field alignment
  • SWFTextField->__construct — Creates a text field object
  • SWFTextField->setBounds — Sets the text field width and height
  • SWFTextField->setColor — Sets the color of the text field
  • SWFTextField->setFont — Sets the text field font
  • SWFTextField->setHeight — Sets the font height of this text field font
  • SWFTextField->setIndentation — Sets the indentation of the first line
  • SWFTextField->setLeftMargin — Sets the left margin width of the text field
  • SWFTextField->setLineSpacing — Sets the line spacing of the text field
  • SWFTextField->setMargins — Sets the margins width of the text field
  • SWFTextField->setName — Sets the variable name
  • SWFTextField->setPadding — Sets the padding of this textfield
  • SWFTextField->setRightMargin — Sets the right margin width of the text field
SWFText->setSpacing
SWFTextField->addChars
Ming


The SWFVideoStream class

Introduction

SWFVideoStream.

Class synopsis

SWFVideoStream
SWFVideoStream {
/* Methods */
SWFVideoStream __construct ([ string $file ] )
int getNumFrames ( void )
void setDimension ( int $x , int $y )
}

Table of Contents

  • SWFVideoStream->__construct — Returns a SWFVideoStream object
  • SWFVideoStream->getNumFrames — Returns the number of frames in the video
  • SWFVideoStream->setDimension — Sets video dimension
SWFTextField->setRightMargin
SWFVideoStream->__construct
Ming


The KTaglib_Tag class

Introduction

Base class for ID3v1 or ID3v2 tags

Class synopsis

KTaglib_Tag
KTaglib_Tag {
}

Table of Contents

  • KTaglib_Tag::getAlbum — Returns the title string from a ID3 tag
  • KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag
  • KTaglib_Tag::getComment — Returns the comment from a ID3 tag
  • KTaglib_Tag::getGenre — Returns the genre from a ID3 tag
  • KTaglib_Tag::getTitle — Returns the title string from a ID3 tag
  • KTaglib_Tag::getTrack — Returns the track number from a ID3 tag
  • KTaglib_Tag::getYear — Returns the year from a ID3 tag
  • KTaglib_Tag::isEmpty — Returns true if the tag is empty
KTaglib_MPEG_AudioProperties::isProtectionEnabled
KTaglib_Tag::getAlbum
KTaglib


The TokyoTyrant class

Introduction

The main Tokyo Tyrant class

Class synopsis

TokyoTyrant
TokyoTyrant {
/* Constants */
const integer TokyoTyrant::RDBDEF_PORT = 1978 ;
const integer TokyoTyrant::RDBQC_STREQ = 0 ;
const integer TokyoTyrant::RDBQC_STRINC = 1 ;
const integer TokyoTyrant::RDBQC_STRBW = 2 ;
const integer TokyoTyrant::RDBQC_STREW = 3 ;
const integer TokyoTyrant::RDBQC_STRAND = 4 ;
const integer TokyoTyrant::RDBQC_STROR = 5 ;
const integer TokyoTyrant::RDBQC_STROREQ = 6 ;
const integer TokyoTyrant::RDBQC_STRRX = 7 ;
const integer TokyoTyrant::RDBQC_NUMEQ = 8 ;
const integer TokyoTyrant::RDBQC_NUMGT = 9 ;
const integer TokyoTyrant::RDBQC_NUMGE = 10 ;
const integer TokyoTyrant::RDBQC_NUMLT = 11 ;
const integer TokyoTyrant::RDBQC_NUMLE = 12 ;
const integer TokyoTyrant::RDBQC_NUMBT = 13 ;
const integer TokyoTyrant::RDBQC_NUMOREQ = 14 ;
const integer TokyoTyrant::RDBQC_NEGATE = 16777216 ;
const integer TokyoTyrant::RDBQC_NOIDX = 33554432 ;
const integer TokyoTyrant::RDBQO_STRASC = 0 ;
const integer TokyoTyrant::RDBQO_STRDESC = 1 ;
const integer TokyoTyrant::RDBQO_NUMASC = 2 ;
const integer TokyoTyrant::RDBQO_NUMDESC = 3 ;
const integer TokyoTyrant::RDBIT_LEXICAL = 0 ;
const integer TokyoTyrant::RDBIT_DECIMAL = 1 ;
const integer TokyoTyrant::RDBIT_TOKEN = 2 ;
const integer TokyoTyrant::RDBIT_QGRAM = 3 ;
const integer TokyoTyrant::RDBIT_OPT = 9998 ;
const integer TokyoTyrant::RDBIT_VOID = 9999 ;
const integer TokyoTyrant::RDBIT_KEEP = 16777216 ;
const integer TokyoTyrant::RDBQCFTS_PH = 15 ;
const integer TokyoTyrant::RDBQCFTS_AND = 16 ;
const integer TokyoTyrant::RDBQCFTS_OR = 17 ;
const integer TokyoTyrant::RDBQCFTS_EX = 18 ;
const integer TokyoTyrant::RDBXO_LCKREC = 1 ;
const integer TokyoTyrant::RDBXOLCK_GLB = 2 ;
const integer TokyoTyrant::RDBREC_INT = 1 ;
const integer TokyoTyrant::RDBREC_DBL = 2 ;
const integer TokyoTyrant::RDBMS_UNION = 0 ;
const integer TokyoTyrant::RDBMS_ISECT = 1 ;
const integer TokyoTyrant::RDBMS_DIFF = 2 ;
const integer TokyoTyrant::RDBT_RECON = 1 ;
/* Methods */
public number add ( string $key , number $increment [, int $type = 0 ] )
public TokyoTyrant connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )
public TokyoTyrant connectUri ( string $uri )
__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant copy ( string $path )
public string ext ( string $name , int $options , string $key , string $value )
public array fwmKeys ( string $prefix , int $max_recs )
public mixed get ( mixed $keys )
public TokyoTyrantIterator getIterator ( void )
public int num ( void )
public TokyoTyrant out ( mixed $keys )
public TokyoTyrant put ( mixed $keys [, string $value ] )
public TokyoTyrant putCat ( mixed $keys [, string $value ] )
public TokyoTyrant putKeep ( mixed $keys [, string $value ] )
public TokyoTyrant putNr ( mixed $keys [, string $value ] )
public mixed putShl ( string $key , string $value , int $width )
public mixed restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )
public mixed setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )
public int size ( string $key )
public array stat ( void )
public mixed sync ( void )
public TokyoTyrant tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )
public mixed vanish ( void )
}

Predefined Constants

TokyoTyrant Constants

TokyoTyrant::RDBDEF_PORT

The default port of the Tokyo Tyrant database

TokyoTyrant::RDBQC_STREQ

string is equal to

TokyoTyrant::RDBQC_STRINC

string is included in

TokyoTyrant::RDBQC_STRBW

string begins with

TokyoTyrant::RDBQC_STREW

string ends with

TokyoTyrant::RDBQC_STRAND

string includes all tokens in

TokyoTyrant::RDBQC_STROR

string includes at least one token in

TokyoTyrant::RDBQC_STROREQ

string is equal to at least one token in

TokyoTyrant::RDBQC_STRRX

string matches regular expressions of

TokyoTyrant::RDBQC_NUMEQ

number is equal to

TokyoTyrant::RDBQC_NUMGT

number is greater than

TokyoTyrant::RDBQC_NUMGE

number is greater than or equal to

TokyoTyrant::RDBQC_NUMLT

number is less than

TokyoTyrant::RDBQC_NUMLE

number is less than or equal to

TokyoTyrant::RDBQC_NUMBT

number is between two tokens of

TokyoTyrant::RDBQC_NUMOREQ

number is equal to at least one token in

TokyoTyrant::RDBQC_NEGATE

negation flag

TokyoTyrant::RDBQC_NOIDX

no index flag

TokyoTyrant::RDBQO_STRASC

string ascending

TokyoTyrant::RDBQO_STRDESC

string descending

TokyoTyrant::RDBQO_NUMASC

number ascending

TokyoTyrant::RDBQO_NUMDESC

number descending

TokyoTyrant::RDBIT_LEXICAL

lexical string

TokyoTyrant::RDBIT_DECIMAL

decimal string

TokyoTyrant::RDBIT_TOKEN

token inverted index (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBIT_QGRAM

QGRAM inverted index (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBIT_OPT

optimize

TokyoTyrant::RDBIT_VOID

void

TokyoTyrant::RDBIT_KEEP

keep existing index

TokyoTyrant::RDBQCFTS_PH

full-text search with the phrase of (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_AND

full-text search with all tokens in (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_OR

full-text search with at least one token in (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_EX

full-text search with the compound expression of (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_AND

Metasearch union between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBQCFTS_OR

Metasearch intersection between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBQCFTS_EX

Metasearch difference between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBT_RECON

Whether to reconnect on connection failure. It is recommended to have this parameter on for persistent connections

TokyoTyrant::RDBXOLCK_REC

record locking

TokyoTyrant::RDBXOLCK_GLB

global locking

TokyoTyrant::RDBREC_INT

record type int

TokyoTyrant::RDBREC_DBL

record type float (double)

TokyoTyrant::TTE_SUCCESS

success

TokyoTyrant::TTE_INVALID

invalid operation

TokyoTyrant::TTE_NOHOST

host not found

TokyoTyrant::TTE_REFUSED

connection refused

TokyoTyrant::TTE_SEND

send error

TokyoTyrant::TTE_RECV

recv error

TokyoTyrant::TTE_KEEP

record exist

TokyoTyrant::TTE_NOREC

no record found

TokyoTyrant::TTE_MISC

miscellaneous error

Table of Contents

  • TokyoTyrant::add — Adds to a numeric key
  • TokyoTyrant::connect — Connect to a database
  • TokyoTyrant::connectUri — Connects to a database
  • TokyoTyrant::__construct — Construct a new TokyoTyrant object
  • TokyoTyrant::copy — Copies the database
  • TokyoTyrant::ext — Execute a remote script
  • TokyoTyrant::fwmKeys — Returns the forward matching keys
  • TokyoTyrant::get — The get purpose
  • TokyoTyrant::getIterator — Get an iterator
  • TokyoTyrant::num — Number of records in the database
  • TokyoTyrant::out — Removes records
  • TokyoTyrant::put — Puts values
  • TokyoTyrant::putCat — Concatenates to a record
  • TokyoTyrant::putKeep — Puts a record
  • TokyoTyrant::putNr — Puts value
  • TokyoTyrant::putShl — Concatenates to a record
  • TokyoTyrant::restore — Restore the database
  • TokyoTyrant::setMaster — Set the replication master
  • TokyoTyrant::size — Returns the size of the value
  • TokyoTyrant::stat — Get statistics
  • TokyoTyrant::sync — Synchronize the database
  • TokyoTyrant::tune — Tunes connection values
  • TokyoTyrant::vanish — Empties the database
Examples
TokyoTyrant::add
tokyo_tyrant


The TokyoTyrantQuery class

Introduction

This class is used to query the table databases

Class synopsis

TokyoTyrantQuery
TokyoTyrantQuery implements Iterator , Traversable {
/* Methods */
public mixed addCond ( string $name , int $op , string $expr )
__construct ( TokyoTyrantTable $table )
public int count ( void )
public array current ( void )
public string hint ( void )
public string key ( void )
public array metaSearch ( array $queries , int $type )
public array next ( void )
public TokyoTyrantQuery out ( void )
public bool rewind ( void )
public array search ( void )
public mixed setLimit ([ int $max [, int $skip ]] )
public bool valid ( void )
}

Table of Contents

  • TokyoTyrantQuery::addCond — Adds a condition to the query
  • TokyoTyrantQuery::__construct — Construct a new query
  • TokyoTyrantQuery::count — Counts records
  • TokyoTyrantQuery::current — Returns the current element
  • TokyoTyrantQuery::hint — Get the hint string of the query
  • TokyoTyrantQuery::key — Returns the current key
  • TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries
  • TokyoTyrantQuery::next — Moves the iterator to next entry
  • TokyoTyrantQuery::out — Removes records based on query
  • TokyoTyrantQuery::rewind — Rewinds the iterator
  • TokyoTyrantQuery::search — Searches records
  • TokyoTyrantQuery::setLimit — Limit results
  • TokyoTyrantQuery::valid — Checks the validity of current item
TokyoTyrantTable::setIndex
TokyoTyrantQuery::addCond
tokyo_tyrant


The TokyoTyrantTable class

Introduction

Provides an API to the table databases. A table database can be create using the following command: ttserver -port 1979 /tmp/tt_table.tct. In Tokyo Tyrant the table API is a schemaless database which can store arbitrary amount of key-value pairs under a single primary key.

Class synopsis

TokyoTyrantTable
TokyoTyrantTable extends TokyoTyrant {
/* Methods */
public void add ( string $key , mixed $increment [, string $type ] )
public int genUid ( void )
public void get ( string $keys )
public TokyoTyrantIterator getIterator ( void )
public TokyoTyrantQuery getQuery ( void )
public void out ( mixed $keys )
public int put ( string $key , array $columns )
public void putCat ( string $key , array $columns )
public void putKeep ( string $key , array $columns )
public void putNr ( mixed $keys [, string $value ] )
public void putShl ( string $key , string $value , int $width )
public mixed setIndex ( string $column , int $type )
/* Inherited methods */
public number TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] )
public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )
public TokyoTyrant TokyoTyrant::connectUri ( string $uri )
TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant TokyoTyrant::copy ( string $path )
public string TokyoTyrant::ext ( string $name , int $options , string $key , string $value )
public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )
public mixed TokyoTyrant::get ( mixed $keys )
public TokyoTyrantIterator TokyoTyrant::getIterator ( void )
public int TokyoTyrant::num ( void )
public TokyoTyrant TokyoTyrant::out ( mixed $keys )
public TokyoTyrant TokyoTyrant::put ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putCat ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putKeep ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putNr ( mixed $keys [, string $value ] )
public mixed TokyoTyrant::putShl ( string $key , string $value , int $width )
public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )
public mixed TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )
public int TokyoTyrant::size ( string $key )
public array TokyoTyrant::stat ( void )
public mixed TokyoTyrant::sync ( void )
public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )
public mixed TokyoTyrant::vanish ( void )
}

Table of Contents

  • TokyoTyrantTable::add — Adds a record
  • TokyoTyrantTable::genUid — Generate unique id
  • TokyoTyrantTable::get — Get a row
  • TokyoTyrantTable::getIterator — Get an iterator
  • TokyoTyrantTable::getQuery — Get a query object
  • TokyoTyrantTable::out — Remove records
  • TokyoTyrantTable::put — Store a row
  • TokyoTyrantTable::putCat — Concatenates to a row
  • TokyoTyrantTable::putKeep — Put a new record
  • TokyoTyrantTable::putNr — Puts value
  • TokyoTyrantTable::putShl — Concatenates to a record
  • TokyoTyrantTable::setIndex — Sets index
TokyoTyrant::vanish
TokyoTyrantTable::add
tokyo_tyrant


The Traversable interface

Introduction

Interface to detect if a class is traversable using foreach.

Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator.

Note: Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.

Note: This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead.

Interface synopsis

Traversable
Traversable {
}

This interface has no methods, its only purpose is to be the base interface for all traversable classes.

Predefined Interfaces
Iterator
Predefined Interfaces


The ZipArchive class

Introduction

A file archive, compressed with Zip.

Class synopsis

ZipArchive
ZipArchive {
/* Properties */
/* Methods */
bool addEmptyDir ( string $dirname )
bool addFile ( string $filename [, string $localname ] )
bool addFromString ( string $localname , string $contents )
bool close ( void )
bool deleteIndex ( int $index )
bool deleteName ( string $name )
bool extractTo ( string $destination [, mixed $entries ] )
string getArchiveComment ( void )
string getCommentIndex ( int $index [, int $flags ] )
string getCommentName ( string $name [, int $flags ] )
mixed getFromIndex ( int $index [, int $flags ] )
mixed getFromName ( string $name [, int $flags ] )
string getNameIndex ( int $index )
string getStatusString ( void )
resource getStream ( string $name )
mixed locateName ( string $name [, int $flags ] )
mixed open ( string $filename [, int $flags ] )
bool renameIndex ( int $index , string $newname )
bool renameName ( string $name , string $newname )
mixed setArchiveComment ( string $comment )
mixed setCommentIndex ( int $index , string $comment )
mixed setCommentName ( string $name , string $comment )
mixed statIndex ( int $index [, int $flags ] )
mixed statName ( name $name [, int $flags ] )
mixed unchangeAll ( void )
mixed unchangeArchive ( void )
mixed unchangeIndex ( int $index )
mixed unchangeName ( string $name )
}

Properties

status

Status of the Zip Archive

statusSys

System status of the Zip Archive

numFiles

Number of files in archive

filename

File name in the file system

comment

Comment for the archive

Table of Contents

  • ZipArchive::addEmptyDir — Add a new directory
  • ZipArchive::addFile — Adds a file to a ZIP archive from the given path
  • ZipArchive::addFromString — Add a file to a ZIP archive using its contents
  • ZipArchive::close — Close the active archive (opened or newly created)
  • ZipArchive::deleteIndex — delete an entry in the archive using its index
  • ZipArchive::deleteName — delete an entry in the archive using its name
  • ZipArchive::extractTo — Extract the archive contents
  • ZipArchive::getArchiveComment — Returns the Zip archive comment
  • ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
  • ZipArchive::getCommentName — Returns the comment of an entry using the entry name
  • ZipArchive::getFromIndex — Returns the entry contents using its index.
  • ZipArchive::getFromName — Returns the entry contents using its name.
  • ZipArchive::getNameIndex — Returns the name of an entry using its index
  • ZipArchive::GetStatusString — Returns the status error message, system and/or zip messages.
  • ZipArchive::getStream — Get a file handler to the entry defined by its name (read only).
  • ZipArchive::locateName — Returns the index of the entry in the archive
  • ZipArchive::open — Open a ZIP file archive
  • ZipArchive::renameIndex — Renames an entry defined by its index
  • ZipArchive::renameName — Renames an entry defined by its name
  • ZipArchive::setArchiveComment — Set the comment of a ZIP archive
  • ZipArchive::setCommentIndex — Set the comment of an entry defined by its index
  • ZipArchive::setCommentName — Set the comment of an entry defined by its name
  • ZipArchive::statIndex — Get the details of an entry defined by its index.
  • ZipArchive::statName — Get the details of an entry defined by its name.
  • ZipArchive::unchangeAll — Undo all changes done in the archive.
  • ZipArchive::unchangeArchive — Revert all global changes done in the archive.
  • ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index.
  • ZipArchive::unchangeName — Revert all changes done to an entry with the given name.
Examples
ZipArchive::addEmptyDir
Zip


Sort array maintaining index association

Collator
Collator::compare
Collator
PHP Manual

Collator::asort

collator_asort

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::asort -- collator_asort — Sort array maintaining index association

Description

Object oriented style

bool Collator::asort ( array &$arr [, int $sort_flag ] )

Procedural style

bool collator_asort ( Collator $coll , array &$arr [, int $sort_flag ] )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. Array elements will have sort order according to current locale rules.

Equivalent to standard PHP asort().

Parameters

coll

Collator object.

arr

Array of strings to sort.

sort_flag

Optional sorting type, one of the following:

  • Collator::SORT_REGULAR - compare items normally (don't change types)

  • Collator::SORT_NUMERIC - compare items numerically

  • Collator::SORT_STRING - compare items as strings

Default $sort_flag value is Collator::SORT_REGULAR. It is also used if an invalid $sort_flag value has been specified.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 collator_asort()example

<?php
$coll = collator_create( 'en_US' );
$arr = array(
     'a' => '100',
     'b' => '50',
     'c' => '7'
);
collator_asort( $coll, $arr, Collator::SORT_NUMERIC );
var_export( $arr );

collator_asort( $coll, $arr, Collator::SORT_STRING );
var_export( $arr );
?>

The above example will output:

array (
  'c' => '7',
  'b' => '50',
  'a' => '100',
)array (
  'a' => '100',
  'b' => '50',
  'c' => '7',
)

See Also

  • Collator constants
  • collator_sort() - Sort array using specified collator
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

Collator
Collator::compare
Collator


Compare two Unicode strings

Collator::asort
Collator::__construct
Collator
PHP Manual

Collator::compare

collator_compare

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::compare -- collator_compare — Compare two Unicode strings

Description

Object oriented style

int Collator::compare ( string $str1 , string $str2 )

Procedural style

int collator_compare ( Collator $coll , string $str1 , string $str2 )

Compare two Unicode strings according to collation rules.

Parameters

coll

Collator object.

str1

The first string to compare.

str2

The second string to compare.

Return Values

Return comparison result:

  • 1 if str1 is greater than str2 ;

  • 0 if str1 is equal to str2 ;

  • -1 if str1 is less than str2 .

On error boolean FALSE is returned.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 collator_compare()example

<?php
$s1 = 'Hello';
$s2 = 'hello';

$coll = collator_create( 'en_US' );
$res  = collator_compare( $coll, $s1, $s2 );

if ($res === false) {
    echo collator_get_error_message( $coll );
} else if( $res > 0 ) {
    echo "s1 is greater than s2\n";
} else if( $res < 0 ) {
    echo "s1 is less than s2\n";
} else {
    echo "s1 is equal to s2\n";
}
?>

The above example will output:

s1 is greater than s2

See Also

  • collator_sort() - Sort array using specified collator

Collator::asort
Collator::__construct
Collator


Create a collator

Collator::compare
Collator::create
Collator
PHP Manual

Collator::__construct

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::__construct — Create a collator

Description

Collator::__construct ( string $locale )

Creates a new instance of Collator.

Parameters

locale

The locale whose collation rules should be used. Special values for locales can be passed in - if null is passed for the locale, the default locale collation rules will be used. If empty string ("") or "root" are passed, UCA rules will be used.

The Locale attribute is typically the most important attribute for correct sorting and matching, according to the user expectations in different countries and regions. The default » UCA ordering will only sort a few languages such as Dutch and Portuguese correctly ("correctly" meaning according to the normal expectations for users of the languages). Otherwise, you need to supply the locale to UCA in order to properly collate text for a given language. Thus a locale needs to be supplied so as to choose a collator that is correctly tailored for that locale. The choice of a locale will automatically preset the values for all of the attributes to something that is reasonable for that locale. Thus most of the time the other attributes do not need to be explicitly set. In some cases, the choice of locale will make a difference in string comparison performance and/or sort key length.

Return Values

Returns Collator instance.

Errors/Exceptions

Returns an "empty" object on error. You can use intl_get_error_code() and/or intl_get_error_message() to know what happened.

Examples

Example #1 Collator::__construct() example

<?php
$coll = new Collator( 'en_CA' );
?>

See Also

  • Collator::create() - Create a collator
  • collator_create() - Create a collator

Collator::compare
Collator::create
Collator


Create a collator

Collator::__construct
Collator::getAttribute
Collator
PHP Manual

Collator::create

collator_create

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::create -- collator_create — Create a collator

Description

Object oriented style

static Collator Collator::create ( string $locale )

Procedural style

Collator collator_create ( string $locale )

The strings will be compared using the options already specified.

Parameters

locale

The locale containing the required collation rules. Special values for locales can be passed in - if null is passed for the locale, the default locale collation rules will be used. If empty string ("") or "root" are passed, UCA rules will be used.

Return Values

Return new instance of Collator object, or NULL on error.

Examples

Example #1 collator_create() example

<?php
$coll = collator_create( 'en_US' );

if( !isset( $coll ) ) {
    printf( "Collator creation failed: %s\n", intl_get_error_message() );
    exit( 1 );
}
?>

See Also

  • Collator::__construct() - Create a collator

Collator::__construct
Collator::getAttribute
Collator


Get collation attribute value

Collator::create
Collator::getErrorCode
Collator
PHP Manual

Collator::getAttribute

collator_get_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getAttribute -- collator_get_attribute — Get collation attribute value

Description

Object oriented style

int Collator::getAttribute ( int $attr )

Procedural style

int collator_get_attribute ( Collator $coll , int $attr )

Get a value of an integer collator attribute.

Parameters

coll

Collator object.

attr

Attribute to get value for.

Return Values

Attribute value, or boolean FALSE on error.

Examples

Example #1 collator_get_attribute() example

<?php
$coll = collator_create( 'en_CA' );
$val = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if( $val === false )
{
    // Handle error.
}
?>

See Also

  • Collator constants
  • collator_set_attribute() - Set collation attribute
  • collator_get_strength() - Get current collation strength

Collator::create
Collator::getErrorCode
Collator


Get collator's last error code

Collator::getAttribute
Collator::getErrorMessage
Collator
PHP Manual

Collator::getErrorCode

collator_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getErrorCode -- collator_get_error_code — Get collator's last error code

Description

Object oriented style

int Collator::getErrorCode ( void )

Procedural style

int collator_get_error_code ( Collator $coll )

Parameters

coll

Collator object.

Return Values

Error code returned by the last Collator API function call.

Examples

Example #1 collator_get_error_code() example

<?php
$coll = collator_create( 'en_US' );
if( collator_get_attribute( $coll, Collator::FRENCH_COLLATION ) === false )
        handle_error( collator_get_error_code() );
?>

See Also

  • collator_get_error_message() - Get text for collator's last error code

Collator::getAttribute
Collator::getErrorMessage
Collator


Get text for collator's last error code

Collator::getErrorCode
Collator::getLocale
Collator
PHP Manual

Collator::getErrorMessage

collator_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getErrorMessage -- collator_get_error_message — Get text for collator's last error code

Description

Object oriented style

string Collator::getErrorMessage ( void )

Procedural style

string collator_get_error_message ( Collator $coll )

Retrieves the message for the last error.

Parameters

coll

Collator object.

Return Values

Description of an error occurred in the last Collator API function call.

Examples

Example #1 collator_get_error_message() example

<?php
$coll = collator_create( 'lt' );
if( collator_compare( $coll, 'y', 'k' ) === false ) {
    echo collator_get_error_message( $coll );
}
?>

See Also

  • collator_get_error_code() - Get collator's last error code

Collator::getErrorCode
Collator::getLocale
Collator


Get the locale name of the collator

Collator::getErrorMessage
Collator::getSortKey
Collator
PHP Manual

Collator::getLocale

collator_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getLocale -- collator_get_locale — Get the locale name of the collator

Description

Object oriented style

string Collator::getLocale ([ int $type ] )

Procedural style

string collator_get_locale ( Collator $coll , int $type )

Get collector locale name.

Parameters

coll

Collator object.

type

You can choose between valid and actual locale ( Locale::VALID_LOCALE and Locale::ACTUAL_LOCALE, respectively). The default is the actual locale.

Return Values

Real locale name from which the collation data comes. If the collator was instantiated from rules or an error occurred, returns boolean FALSE.

Examples

Example #1 collator_get_locale() example

<?php
$coll    = collator_create( 'en_US_California' );
$res_val = collator_get_locale( $coll, Locale::VALID_LOCALE );
$res_act = collator_get_locale( $coll, Locale::ACTUAL_LOCALE );
printf( "Valid locale name: %s\nActual locale name: %s\n",
         $res_req, $res_val, $res_act );
?>

The above example will output:

Requested locale name: en_US_California
Valid locale name: en_US
Actual locale name: en

See Also

  • collator_create() - Create a collator

Collator::getErrorMessage
Collator::getSortKey
Collator


Get sorting key for a string

Collator::getLocale
Collator::getStrength
Collator
PHP Manual

Collator::getSortKey

collator_get_sort_key

(No version information available, might only be in SVN)

Collator::getSortKey -- collator_get_sort_key — Get sorting key for a string

Description

Object oriented style

string Collator::getSortKey ( string $str )

Procedural style

string collator_get_sort_key ( Collator $coll , string $str )

Return collation key for a string.

Parameters

coll

Collator object.

str

The string to produce the key from.

Return Values

Returns the collation key for the string. Collation keys can be compared directly instead of strings.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 collator_get_sort_key()example

<?php
$s1 = 'Hello';

$coll = collator_create( 'en_US' );
$res  = collator_get_sort_key( $coll, $s1);

echo urlencode($res);
?>

The above example will output:

71%3F%3FE%01%09%01%8F%08%00

See Also

  • collator_sort() - Sort array using specified collator
  • collator_sort_with_keys()

Collator::getLocale
Collator::getStrength
Collator


Get current collation strength

Collator::getSortKey
Collator::setAttribute
Collator
PHP Manual

Collator::getStrength

collator_get_strength

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getStrength -- collator_get_strength — Get current collation strength

Description

Object oriented style

int Collator::getStrength ( void )

Procedural style

int collator_get_strength ( Collator $coll )

Parameters

coll

Collator object.

Return Values

Returns current collation strength, or boolean FALSE on error.

Examples

Example #1 collator_get_strength() example

<?php
$coll     = collator_create( 'en_US' );
$strength = collator_get_strength( $coll );
?>

See Also

  • Collator constants
  • collator_set_strength() - Set collation strength
  • collator_get_attribute() - Get collation attribute value

Collator::getSortKey
Collator::setAttribute
Collator


Set collation attribute

Collator::getStrength
Collator::setStrength
Collator
PHP Manual

Collator::setAttribute

collator_set_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::setAttribute -- collator_set_attribute — Set collation attribute

Description

Object oriented style

bool Collator::setAttribute ( int $attr , int $val )

Procedural style

bool collator_set_attribute ( Collator $coll , int $attr , int $val )

Parameters

coll

Collator object.

attr

Attribute.

val

Attribute value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 collator_set_attribute() example

<?php
$coll = collator_create( 'en_CA' );
$val  = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if ($val === false) {
    // Handle error.
} elseif ($val === Collator::ON) {
    // Do something useful.
}
?>

See Also

  • Collator constants
  • collator_get_attribute() - Get collation attribute value
  • collator_set_strength() - Set collation strength

Collator::getStrength
Collator::setStrength
Collator


Set collation strength

Collator::setAttribute
Collator::sortWithSortKeys
Collator
PHP Manual

Collator::setStrength

collator_set_strength

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::setStrength -- collator_set_strength — Set collation strength

Description

Object oriented style

bool Collator::setStrength ( int $strength )

Procedural style

bool collator_set_strength ( Collator $coll , int $strength )

The » ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions.

  1. Primary Level: Typically, this is used to denote differences between base characters (for example, "a" < "b"). It is the strongest difference. For example, dictionaries are divided into different sections by base character. This is also called the level1 strength.

  2. Secondary Level: Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings. This is also called the level2 strength.

    Note: Note: In some languages (such as Danish), certain accented letters are considered to be separate base characters. In most languages, however, an accented letter only has a secondary difference from the unaccented version of that letter.

  3. Tertiary Level: Upper and lower case differences in characters are distinguished at the tertiary level (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary level (such as "A" and " "). Another example is the difference between large and small Kana. A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings. This is also called the level3 strength.

  4. Quaternary Level: When punctuation is ignored (see Ignoring Punctuations ) at level 13, an additional level can be used to distinguish words with and without punctuation (for example, "ab" < "a-b" < "aB"). This difference is ignored when there is a primary, secondary or tertiary difference. This is also known as the level4 strength. The quaternary level should only be used if ignoring punctuation is required or when processing Japanese text (see Hiragana processing).

  5. Identical Level: When all other levels are equal, the identical level is used as a tiebreaker. The Unicode code point values of the NFD form of each string are compared at this level, just in case there is no difference at levels 14. For example, Hebrew cantillation marks are only distinguished at this level. This level should be used sparingly, as only code point values differences between two strings is an extremely rare occurrence. Using this level substantially decreases the performance for both incremental comparison and sort key generation (as well as increasing the sort key length). It is also known as level 5 strength.

For example, people may choose to ignore accents or ignore accents and case when searching for text. Almost all characters are distinguished by the first three levels, and in most locales the default value is thus Tertiary. However, if Alternate is set to be Shifted, then the Quaternary strength can be used to break ties among whitespace, punctuation, and symbols that would otherwise be ignored. If very fine distinctions among characters are required, then the Identical strength can be used (for example, Identical Strength distinguishes between the Mathematical Bold Small A and the Mathematical Italic Small A.). However, using levels higher than Tertiary the Identical strength result in significantly longer sort keys, and slower string comparison performance for equal strings.

Parameters

coll

Collator object.

strength

Strength to set.

Possible values are:

  • Collator::PRIMARY

  • Collator::SECONDARY

  • Collator::TERTIARY

  • Collator::QUATERNARY

  • Collator::IDENTICAL

  • Collator::DEFAULT

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 collator_set_strength() example

<?php
$arr  = array( 'aò', 'Ao', 'ao' );
$coll = collator_create( 'en_US' );

// Sort array using default strength.
collator_sort( $coll, $arr );
var_export( $arr );

// Sort array using primary strength.
collator_set_strength( $coll, Collator::PRIMARY );
collator_sort( $coll, $arr );
var_export( $arr );
?>

The above example will output:

array (
  0 => 'ao',
  1 => 'Ao',
  2 => 'aò',
)
array (
  0 => 'aò',
  1 => 'Ao',
  2 => 'ao',
)

See Also

  • Collator constants
  • collator_get_strength() - Get current collation strength

Collator::setAttribute
Collator::sortWithSortKeys
Collator


Sort array using specified collator

Collator::sortWithSortKeys
NumberFormatter
Collator
PHP Manual

Collator::sort

collator_sort

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::sort -- collator_sort — Sort array using specified collator

Description

Object oriented style

bool Collator::sort ( array &$arr [, int $sort_flag ] )

Procedural style

bool collator_sort ( Collator $coll , array &$arr [, int $sort_flag ] )

This function sorts an array according to current locale rules.

Equivalent to standard PHP sort() .

Parameters

coll

Collator object.

arr

Array of strings to sort.

sort_flag

Optional sorting type, one of the following:

  • Collator::SORT_REGULAR - compare items normally (don't change types)

  • Collator::SORT_NUMERIC - compare items numerically

  • Collator::SORT_STRING - compare items as strings

Default sorting type is Collator::SORT_REGULAR.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 collator_sort() example

<?php
$coll = collator_create( 'en_US' );
$arr  = array( 'at', 'às', 'as' );

var_export( $arr );
collator_sort( $coll, $arr );
var_export( $arr );
?>

The above example will output:

array (
  0 => 'at',
  1 => 'às',
  2 => 'as',
)array (
  0 => 'as',
  1 => 'às',
  2 => 'at',
)

See Also

  • Collator constants
  • collator_asort() - Sort array maintaining index association
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

Collator::sortWithSortKeys
NumberFormatter
Collator


Sort array using specified collator and sort keys

Collator::setStrength
Collator::sort
Collator
PHP Manual

Collator::sortWithSortKeys

collator_sort_with_sort_keys

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::sortWithSortKeys -- collator_sort_with_sort_keys — Sort array using specified collator and sort keys

Description

Object oriented style

bool Collator::sortWithSortKeys ( array &$arr )

Procedural style

bool collator_sort_with_sort_keys ( Collator $coll , array &$arr )

Similar to collator_sort() but uses ICU sorting keys produced by ucol_getSortKey() to gain more speed on large arrays.

Parameters

coll

Collator object.

arr

Array of strings to sort

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 collator_sort_with_sort_keys() example

<?php
$arr  = array( 'Köpfe', 'Kypper', 'Kopfe' );
$coll = collator_create( 'sv' );

collator_sort_with_sort_keys( $coll, $arr );
var_export( $arr );
?>

The above example will output:

array (
  0 => 'Kopfe',
  1 => 'Kypper',
  2 => 'Köpfe',
)

See Also

  • Collator constants
  • collator_sort() - Sort array using specified collator
  • collator_asort() - Sort array maintaining index association

Collator::setStrength
Collator::sort
Collator


Runtime Configuration

Table of Contents

  • The configuration file
  • .user.ini files
  • Where a configuration setting may be set
  • How to change configuration settings
Bug reports
The configuration file
Installation and Configuration


How to change configuration settings

Running PHP as an Apache module

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

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

php_value name value

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

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

php_flag name on|off

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

php_admin_value name value

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

php_admin_flag name on|off

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

Example #1 Apache configuration example

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

Caution

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

Changing PHP configuration via the Windows registry

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

Other interfaces to PHP

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

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

Where a configuration setting may be set
Language Reference
Runtime Configuration


Where a configuration setting may be set

These modes determine when and where a PHP directive may or may not be set, and each directive within the manual refers to one of these modes. For example, some settings may be set within a PHP script using ini_set(), whereas others may require php.ini or httpd.conf.

For example, the output_buffering setting is PHP_INI_PERDIR therefore it may not be set using ini_set(). However, the display_errors directive is PHP_INI_ALL therefore it may be set anywhere, including with ini_set().

Definition of PHP_INI_* modes
Mode | Value | Meaning
PHP_INI_USER | 1 | Entry can be set in user scripts (like with ini_set()) or in the Windows registry
PHP_INI_PERDIR | 6 | Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM | 4 | Entry can be set in php.ini or httpd.conf
PHP_INI_ALL | 7 | Entry can be set anywhere

.user.ini files
How to change configuration settings
Runtime Configuration


The configuration file

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

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

  • SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)

  • The PHPRC environment variable. Before PHP 5.2.0 this was checked after the registry key mentioned below.

  • As of PHP 5.2.0, the location of the php.ini file can be set for different versions of PHP. The following registry keys are examined in order: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z], [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] and [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x], where x, y and z mean the PHP major, minor and release versions. If there is a value for IniFilePath in these keys, then the first one found will be used as the location of the php.ini (Windows only).

  • [HKEY_LOCAL_MACHINE\SOFTWARE\PHP], value of IniFilePath (Windows only).

  • Current working directory (except CLI)

  • The web server's directory (for SAPI modules), or directory of PHP (otherwise in Windows)

  • Windows directory (C:\windows or C:\winnt) (for Windows), or --with-config-file-path compile time option

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

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

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

Example #1 php.ini example

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

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

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

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

Runtime Configuration
.user.ini files
Runtime Configuration


.user.ini files

Since PHP 5.3.0, PHP includes support for .htaccess-style INI files on a per-directory basis. These files are processed only by the CGI/FastCGI SAPI. This functionality obsoletes the PECL htscanner extension. If you are using Apache, use .htaccess files for the same effect.

In addition to the main php.ini file, PHP scans for INI files in each directory, starting with the directory of the requested PHP file, and working its way up to the current document root (as set in $_SERVER['DOCUMENT_ROOT']). Only INI settings with the modes PHP_INI_PERDIR and PHP_INI_USER will be recognized in .user.ini-style INI files.

Two new INI directives, user_ini.filename and user_ini.cache_ttl control the use of user INI files.

user_ini.filename sets the name of the file PHP looks for in each directory; if set to an empty string, PHP doesn't scan at all. The default is .user.ini.

user_ini.cache_ttl controls how often user INI files are re-read. The default is 300 seconds (5 minutes).

The configuration file
Where a configuration setting may be set
Runtime Configuration


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

DBX_MYSQL (integer)
DBX_ODBC (integer)
DBX_PGSQL (integer)
DBX_MSSQL (integer)
DBX_FBSQL (integer)
DBX_OCI8 (integer) (available from PHP 4.3.0)
DBX_SYBASECT (integer)
DBX_SQLITE (integer) (PHP 5)
DBX_PERSISTENT (integer)
DBX_RESULT_INFO (integer)
DBX_RESULT_INDEX (integer)
DBX_RESULT_ASSOC (integer)
DBX_RESULT_UNBUFFERED (integer) (PHP 5)
DBX_COLNAMES_UNCHANGED (integer) (available from PHP 4.3.0)
DBX_COLNAMES_UPPERCASE (integer) (available from PHP 4.3.0)
DBX_COLNAMES_LOWERCASE (integer) (available from PHP 4.3.0)
DBX_CMP_NATIVE (integer)
DBX_CMP_TEXT (integer)
DBX_CMP_NUMBER (integer)
DBX_CMP_ASC (integer)
DBX_CMP_DESC (integer)
Resource Types
dbx Functions
dbx


Newt Anchors

Newt Anchors
constant | meaning
NEWT_ANCHOR_LEFT |
NEWT_ANCHOR_RIGHT |
NEWT_ANCHOR_TOP |
NEWT_ANCHOR_BOTTOM |
Newt Keys
Grid Flags
Predefined Constants


Newt argument flags

Newt argument flags
constant | meaning
NEWT_ARG_LAST |
NEWT_ARG_APPEND |
Newt colorsets
Newt Flags Sense
Predefined Constants


Checkbox Tree Flags

Checkbox Tree Flags
constant | meaning
NEWT_CHECKBOXTREE_UNSELECTABLE |
NEWT_CHECKBOXTREE_HIDE_BOX |
NEWT_CHECKBOXTREE_COLLAPSED |
NEWT_CHECKBOXTREE_EXPANDED |
NEWT_CHECKBOXTREE_UNSELECTED |
NEWT_CHECKBOXTREE_SELECTED |
File Descriptor Flags
Entry Flags
Predefined Constants


Newt colorsets

Newt colorsets
constant | meaning
NEWT_COLORSET_ROOT |
NEWT_COLORSET_BORDER |
NEWT_COLORSET_WINDOW |
NEWT_COLORSET_SHADOW |
NEWT_COLORSET_TITLE |
NEWT_COLORSET_BUTTON |
NEWT_COLORSET_ACTBUTTON |
NEWT_COLORSET_CHECKBOX |
NEWT_COLORSET_ACTCHECKBOX |
NEWT_COLORSET_ENTRY |
NEWT_COLORSET_LABEL |
NEWT_COLORSET_LISTBOX |
NEWT_COLORSET_ACTLISTBOX |
NEWT_COLORSET_TEXTBOX |
NEWT_COLORSET_ACTTEXTBOX |
NEWT_COLORSET_HELPLINE |
NEWT_COLORSET_ROOTTEXT |
NEWT_COLORSET_ROOTTEXT |
NEWT_COLORSET_EMPTYSCALE |
NEWT_COLORSET_FULLSCALE |
NEWT_COLORSET_DISENTRY |
NEWT_COLORSET_COMPACTBUTTON |
NEWT_COLORSET_ACTSELLISTBOX |
NEWT_COLORSET_SELLISTBOX |
Newt form exit reasons
Newt argument flags
Predefined Constants


Newt Components Flags

Newt Components Flags
constant | meaning
NEWT_FLAG_RETURNEXIT | Exit form, when component is activated
NEWT_FLAG_HIDDEN | Component is hidden
NEWT_FLAG_SCROLL | Component is scrollable
NEWT_FLAG_DISABLED | Component is disabled
NEWT_FLAG_BORDER |
NEWT_FLAG_WRAP | Wrap text
NEWT_FLAG_NOF12 | Don't exit form on pressing F12
NEWT_FLAG_MULTIPLE |
NEWT_FLAG_SELECTED | Component is selected
NEWT_FLAG_CHECKBOX | Component is checkbox
NEWT_FLAG_PASSWORD | Entry component is password entry
NEWT_FLAG_SHOWCURSOR | Show cursor
Newt Flags Sense
File Descriptor Flags
Predefined Constants


Entry Flags

Entry Flags
constant | meaning
NEWT_ENTRY_SCROLL |
NEWT_ENTRY_HIDDEN |
NEWT_ENTRY_RETURNEXIT |
NEWT_ENTRY_DISABLED |
Checkbox Tree Flags
Listbox Flags
Predefined Constants


File Descriptor Flags

File Descriptor Flags
constant | meaning
NEWT_FD_READ |
NEWT_FD_WRITE |
NEWT_FD_EXCEPT |
Newt Components Flags
Checkbox Tree Flags
Predefined Constants


Form Flags

Form Flags
constant | meaning
NEWT_FORM_NOF12 | Don't exit form on F12 press
Textbox Flags
Newt Keys
Predefined Constants


Grid Flags

Grid Flags
constant | meaning
NEWT_GRID_FLAG_GROWX |
NEWT_GRID_FLAG_GROWY |
NEWT_GRID_EMPTY |
NEWT_GRID_COMPONENT |
NEWT_GRID_SUBGRID |
Newt Anchors
Examples
Predefined Constants


Newt Keys

Newt Keys
constant | meaning
NEWT_KEY_TAB |
NEWT_KEY_ENTER |
NEWT_KEY_SUSPEND |
NEWT_KEY_ESCAPE |
NEWT_KEY_RETURN |
NEWT_KEY_EXTRA_BASE |
NEWT_KEY_UP |
NEWT_KEY_DOWN |
NEWT_KEY_LEFT |
NEWT_KEY_RIGHT |
NEWT_KEY_BKSPC |
NEWT_KEY_DELETE |
NEWT_KEY_HOME |
NEWT_KEY_END |
NEWT_KEY_UNTAB |
NEWT_KEY_PGUP |
NEWT_KEY_PGDN |
NEWT_KEY_INSERT |
NEWT_KEY_F1 |
NEWT_KEY_F2 |
NEWT_KEY_F3 |
NEWT_KEY_F4 |
NEWT_KEY_F5 |
NEWT_KEY_F6 |
NEWT_KEY_F7 |
NEWT_KEY_F8 |
NEWT_KEY_F9 |
NEWT_KEY_F10 |
NEWT_KEY_F11 |
NEWT_KEY_F12 |
NEWT_KEY_RESIZE |
Form Flags
Newt Anchors
Predefined Constants


Listbox Flags

Listbox Flags
constant | meaning
NEWT_LISTBOX_RETURNEXIT |
Entry Flags
Textbox Flags
Predefined Constants


Newt form exit reasons

Newt form exit reasons
constant | meaning
NEWT_EXIT_HOTKEY | hotkey defined by newt_form_add_hot_key() was pressed
NEWT_EXIT_COMPONENT | some component has caused form to exit
NEWT_EXIT_FDREADY | file descriptor specified in newt_form_watch_fd() is ready to be read or written to
NEWT_EXIT_TIMER | time specified in newt_form_set_timer() has elapsed
Predefined Constants
Newt colorsets
Predefined Constants


Newt Flags Sense

Newt Flags Sense
constant | meaning
NEWT_FLAGS_SET |
NEWT_FLAGS_RESET |
NEWT_FLAGS_TOGGLE |
Newt argument flags
Newt Components Flags
Predefined Constants


Textbox Flags

Textbox Flags
constant | meaning
NEWT_TEXTBOX_WRAP | Wrap text in the textbox
NEWT_TEXTBOX_SCROLL | Scroll text in the textbox
Listbox Flags
Form Flags
Predefined Constants


Context options and parameters

PHP offers various context options and parameters which can be used with all
filesystem and stream wrappers. The context is created with
stream_context_create(). Options are set with
stream_context_set_option() and parameters with
stream_context_set_params().

Table of Contents

  • Socket context options — Socket context option listing
  • HTTP context options — HTTP context option listing
  • FTP context options — FTP context option listing
  • SSL context options — SSL context option listing
  • CURL context options — CURL context option listing
  • Phar context options — Phar context option listing
  • Context parameters — Context parameter listing
Serializable::unserialize
Socket context options
Language Reference


CURL context option listing

SSL context options
Phar context options
Context options and parameters
PHP Manual

CURL context options

CURL context options — CURL context option listing

Description

CURL context options are available when the CURL extension was compiled using the --with-curlwrappers configure option.

Options

method string

GET, POST, or any other HTTP method supported by the remote server.

Defaults to GET.

header string

Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).

user_agent string

Value to send with User-Agent: header.

By default the user_agent php.ini setting is used.

content string

Additional data to be sent after the headers. This option is not used for GET or HEAD requests.

proxy string

URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).

max_redirects integer

The max number of redirects to follow. Value 1 or less means that no redirects are followed.

Defaults to 20.

curl_verify_ssl_host boolean

Verify the host.

Defaults to FALSE

Note: This option is available for both the http and ftp protocol wrappers.

curl_verify_ssl_peer boolean

Require verification of SSL certificate used.

Defaults to FALSE

Note: This option is available for both the http and ftp protocol wrappers.

Examples

Example #1 Fetch a page and send POST data

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

See Also

  • Socket context options

SSL context options
Phar context options
Context options and parameters


FTP context option listing

HTTP context options
SSL context options
Context options and parameters
PHP Manual

FTP context options

FTP context options — FTP context option listing

Description

Context options for ftp:// and ftps:// transports.

Options

overwrite boolean

Allow overwriting of already existing files on remote server. Applies to write mode (uploading) only.

Defaults to FALSE.

resume_pos integer

File offset at which to begin transfer. Applies to read mode (downloading) only.

Defaults to 0 (Beginning of File).

proxy string

Proxy FTP request via http proxy server. Applies to file read operations only. Ex: tcp://squid.example.com:8000.

Changelog

Version | Description
5.1.0 | Added proxy .
5.0.0 | Added overwrite and resume_pos .

Notes

Note: Underlying socket stream context options
Additional context options may be supported by the underlying transport For ftp:// streams, refer to context options for the tcp:// transport. For ftps:// streams, refer to context options for the ssl:// transport.

See Also

  • Socket context options
  • SSL context options

HTTP context options
SSL context options
Context options and parameters


HTTP context option listing

Socket context options
FTP context options
Context options and parameters
PHP Manual

HTTP context options

HTTP context options — HTTP context option listing

Description

Context options for http:// and https:// transports.

Options

method string

GET, POST, or any other HTTP method supported by the remote server.

Defaults to GET.

header string

Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).

user_agent string

Value to send with User-Agent: header. This value will only be used if user-agent is not specified in the header context option above.

By default the user_agent php.ini setting is used.

content string

Additional data to be sent after the headers. Typically used with POST or PUT requests.

proxy string

URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).

request_fulluri boolean

When set to TRUE, the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it.

Defaults to FALSE.

max_redirects integer

The max number of redirects to follow. Value 1 or less means that no redirects are followed.

Defaults to 20.

protocol_version float

HTTP protocol version.

Defaults to 1.0.

Note: PHP prior to 5.3.0 does not implement chunked transfer decoding. If this value is set to 1.1 it is your responsibility to be 1.1 compliant.

timeout float

Read timeout in seconds, specified by a float (e.g. 10.5).

By default the default_socket_timeout php.ini setting is used.

ignore_errors boolean

Fetch the content even on failure status codes.

Defaults to FALSE

Changelog

Version | Description
5.3.0 | The protocol_version supports chunked transfer decoding when set to 1.1.
5.2.10 | Added ignore_errors .
5.2.1 | Added timeout .
5.2.10 | The header can now be an numerically indexed array.
5.1.0 | Added HTTPS proxying through HTTP proxies.
5.1.0 | Added max_redirects .
5.1.0 | Added protocol_version .

Examples

Example #1 Fetch a page and send POST data

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

Example #2 Ignore redirects but fetch headers and content

<?php

$url = "http://www.example.org/header.php";

$opts = array(
       'http' => array('method' => 'GET',
                                       'max_redirects' => '0',
                                       'ignore_errors' => '1')
       );

$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);

// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));

// actual data at $url
var_dump(stream_get_contents($stream));
fclose($stream);
?>

Notes

Note: Underlying socket stream context options
Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.

See Also

  • Socket context options
  • SSL context options

Socket context options
FTP context options
Context options and parameters


Context parameter listing

Phar context options
Security
Context options and parameters
PHP Manual

Context parameters

Context parameters — Context parameter listing

Description

These parameters can be set on a context using the stream_context_set_params() function.

Parameters

notification callback

A callback to be called when an event occurs on a stream.

See stream_notification_callback() for more details.

Phar context options
Security
Context options and parameters


Phar context option listing

CURL context options
Context parameters
Context options and parameters
PHP Manual

Phar context options

Phar context options — Phar context option listing

Description

Context options for phar:// wrapper.

Options

compress int

One of Phar compression constants.

metadata mixed

Phar metadata. See Phar::setMetadata().

See Also

  • Phar context options
  • Phar stream wrapper

CURL context options
Context parameters
Context options and parameters


Socket context option listing

Context options and parameters
HTTP context options
Context options and parameters
PHP Manual

Socket context options

Socket context options — Socket context option listing

Description

Socket context options are available for all wrappers that work over sockets, like tcp, http and ftp.

Options

bindto

Used to specify the IP address (either IPv4 or IPv6) and/or the port number that PHP will use to access the network. The syntax is ip:port. Setting the IP or the port to 0 will let the system choose the IP and/or port.

Note: As FTP creates two socket connections during normal operation, the port number cannot be specified using this option.

Changelog

Version | Description
5.1.0 | Added bindto.

Examples

Example #1 Basic bindto usage example

<?php
// connect to the internet using the '192.168.0.100' IP
$opts = array(
    'socket' => array(
        'bindto' => '192.168.0.100:0',
    ),
);

// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array(
    'socket' => array(
        'bindto' => '192.168.0.100:7000',
    ),
);

// connect to the internet using port '7000'
$opts = array(
    'socket' => array(
        'bindto' => '0:7000',
    ),
);

// create the context...
$context = stream_context_create($opts);

// ...and use it to fetch the data
echo file_get_contents('http://www.example.com', false, $context);

?>

Context options and parameters
HTTP context options
Context options and parameters


SSL context option listing

FTP context options
CURL context options
Context options and parameters
PHP Manual

SSL context options

SSL context options — SSL context option listing

Description

Context options for ssl:// and tls:// transports.

Options

verify_peer boolean

Require verification of SSL certificate used.

Defaults to FALSE.

allow_self_signed boolean

Allow self-signed certificates.

Defaults to FALSE

cafile string

Location of Certificate Authority file on local filesystem which should be used with the verify_peer context option to authenticate the identity of the remote peer.

capath string

If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory.

local_cert string

Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and private key. It can optionally contain the certificate chain of issuers.

passphrase string

Passphrase with which your local_cert file was encoded.

CN_match string

Common Name we are expecting. PHP will perform limited wildcard matching. If the Common Name does not match this, the connection attempt will fail.

verify_depth integer

Abort if the certificate chain is too deep.

Defaults to no verification.

ciphers string

Sets the list of available ciphers. The format of the string is described in » ciphers(1).

Defaults to DEFAULT.

capture_peer_cert boolean

If set to TRUE a peer_certificate context option will be created containing the peer certificate.

capture_peer_chain boolean

If set to TRUE a peer_certificate_chain context option will be created containing the certificate chain.

SNI_enabled boolean

If set to TRUE server name indication will be enabled. Enabling SNI allows multiple certificates on the same IP address.

SNI_server_name string

If set, then this value will be used as server name for server name indication. If this value is not set, then the server name is guessed based on the hostname used when opening the stream.

Changelog

Version | Description
5.3.2 | Added SNI_enabled and SNI_server_name .
5.0.0 | Added capture_peer_cert , capture_peer_chain and ciphers .

Notes

Note: Because ssl:// is the underlying transport for the https:// and ftps:// wrappers, any context options which apply to ssl:// also apply to https:// and ftps://.

Note: For SNI (Server Name Indication) to be available, then PHP must be compiled with OpenSSL 0.9.8j or greater. Use the OPENSSL_TLSEXT_SERVER_NAME to determine whether SNI is supported.

See Also

  • Socket context options

FTP context options
CURL context options
Context options and parameters


Alternative syntax for control structures

PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5.

The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and else in the alternative format:

<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?>

Note: Mixing syntaxes in the same control block is not supported.

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

elseif/else if
while
Control Structures


break

break ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

/* Using the optional argument. */

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

foreach
continue
Control Structures


continue

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.

Note: continue 0; and continue 1; is the same as running continue;.

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

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

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

<?php
for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    print "$i\n";
}
?>

One can expect the result to be :

0
1
3
4

but this script will output :

2

because the return value of the print() call is int(1), and it will look like the optional numeric argument mentioned above.

break
switch
Control Structures


declare

The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:

declare (directive)
    statement

The directive section allows the behavior of the declare block to be set. Currently only two directives are recognized: the ticks directive (See below for more information on the ticks directive) and the encoding directive (See below for more information on the encoding directive).

Note: The encoding directive was added in PHP 5.3.0

The statement part of the declare block will be executed - how it is executed and what side effects occur during execution may depend on the directive set in the directive block.

The declare construct can also be used in the global scope, affecting all code following it (however if the file with declare was included then it does not affect the parent file).

<?php
// these are the same:

// you can use this:
declare(ticks=1) {
    // entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>

Ticks

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable.

The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.

Example #1 Tick usage example

<?php

declare(ticks=1);

// A function called on each tick event
function tick_handler()
{
    echo "tick_handler() called\n";
}

register_tick_function('tick_handler');

$a = 1;

if ($a > 0) {
    $a += 2;
    print($a);
}

?>

Example #2 Ticks usage example

<?php

function tick_handler()
{
  echo "tick_handler() called\n";
}

$a = 1;
tick_handler();

if ($a > 0) {
    $a += 2;
    tick_handler();
    print($a);
    tick_handler();
}
tick_handler();

?>

See also register_tick_function() and unregister_tick_function().

Encoding

A script's encoding can be specified per-script using the encoding directive.

Example #3 Declaring an encoding for the script.

<?php
declare(encoding='ISO-8859-1');
// code here
?>

Caution

When combined with namespaces, the only legal syntax for declare is declare(encoding='...'); where ... is the encoding value. declare(encoding='...') {} will result in a parse error when combined with namespaces.

The encoding declare value is ignored in PHP 5.3 unless php is compiled with --enable-zend-multibyte. In PHP 6.0, the encoding directive will be used to inform the scanner what encoding the file is created in. Legal values are encoding names such as UTF-8.

switch
return
Control Structures


do-while

do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

There is just one syntax for do-while loops:

<?php
$i = 0;
do {
    echo $i;
} while ($i > 0);
?>

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:

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

    /* process i */

} while (0);
?>

Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this 'feature'. Since PHP 5.3.0, it is possible to use goto operator instead of this hack.

while
for
Control Structures


else

Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is greater than b if $a is greater than $b, and a is NOT greater than b otherwise:

<?php
if ($a > $b) {
  echo "a is greater than b";
} else {
  echo "a is NOT greater than b";
}
?>

The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see elseif).

if
elseif/else if
Control Structures


elseif/else if

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:

<?php
if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?>

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

<?php

/* Incorrect Method: */
if($a > $b):
    echo $a." is greater than ".$b;
else if($a == $b): // Will not compile.
    echo "The above line causes a parse error.";
endif;

/* Correct Method: */
if($a > $b):
    echo $a." is greater than ".$b;
elseif($a == $b): // Note the combination of the words.
    echo $a." equals ".$b;
else:
    echo $a." is neither greater than or equal to ".$b;
endif;

?>

else
Alternative syntax for control structures
Control Structures


for

for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:

for (expr1; expr2; expr3)
    statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

Consider the following examples. All of them display the numbers 1 through 10:

<?php
/* example 1 */

for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

/* example 2 */

for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}

/* example 3 */

$i = 1;
for (; ; ) {
    if ($i > 10) {
        break;
    }
    echo $i;
    $i++;
}

/* example 4 */

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for for loops.

for (expr1; expr2; expr3):
    statement
    ...
endfor;

Its a common thing to many users to iterate though arrays like in the example below.

<?php
/*
* This is an array with some data we want to modify
* when running through the for loop.
*/
$people = Array(
        Array('name' => 'Kalle', 'salt' => 856412),
        Array('name' => 'Pierre', 'salt' => 215863)
        );

for($i = 0; $i < sizeof($people); ++$i)
{
    $people[$i]['salt'] = rand(000000, 999999);
}
?>

The problem lies in the second for expression. This code can be slow because it has to calculate the size of the array on each iteration. Since the size never change, it can be optimized easily using an intermediate variable to store the size and use in the loop instead of sizeof. The example below illustrates this:

<?php
$people = Array(
        Array('name' => 'Kalle', 'salt' => 856412),
        Array('name' => 'Pierre', 'salt' => 215863)
        );

for($i = 0, $size = sizeof($people); $i < $size; ++$i)
{
    $people[$i]['salt'] = rand(000000, 999999);
}
?>

do-while
foreach
Control Structures


foreach

PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.

As of PHP 5, it is possible to iterate objects too.

Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

This is possible only if iterated array can be referenced (i.e. is variable), that means the following code won't work:

<?php
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}

?>

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

Note: foreach does not support the ability to suppress error messages using '@'.

You may have noticed that the following are functionally identical:

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

foreach ($arr as $value) {
    echo "Value: $value<br />\n";
}
?>

The following are also functionally identical:

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

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}
?>

Some more examples to demonstrate usages:

<?php
/* foreach example 1: value only */

$a = array(1, 2, 3, 17);

foreach ($a as $v) {
    echo "Current value of \$a: $v.\n";
}

/* foreach example 2: value (with its manual access notation printed for illustration) */

$a = array(1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
    echo "\$a[$i] => $v.\n";
    $i++;
}

/* foreach example 3: key and value */

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

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

/* foreach example 5: dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v) {
    echo "$v\n";
}
?>

for
break
Control Structures


goto

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break.

Example #1 goto example

<?php
goto a;
echo 'Foo';

a:
echo 'Bar';
?>

The above example will output:

Bar

Example #2 goto loop example

<?php
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    if($j==17) goto end;
  }
}
echo "i = $i";
end:
echo 'j hit 17';
?>

The above example will output:

j hit 17

Example #3 This will not work

<?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    loop:
  }
}
echo "$i = $i";
?>

The above example will output:

Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2

Note: The goto operator is available as of PHP 5.3.

What's the worse thing that could happen if you use goto?

Image courtesy of » xkcd

include_once
Functions
Control Structures


if

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

if (expr)
  statement

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.

The following example would display a is bigger than b if $a is bigger than $b:

<?php
if ($a > $b)
  echo "a is bigger than b";
?>

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

<?php
if ($a > $b) {
  echo "a is bigger than b";
  $b = $a;
}
?>

If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.

Introduction
else
Control Structures


Introduction

Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.

Control Structures
if
Control Structures


switch

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.

Note: Note that switch/case does loose comparision.

The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:

Example #1 switch structure

<?php
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}
?>

Example #2 switch structure allows usage of strings

<?php
switch ($i) {
    case "apple":
        echo "i is apple";
        break;
    case "bar":
        echo "i is bar";
        break;
    case "cake":
        echo "i is cake";
        break;
}
?>

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

<?php
switch ($i) {
    case 0:
        echo "i equals 0";
    case 1:
        echo "i equals 1";
    case 2:
        echo "i equals 2";
}
?>

Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

The statement list for a case can also be empty, which simply passes control into the statement list for the next case.

<?php
switch ($i) {
case 0:
case 1:
case 2:
    echo "i is less than 3 but not negative";
    break;
case 3:
    echo "i is 3";
}
?>

A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:

<?php
switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
       echo "i is not equal to 0, 1 or 2";
}
?>

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.

The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures.

<?php
switch ($i):
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
        echo "i is not equal to 0, 1 or 2";
endswitch;
?>

Its possible to use a semicolon instead of a colon after a case like:

<?php
switch($beer)
{
    case 'tuborg';
    case 'carlsberg';
    case 'heineken';
        echo 'Good choice';
    break;
    default;
        echo 'Please make a new selection...';
    break;
}
?>

continue
declare
Control Structures


while

while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

while (expr)
    statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr):
    statement
    ...
endwhile;

The following examples are identical, and both print the numbers 1 through 10:

<?php
/* example 1 */

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

/* example 2 */

$i = 1;
while ($i <= 10):
    echo $i;
    $i++;
endwhile;
?>

Alternative syntax for control structures
do-while
Control Structures


Copyright

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

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


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Crack configuration options
Name | Default | Changeable | Changelog
crack.default_dictionary | NULL | PHP_INI_PERDIR | PHP_INI_SYSTEM in crack <= 0.2. Available since PHP 4.0.5. Removed in PHP 5.0.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
Crack


Examples

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

Example #1 CrackLib example

<?php
// Open CrackLib Dictionary
$dictionary = crack_opendict('/usr/local/lib/pw_dict')
     or die('Unable to open CrackLib dictionary');

// Perform password check
$check = crack_check($dictionary, 'gx9A2s0x');

// Retrieve messages
$diag = crack_getlastmessage();
echo $diag; // 'strong password'

// Close dictionary
crack_closedict($dictionary);
?>

Note: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.

Predefined Constants
Crack Functions
Crack


Installation

This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/crack.

In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile PHP with Crack support by using the --with-crack[=DIR] configuration option.

Windows users will enable php_crack.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

More information regarding CrackLib along with the library can be found at » http://sourceforge.net/projects/cracklib.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

The CrackLib extension defines a dictionary resource identifier returned by crack_opendict().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Crack


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CYRUS_CONN_NONSYNCLITERAL (integer)
CYRUS_CONN_INITIALRESPONSE (integer)
CYRUS_CALLBACK_NUMBERED (integer)
CYRUS_CALLBACK_NOLITERAL (integer)
Resource Types
Cyrus Functions
Cyrus


Installation

To enable Cyrus IMAP support and to use these functions you have to compile PHP with the --with-cyrus option.

Warning

The IMAP, recode, YAZ and Cyrus extensions cannot be used in conjuction, because they share the same internal symbols. Note: Yaz 2.0 and above does not suffer from this problem.

Requirements
Runtime Configuration
Installing/Configuring


Resource Types

This extension defines a Cyrus IMAP connection identifier returned by cyrus_connect().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Cyrus


Creates new DateInterval object

DateInterval
DateInterval::createFromDateString
DateInterval
PHP Manual

DateInterval::__construct

(PHP 5 >= 5.3.0)

DateInterval::__construct — Creates new DateInterval object

Description

DateInterval::__construct ( string $interval_spec )

Creates new DateInterval object.

Parameters

interval_spec

Interval specification.

The format starts with the letter P, for "period." Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.

interval_spec Period Designators
Period Designator | Description
Y | years
M | months
D | days
W | weeks. These get converted into days, so can not be combined with D.
H | hours
M | minutes
S | seconds

Here are some simple examples. Two days is P2D. Two seconds is PT2S. Six years and five minutes is P6YT5M.

Note: The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as P1Y4D, not P4D1Y.

The specification can also be represented as a date time. A sample of one year and four days would be P0001-00-04T00:00:00. But the values in this format can not exceed a given period's roll-over-point (e.g. 25 hours is invalid).

These formats are based on the » ISO 8601 duration specification.

Examples

Example #1 DateInterval example

<?php

$interval = new DateInterval('P2Y4DT6H8M');
print_r($interval);

?>

The above example will output:

DateInterval Object
(
    [y] => 2
    [m] => 0
    [d] => 4
    [h] => 6
    [i] => 8
    [s] => 0
    [invert] => 0
    [days] => 0
)

See Also

  • DateInterval::format() - Formats the interval
  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects

DateInterval
DateInterval::createFromDateString
DateInterval


Sets up a DateInterval from the relative parts of the string

DateInterval::__construct
DateInterval::format
DateInterval
PHP Manual

DateInterval::createFromDateString

(PHP 5 >= 5.3.0)

DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string

Description

public static DateInterval DateInterval::createFromDateString ( string $time )

Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string.

Parameters

time

Date with relative parts.

Return Values

Returns new DateInterval instance if success.

DateInterval::__construct
DateInterval::format
DateInterval


Formats the interval

DateInterval::createFromDateString
DatePeriod
DateInterval
PHP Manual

DateInterval::format

(PHP 5 >= 5.3.0)

DateInterval::format — Formats the interval

Description

public string DateInterval::format ( string $format )

Formats the interval.

Parameters

format

The following characters are recognized in the format parameter string. Each format character must be proceeded by a percent sign (%).
format character | Description | Example values
% Literal % %
Y | Years, numeric, at least 2 digits with leading 0 | 01, 03
y | Years, numeric | 1, 3
M | Months, numeric, at least 2 digits with leading 0 | 01, 03, 12
m | Months, numeric | 1, 3, 12
D | Days, numeric, at least 2 digits with leading 0 | 01, 03, 31
d | Days, numeric | 1, 3, 31
a | Total amount of days | 4, 18, 8123
H | Hours, numeric, at least 2 digits with leading 0 | 01, 03, 23
h | Hours, numeric | 1, 3, 23
I | Minutes, numeric, at least 2 digits with leading 0 | 01, 03, 59
i | Minutes, numeric | 1, 3, 59
S | Seconds, numeric, at least 2 digits with leading 0 | 01, 03, 57
s | Seconds, numeric | 1, 3, 57
R Sign "-" when negative, "+" when positive -, +
r Sign "-" when negative, empty when positive -,

Return Values

Returns the formatted interval.

Notes

Note: The DateInterval::format method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like "32 days" which could be interpreted as anything from "1 month and 4 days" to "1 month and 1 day".

Examples

Example #1 DateInterval example

<?php

$interval = new DateInterval('P2Y4DT6H8M');
echo $interval->format('%d days');

?>

The above example will output:

4 days

Example #2 DateInterval and carry over points

<?php

$interval = new DateInterval('P32D');
echo $interval->format('%d days');

?>

The above example will output:

32 days

DateInterval::createFromDateString
DatePeriod
DateInterval


Creates new DatePeriod object

DatePeriod
Date/Time Functions
DatePeriod
PHP Manual

DatePeriod::__construct

(PHP 5 >= 5.3.0)

DatePeriod::__construct — Creates new DatePeriod object

Description

DatePeriod::__construct ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
DatePeriod::__construct ( DateTime $start , DateInterval $interval , DateTime $end [, int $options ] )
DatePeriod::__construct ( string $isostr [, int $options ] )

Creates new DatePeriod object.

Parameters

start

Start date.

interval

Interval.

recurrences

Number of recurrences.

end

End date.

isostr

String containing the ISO interval.

options

Can be set to DatePeriod::EXCLUDE_START_DATE.

DatePeriod
Date/Time Functions
DatePeriod


Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

DateTime
DateTime::__construct
DateTime
PHP Manual

DateTime::add

(PHP 5 >= 5.3.0)

DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

Description

public DateTime DateTime::add ( DateInterval $interval )
DateTime date_add ( DateTime $object , DateInterval $interval )

Adds the specified DateInterval object to the specified DateTime object.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

interval

A DateInterval object

Return Values

Returns the modified self object (DateTime).

Examples

Example #1 date_add() example

<?php

$date = new DateTime("18-July-2008 16:30:30");
echo $date->format("d-m-Y H:i:s").'<br />';

date_add($date, new DateInterval("P5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days';

date_add($date, new DateInterval("P5M"));
echo '<br />'.$date->format("d-m-Y").' : 5 Months';

date_add($date, new DateInterval("P5Y"));
echo '<br />'.$date->format("d-m-Y").' : 5 Years';

date_add($date, new DateInterval("P5Y5M5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';

date_add($date, new DateInterval("P5YT5H"));
echo '<br />'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';

?>

See Also

  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects

DateTime
DateTime::__construct
DateTime


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Date/Time Configuration Options
Name | Default | Changeable | Changelog
date.default_latitude | "31.7667" | PHP_INI_ALL | Available since PHP 5.0.0.
date.default_longitude | "35.2333" | PHP_INI_ALL | Available since PHP 5.0.0.
date.sunrise_zenith | "90.583333" | PHP_INI_ALL | Available since PHP 5.0.0.
date.sunset_zenith | "90.583333" | PHP_INI_ALL | Available since PHP 5.0.0.
date.timezone | "" | PHP_INI_ALL | Available since PHP 5.1.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

date.default_latitude float

The default latitude.

date.default_longitude float

The default longitude.

date.sunrise_zenith float

The default sunrise zenith.

date.sunset_zenith float

The default sunset zenith.

date.timezone string

The default timezone used by all date/time functions if the TZ environment variable isn't set. The precedence order is described in the date_default_timezone_get() page. See List of Supported Timezones for a list of supported timezones.

Note: The first four configuration options are currently only used by date_sunrise() and date_sunset().

Installation
Resource Types
Installing/Configuring


Predefined Constants

The DATE_ constants are defined since PHP 5.1.1 and they offer standard date representations, which can be used along with the date format functions (like date()).

Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().

SUNFUNCS_RET_TIMESTAMP (integer)
Timestamp
SUNFUNCS_RET_STRING (integer)
Hours:minutes (example: 08:02)
SUNFUNCS_RET_DOUBLE (integer)
Hours as floating point number (example 8.75)
Resource Types
List of Supported Timezones
Date/Time


Returns new DateTime object

DateTime::add
DateTime::createFromFormat
DateTime
PHP Manual

DateTime::__construct

(PHP 5 >= 5.2.0)

DateTime::__construct — Returns new DateTime object

Description

DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Returns new DateTime object.

Parameters

time

String in a format accepted by strtotime().

timezone

Time zone of the time.

Errors/Exceptions

Emits Exception in case of an error.

Examples

Example #1 DateTime::__construct() example

<?php
date_default_timezone_set('Europe/London');

$datetime = new DateTime('2008-08-03 14:52:10');
echo $datetime->format(DATE_ATOM);
?>

DateTime::add
DateTime::createFromFormat
DateTime


Returns new DateTime object formatted according to the specified format

DateTime::__construct
DateTime::diff
DateTime
PHP Manual

DateTime::createFromFormat

(PHP 5 >= 5.3.0)

DateTime::createFromFormat — Returns new DateTime object formatted according to the specified format

Description

public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

Returns new DateTime object formatted according to the specified format.

Parameters

format

Format accepted by date().

If format does not contain the character ! then portions of the date/time value specified in format but not specified in time will be set to the current system time.

If format contains the character !, then portions of the generated time specified to the left-hand side of the ! in format will be set to corresponding values from the Unix epoch.

If the first character of format is !, then all portions of the date/time value generated which are not specified in time will be initialized to corresponding values from the Unix epoch.

The Unix epoch is 1970-01-01 00:00:00 UTC.

time

String representing the time.

timezone

Time zone.

Return Values

Returns new DateTime instance or FALSE on failure.

Examples

Example #1 Using ! to reset default date/time values

<?php
echo "Current system date and time: " . date('Y-m-d H:i:s') . "\n";

$format = 'Y-m-d';
$dt = DateTime::createFromFormat($format, '2009-02-03');
echo "Format: $format; " . $dt->date . "\n";

$format = 'Y-m-d H:i:s';
$dt = DateTime::createFromFormat($format, '2009-02-03 15:16:17');
echo "Format: $format; " . $dt->date . "\n";

$format = 'Y-m-!d H:i:s';
$dt = DateTime::createFromFormat($format, '2009-02-03 15:16:17');
echo "Format: $format; " . $dt->date . "\n";

$format = '!Y-m-d';
$dt = DateTime::createFromFormat($format, '2009-02-03');
echo "Format: $format; " . $dt->date . "\n";
?>

The above example will output something like the following (taking into account the current system time):

Current system date and time: 2009-09-13 01:04:03
Format: Y-m-d; 2009-02-03 01:04:03
Format: Y-m-d H:i:s; 2009-02-03 15:16:17
Format: Y-m-!d H:i:s; 1970-01-03 15:16:17
Format: !Y-m-d; 2009-02-03 00:00:00

See Also

  • DateTime::__construct - Returns new DateTime object
  • DateTime::getLastErrors - Returns the warnings and errors

DateTime::__construct
DateTime::diff
DateTime


Returns the difference between two DateTime objects

DateTime::createFromFormat
DateTime::format
DateTime
PHP Manual

DateTime::diff

(PHP 5 >= 5.3.0)

DateTime::diff — Returns the difference between two DateTime objects

Description

public DateInterval DateTime::diff ( DateTime $datetime [, bool $absolute = false ] )

Returns the difference between two DateTime objects.

Parameters

datetime

The date to compare to.

absolute

Whether to return absolute difference.

Return Values

The difference between two dates.

DateTime::createFromFormat
DateTime::format
DateTime


Returns date formatted according to given format

DateTime::diff
DateTime::getLastErrors
DateTime
PHP Manual

DateTime::format

(PHP 5 >= 5.2.0)

DateTime::format — Returns date formatted according to given format

Description

public string DateTime::format ( string $format )
string date_format ( DateTime $object , string $format )

Parameters

object

Procedural style only: A DateTime object returned by date_create()

format

Format accepted by date().

Return Values

Returns formatted date on success or FALSE on failure.

Examples

Example #1 Displaying the date and time using the procedural form

<?php
date_default_timezone_set('Europe/London');

$datetime = date_create('2008-08-03 14:52:10');
echo date_format($datetime, 'jS, F Y') . "\n";
echo date_format($datetime, DATE_ATOM);
?>

Example #2 Displaying the date and time using the object oriented form

<?php
date_default_timezone_set('Europe/London');

$datetime = new DateTime('2008-08-03 14:52:10');
echo $datetime->format('jS, F Y') . "\n";
echo $datetime->format(DATE_ATOM);
?>
?>

The above example will output:

3rd, August 2008
2008-08-03T14:52:10+01:00

See Also

  • date() - Format a local time/date

DateTime::diff
DateTime::getLastErrors
DateTime


Returns the warnings and errors

DateTime::format
DateTime::getOffset
DateTime
PHP Manual

DateTime::getLastErrors

(PHP 5 >= 5.3.0)

DateTime::getLastErrors — Returns the warnings and errors

Description

public static array DateTime::getLastErrors ( void )

Returns the warnings and errors found while parsing a date/time string.

Parameters

This function has no parameters.

Return Values

Returns array containing info about warnings and errors.

Examples

Example #1 DateTime::getLastErrors() example

<?php
$date = date_create('asdfasdf');
print_r(DateTime::getLastErrors());
?>

The above example will output:

Array
(
    [warning_count] => 1
    [warnings] => Array
        (
            [6] => Double timezone specification
        )

    [error_count] => 1
    [errors] => Array
        (
            [0] => The timezone could not be found in the database
        )

)

DateTime::format
DateTime::getOffset
DateTime


Returns the timezone offset

DateTime::getLastErrors
DateTime::getTimestamp
DateTime
PHP Manual

DateTime::getOffset

(PHP 5 >= 5.2.0)

DateTime::getOffset — Returns the timezone offset

Description

public int DateTime::getOffset ( void )
int date_offset_get ( DateTime $object )

Parameters

object

Procedural style only: A DateTime object returned by date_create()

Return Values

Returns offset in seconds with respect to daylight saving time on success or FALSE on failure.

Examples

Example #1 Comparing offsets between Summer and Winter

<?php
date_default_timezone_set('Europe/London');

$winter = new DateTime('2008-12-25 14:25:41');
$summer = new DateTime('2008-07-14 14:25:41');

echo $winter->getOffset(); // Winter offset: 0
echo $summer->getOffset(); // Summer offset: 3600 = 1 hour
?>

DateTime::getLastErrors
DateTime::getTimestamp
DateTime


Gets the Unix timestamp

DateTime::getOffset
DateTime::getTimezone
DateTime
PHP Manual

DateTime::getTimestamp

(PHP 5 >= 5.3.0)

DateTime::getTimestamp — Gets the Unix timestamp

Description

public int DateTime::getTimestamp ( void )

Gets the Unix timestamp.

Parameters

This function has no parameters.

Return Values

Returns Unix timestamp representing the date.

See Also

  • DateTime::setTimestamp - Sets the date and time based on an Unix timestamp

DateTime::getOffset
DateTime::getTimezone
DateTime


Return time zone relative to given DateTime

DateTime::getTimestamp
DateTime::modify
DateTime
PHP Manual

DateTime::getTimezone

(PHP 5 >= 5.2.0)

DateTime::getTimezone — Return time zone relative to given DateTime

Description

public DateTimeZone DateTime::getTimezone ( void )
DateTimeZone date_timezone_get ( DateTime $object )

Parameters

object

Procedural style only: A DateTime object returned by date_create()

Return Values

Returns DateTimeZone object on success or FALSE on failure.

Examples

Example #1 Setting and getting DateTimeZone objects

<?php
date_default_timezone_set('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->getTimezone()->getName() . "\n";

$datetime = new DateTime('2008-08-03 12:35:23');
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->getTimezone()->getName();
?>

The above example will output:

Europe/London
America/Los_Angeles

See Also

  • DateTime::setTimezone() - Sets the time zone for the DateTime object
  • timezone_open() - Returns new DateTimeZone object

DateTime::getTimestamp
DateTime::modify
DateTime


Installation

There is no installation needed to use these functions; they are part of the PHP core.

Note: Getting the latest timezone database
The latest version of the timezone database can be installed via PECL's » timezonedb.

Note: Experimental DateTime support in PHP 5.1.x
Although the DateTime class (and related functions) are enabled by default since PHP 5.2.0, it is possible to add experimental support into PHP 5.1.x by using the following flag before configure/compile: CFLAGS=-DEXPERIMENTAL_DATE_SUPPORT=1

Requirements
Runtime Configuration
Installing/Configuring


Alters the timestamp

DateTime::getTimezone
DateTime::__set_state
DateTime
PHP Manual

DateTime::modify

(PHP 5 >= 5.2.0)

DateTime::modify — Alters the timestamp

Description

public DateTime DateTime::modify ( string $modify )
DateTime date_modify ( DateTime $object , string $modify )

Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by strtotime().

Parameters

object

Procedural style only: A DateTime object returned by date_create()

modify

String in a relative format accepted by strtotime().

Return Values

Returns the modified DateTime.

Changelog

Version | Description
5.3.0 | Changed the return value from NULL to DateTime.

Examples

Example #1 A date_modify() example

<?php
$date = new DateTime("2006-12-12");
$date->modify("+1 day");
echo $date->format("Y-m-d");
?>

The above example will output:

2006-12-13

See Also

  • strtotime() - Parse about any English textual datetime description into a Unix timestamp

DateTime::getTimezone
DateTime::__set_state
DateTime


The __set_state handler

DateTime::modify
DateTime::setDate
DateTime
PHP Manual

DateTime::__set_state

(PHP 5 >= 5.2.0)

DateTime::__set_state — The __set_state handler

Description

public static DateTime DateTime::__set_state ( array $array )

The __set_state handler.

Parameters

array

Initialization array.

Return Values

Returns a new instance of a DateTime object.

DateTime::modify
DateTime::setDate
DateTime


Sets the date

DateTime::__set_state
DateTime::setISODate
DateTime
PHP Manual

DateTime::setDate

(PHP 5 >= 5.2.0)

DateTime::setDate — Sets the date

Description

public DateTime DateTime::setDate ( int $year , int $month , int $day )
DateTime date_date_set ( DateTime $object , int $year , int $month , int $day )

Resets the current date of the DateTime object to a different date.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

year

Year of the date.

month

Month of the date.

day

Day of the date.

Return Values

Returns the modified DateTime.

Changelog

Version | Description
5.3.0 | Changed the return value from NULL to DateTime.

Examples

Example #1 Object oriented example usage

<?php
date_default_timezone_set('Europe/London');

$datetime = new DateTime('2008-08-03 14:52:10');
$datetime->setDate(2008, 10, 12);

echo $datetime->format(DATE_RFC2822);
?>

Example #2 Procedural example usage

<?php
date_default_timezone_set('Europe/London');

$datetime = date_create('2008-08-03 14:52:10');
date_date_set($datetime, 2008, 10, 12);

echo date_format($datetime, DATE_RFC2822);
?>

The above example will output:

Sun, 12 Oct 2008 14:52:10 +0100

See Also

  • DateTime::setISODate() - Sets the ISO date
  • DateTime::setTime() - Sets the time

DateTime::__set_state
DateTime::setISODate
DateTime


Sets the ISO date

DateTime::setDate
DateTime::setTime
DateTime
PHP Manual

DateTime::setISODate

(PHP 5 >= 5.2.0)

DateTime::setISODate — Sets the ISO date

Description

public DateTime DateTime::setISODate ( int $year , int $week [, int $day ] )
DateTime date_isodate_set ( DateTime $object , int $year , int $week [, int $day ] )

Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

year

Year of the date.

week

Week of the date.

day

Offset from the first day of the week.

Return Values

Returns the modified DateTime.

Changelog

Version | Description
5.3.0 | Changed the return value from NULL to DateTime.

Examples

Example #1 Finding the date from a week number and day offset

<?php
date_default_timezone_set('Europe/London');

$datetime = new DateTime();

// Offset from start of week 2 (7) = 5
$datetime->setISODate(2008, 2, 5); // Day 5 of week 2 of 2008 is the 11th of January.

// Offset from start of week 2 (7) = 10
$datetime->setISODate(2008, 2, 10); // Day 10 of week 2 of 2008 is the 16th of January.
?>

Example #2 Finding the month a week is in

<?php
date_default_timezone_set('Europe/London');

$datetime = date_create();
date_isodate_set($datetime, 2008, 6); // Week 6 of 2008 is in February.
?>

See Also

  • DateTime::setDate() - Sets the date

DateTime::setDate
DateTime::setTime
DateTime


Sets the time

DateTime::setISODate
DateTime::setTimestamp
DateTime
PHP Manual

DateTime::setTime

(PHP 5 >= 5.2.0)

DateTime::setTime — Sets the time

Description

public DateTime DateTime::setTime ( int $hour , int $minute [, int $second ] )
DateTime date_time_set ( DateTime $object , int $hour , int $minute [, int $second ] )

Resets the current time of the DateTime object to a different time.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

hour

Hour of the time.

minute

Minute of the time.

second

Second of the time.

Return Values

Returns the modified DateTime.

Changelog

Version | Description
5.3.0 | Changed the return value from NULL to DateTime.

Examples

Example #1 Changing the time of a DateTime object

<?php
date_default_timezone_set('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->format('Y-m-d H:i:s') . "\n";

$datetime->setTime(14, 55, 24);
echo $datetime->format('Y-m-d H:i:s') . "\n";

// Warning: Does not increment the hour!
// This is because the hour has been set (14) - see date_modify()
$datetime->setTime($datetime->format('H'), $datetime->format('n') + 6);
echo $datetime->format('Y-m-d H:i:s') . "\n";

// *Does* increment the day, because the day has not been set
$datetime->setTime($datetime->format('H') + 12, $datetime->format('n'));
echo $datetime->format('Y-m-d H:i:s') . "\n";
?>

The above example will output:

2008-08-03 12:35:23
2008-08-03 14:55:24
2008-08-03 14:14:00
2008-08-04 02:08:00

See Also

  • DateTime::setDate() - Sets the date

DateTime::setISODate
DateTime::setTimestamp
DateTime


Sets the date and time based on an Unix timestamp

DateTime::setTime
DateTime::setTimezone
DateTime
PHP Manual

DateTime::setTimestamp

(PHP 5 >= 5.3.0)

DateTime::setTimestamp — Sets the date and time based on an Unix timestamp

Description

public DateTime DateTime::setTimestamp ( int $unixtimestamp )

Sets the date and time based on an Unix timestamp.

Parameters

unixtimestamp

Unix timestamp representing the date.

Return Values

Returns the modified DateTime.

See Also

  • DateTime::getTimestamp - Gets the Unix timestamp

DateTime::setTime
DateTime::setTimezone
DateTime


Sets the time zone for the DateTime object

DateTime::setTimestamp
DateTime::sub
DateTime
PHP Manual

DateTime::setTimezone

(PHP 5 >= 5.2.0)

DateTime::setTimezone — Sets the time zone for the DateTime object

Description

public DateTime DateTime::setTimezone ( DateTimeZone $timezone )
DateTime date_timezone_set ( DateTime $object , DateTimeZone $timezone )

Parameters

object

Procedural style only: A DateTime object returned by date_create()

timezone

Desired time zone.

Return Values

Returns the modified DateTime.

Changelog

Version | Description
5.3.0 | Changed the return value from NULL to DateTime.

Examples

Example #1 Setting and getting DateTimeZone objects

<?php
date_default_timezone_set('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->getTimezone()->getName() . "\n";

$datetime = new DateTime('2008-08-03 12:35:23');
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->getTimezone()->getName();
?>

The above example will output:

Europe/London
America/Los_Angeles

See Also

  • DateTime::getTimezone() - Return time zone relative to given DateTime
  • timezone_open() - Returns new DateTimeZone object

DateTime::setTimestamp
DateTime::sub
DateTime


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Date/Time


Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

DateTime::setTimezone
DateTime::__wakeup
DateTime
PHP Manual

DateTime::sub

(PHP 5 >= 5.3.0)

DateTime::sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

Description

public DateTime DateTime::sub ( DateInterval $interval )
DateTime date_sub ( DateTime $object , DateInterval $interval )

Subtracts the specified DateInterval object from the specified DateTime object.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

interval

A DateInterval object

Return Values

Returns the modified self object (DateTime).

Examples

Example #1 date_sub() example

<?php

$date = new DateTime("18-July-2008 16:30:30");
echo $date->format("d-m-Y H:i:s").'<br />';

date_sub($date, new DateInterval("P5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days';

date_sub($date, new DateInterval("P5M"));
echo '<br />'.$date->format("d-m-Y").' : 5 Months';

date_sub($date, new DateInterval("P5Y"));
echo '<br />'.$date->format("d-m-Y").' : 5 Years';

date_sub($date, new DateInterval("P5Y5M5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';

date_sub($date, new DateInterval("P5YT5H"));
echo '<br />'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';

?>

See Also

  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects

DateTime::setTimezone
DateTime::__wakeup
DateTime


The __wakeup handler

DateTime::sub
DateTimeZone
DateTime
PHP Manual

DateTime::__wakeup

(PHP 5 >= 5.2.0)

DateTime::__wakeup — The __wakeup handler

Description

public DateTime DateTime::__wakeup ( void )

The __wakeup handler.

Parameters

This function has no parameters.

Return Values

Initializes a DateTime object.

DateTime::sub
DateTimeZone
DateTime


Creates new DateTimeZone object

DateTimeZone
DateTimeZone::getLocation
DateTimeZone
PHP Manual

DateTimeZone::__construct

(PHP 5 >= 5.2.0)

DateTimeZone::__construct — Creates new DateTimeZone object

Description

public DateTimeZone::__construct ( string $timezone )

Creates new DateTimeZone object.

Parameters

timezone

One of timezones.

Return Values

Returns DateTimeZone on success.

Errors/Exceptions

This method throws Exception if the timezone supplied is not recognised as a valid timezone.

Examples

Example #1 Catching errors when instantiating DateTimeZone

<?php
// Error handling by catching exceptions
$timezones = array('Europe/London', 'Mars/Phobos', 'Jupiter/Europa');

foreach ($timezones as $tz) {
    try {
        $mars = new DateTimeZone($tz);
    } catch(Exception $e) {
        echo $e->getMessage() . '<br />';
    }
}
?>

The above example will output:

DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos)
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)

DateTimeZone
DateTimeZone::getLocation
DateTimeZone


Returns location information for a timezone

DateTimeZone::__construct
DateTimeZone::getName
DateTimeZone
PHP Manual

DateTimeZone::getLocation

(PHP 5 >= 5.3.0)

DateTimeZone::getLocation — Returns location information for a timezone

Description

public array DateTimeZone::getLocation ( void )

Returns location information for a timezone, including country code, latitude/longitude and comments.

Parameters

This function has no parameters.

Return Values

Array containing location information about timezone.

Examples

Example #1 DateTimeZone::getLocation() example

<?php
$tz = new DateTimeZone("Europe/Prague");
print_r($tz->getLocation());
?>

The above example will output:

Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] =>
)

DateTimeZone::__construct
DateTimeZone::getName
DateTimeZone


Returns the name of the timezone

DateTimeZone::getLocation
DateTimeZone::getOffset
DateTimeZone
PHP Manual

DateTimeZone::getName

(PHP 5 >= 5.2.0)

DateTimeZone::getName — Returns the name of the timezone

Description

public string DateTimeZone::getName ( void )

Returns the name of the timezone.

Parameters

This function has no parameters.

Return Values

One of timezones.

DateTimeZone::getLocation
DateTimeZone::getOffset
DateTimeZone


Returns the timezone offset from GMT

DateTimeZone::getName
DateTimeZone::getTransitions
DateTimeZone
PHP Manual

DateTimeZone::getOffset

(PHP 5 >= 5.2.0)

DateTimeZone::getOffset — Returns the timezone offset from GMT

Description

public int DateTimeZone::getOffset ( DateTime $datetime )
int timezone_offset_get ( DateTimeZone $object , DateTime $datetime )

This function returns the offset to GMT for the date/time specified in the datetime parameter. The GMT offset is calculated with the timezone information contained in the DateTimeZone object being used.

Parameters

object

Procedural style only: A DateTimeZone object returned by timezone_open()

datetime

DateTime that contains the date/time to compute the offset from.

Return Values

Returns time zone offset in seconds on success or FALSE on failure.

Examples

Example #1 DateTimeZone::getOffset() examples

<?php
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");

// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime("now", $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now", $dateTimeZoneJapan);

// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?>

DateTimeZone::getName
DateTimeZone::getTransitions
DateTimeZone


Returns all transitions for the timezone

DateTimeZone::getOffset
DateTimeZone::listAbbreviations
DateTimeZone
PHP Manual

DateTimeZone::getTransitions

(PHP 5 >= 5.2.0)

DateTimeZone::getTransitions — Returns all transitions for the timezone

Description

public array DateTimeZone::getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )
array timezone_transitions_get ( DateTimeZone $object [, int $timestamp_begin [, int $timestamp_end ]] )

Parameters

object

Procedural style only: A DateTimeZone object returned by timezone_open()

timestamp_begin

Begin timestamp.

timestamp_end

End timestamp.

Return Values

Returns numerically indexed array containing associative array with all transitions on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | The optional timestamp_begin and timestamp_end were added.

Examples

Example #1 A timezone_transitions_get() example

<?php
$timezone = new DateTimeZone("CET");
print_r(reset($timezone->getTransitions()));
?>

The above example will output something similar to:

Array
(
    [ts] => -1693706400
    [time] => 1916-04-30T22:00:00+0000
    [offset] => 7200
    [isdst] => 1
    [abbr] => CEST
)

DateTimeZone::getOffset
DateTimeZone::listAbbreviations
DateTimeZone


Returns associative array containing dst, offset and the timezone name

DateTimeZone::getTransitions
DateTimeZone::listIdentifiers
DateTimeZone
PHP Manual

DateTimeZone::listAbbreviations

(PHP 5 >= 5.2.0)

DateTimeZone::listAbbreviations — Returns associative array containing dst, offset and the timezone name

Description

public static array DateTimeZone::listAbbreviations ( void )
array timezone_abbreviations_list ( void )

Return Values

Returns array on success or FALSE on failure.

Examples

Example #1 A timezone_abbreviations_list() example

<?php
$timezone_abbreviations = DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Porto_Acre
        )

    [1] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Eirunepe
        )

    [2] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Rio_Branco
        )

    [3] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => Brazil/Acre
        )

)

See Also

  • timezone_identifiers_list() - Alias of DateTimeZone::listIdentifiers

DateTimeZone::getTransitions
DateTimeZone::listIdentifiers
DateTimeZone


Returns numerically index array with all timezone identifiers

DateTimeZone::listAbbreviations
DateInterval
DateTimeZone
PHP Manual

DateTimeZone::listIdentifiers

(PHP 5 >= 5.2.0)

DateTimeZone::listIdentifiers — Returns numerically index array with all timezone identifiers

Description

public static array DateTimeZone::listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )
array timezone_identifiers_list ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )

Parameters

what

One of DateTimeZone class constants.

country

A two-letter ISO 3166-1 compatible country code.

Note: This option is only used when what is set to DateTimeZone::PER_COUNTRY.

Return Values

Returns array on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | Added the optional what and country parameters.

Examples

Example #1 A timezone_identifiers_list() example

<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
for ($i=0; $i < 5; $i++) {
    echo "$timezone_identifiers[$i]\n";
}
?>

The above example will output something similar to:

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmera

See Also

  • timezone_abbreviations_list() - Alias of DateTimeZone::listAbbreviations

DateTimeZone::listAbbreviations
DateInterval
DateTimeZone


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
DBA


Basic usage

Example #1 DBA example

<?php

$id = dba_open("/tmp/test.db", "n", "db2");

if (!$id) {
    echo "dba_open failed\n";
    exit;
}

dba_replace("key", "This is an example!", $id);

if (dba_exists("key", $id)) {
    echo dba_fetch("key", $id);
    dba_delete("key", $id);
}

dba_close($id);
?>

DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.

All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().

You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.

Example #2 Traversing a database

<?php

// ...open database...

$key = dba_firstkey($id);

while ($key != false) {
    if (true) {          // remember the key to perform some action later
        $handle_later[] = $key;
    }
    $key = dba_nextkey($id);
}

foreach ($handle_later as $val) {
    dba_delete($val, $id);
}

?>

Examples
DBA Functions
Examples


Examples

Table of Contents

  • Basic usage
Predefined Constants
Basic usage
DBA


Installation

By using the --enable-dba=shared configuration option you can build a dynamic loadable module to enable PHP for basic support of dbm-style databases. You also have to add support for at least one of the following handlers by specifying the --with-XXXX configure switch to your PHP configure line.

Warning

After configuring and compiling PHP you must execute the following test from commandline: php run-tests.php ext/dba. This shows whether your combination of handlers works. Most problematic are dbm and ndbm which conflict with many installations. The reason for this is that on several systems these libraries are part of more than one other library. The configuration test only prevents you from configuring malfunctioning single handlers but not combinations.

Supported DBA handlers
Handler | Configure Switch
dbm

To enable support for dbm add --with-dbm[=DIR].

Note: dbm normally is a wrapper which often results in failures. This means you should only use dbm if you are sure it works and if you really need this format.

ndbm

To enable support for ndbm add --with-ndbm[=DIR].

Note: ndbm normally is a wrapper which often results in failures. This means you should only use ndbm if you are sure it works and if you really need this format.

gdbm | To enable support for gdbm add --with-gdbm[=DIR].
db2

To enable support for db2 add --with-db2[=DIR].

Note: db2 conflicts with db3 and db4.

db3

To enable support for db3 add --with-db3[=DIR].

Note: db3 conflicts with db2 and db4.

db4

To enable support for db4 add --with-db4[=DIR].

Note: db4 conflicts with db2 and db3.

Note: This was added in PHP 4.3.2. In earlier versions of PHP you need to use --with-db3=DIR with DIR being the path to db4 library. It is not possible to use db versions starting from 4.1 with PHP prior to version 4.3.0. Also, the db libraries with versions 4.1 through 4.1.24 cannot be used in any PHP version.

cdb

To enable support for cdb add --with-cdb[=DIR].

Note: Since PHP 4.3.0 you can omit DIR to use the bundled cdb library that adds the cdb_make handler which allows creation of cdb files and allows to access cdb files on the network using PHP's streams.

flatfile

To enable support for flatfile add --with-flatfile.

Note: This was added in PHP 4.3.0 to add compatibility with deprecated dbm extension. Use this handler only when you cannot install one of the libraries required by the other handlers and when you cannot use bundled cdb handler.

inifile

To enable support for inifile add --with-inifile.

Note: This was added in PHP 5.0.0 and allows to read and set microsoft style .ini files (like the php.ini file).

qdbm

To enable support for qdbm add --with-qdbm[=DIR].

Note: qdbm conflicts with dbm and gdbm.

Note: This was added in PHP 5.0.0. The qdbm library can be loaded from » http://qdbm.sourceforge.net/.

Note: Up to PHP 4.3.0 you are able to add both db2 and db3 handler but only one of them can be used internally. That means that you cannot have both file formats. Starting with PHP 5.0.0 there is a configuration check avoid such misconfigurations.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

The behaviour of various aspects depends on the implementation of the underlying database. Functions such as dba_optimize() and dba_sync() will do what they promise for one database and will do nothing for others. You have to download and install supported dba-Handlers.

List of DBA handlers
Handler | Notes
dbm | Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format.
ndbm | Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated).
gdbm | Gdbm is the » GNU database manager.
db2 | DB2 is » Sleepycat Software's DB2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications.
db3 | DB3 is » Sleepycat Software's DB3.
db4 | DB4 is » Sleepycat Software's DB4. This is available since PHP 4.3.2.
cdb | Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at » http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. And since PHP 4.3.0 we support writing (not updating) through the internal cdb library.
cdb_make | Since PHP 4.3.0 we support creation (not updating) of cdb files when the bundled cdb library is used.
flatfile | This is available since PHP 4.3.0 for compatibility with the deprecated dbm extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library.
inifile | This is available since PHP 4.3.3 to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is a new function dba_key_split() available since PHP 5 which allows to convert the string keys into array keys without loosing FALSE.
qdbm | This is available since PHP 5.0.0. The qdbm library can be loaded from » http://qdbm.sourceforge.net/.

When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().

Installing/Configuring
Installation
Installing/Configuring


Resource Types

The functions dba_open() and dba_popen() return a handle to the specified database file to access which is used by all other dba-function calls.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
DBA


Predefined Constants

This extension has no constants defined.

Resource Types
dBase Functions
dBase


Installation

In order to enable the bundled dbase library and to use these functions, you must compile PHP with the --enable-dbase option.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
dBase


Predefined Constants

Table of Contents

  • db++ error codes

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Resource Types
db++ error codes
DB++


db++ error codes

DB++ Error Codes
PHP Constant | db++ constant | meaning
DBPLUS_ERR_NOERR (integer) | ERR_NOERR | Null error condition
DBPLUS_ERR_DUPLICATE (integer) | ERR_DUPLICATE | Tried to insert a duplicate tuple
DBPLUS_ERR_EOSCAN (integer) | ERR_EOSCAN | End of scan from rget()
DBPLUS_ERR_EMPTY (integer) | ERR_EMPTY | Relation is empty (server)
DBPLUS_ERR_CLOSE (integer) | ERR_CLOSE | The server can't close
DBPLUS_ERR_WLOCKED (integer) | ERR_WLOCKED | The record is write locked
DBPLUS_ERR_LOCKED (integer) | ERR_LOCKED | Relation was already locked
DBPLUS_ERR_NOLOCK (integer) | ERR_NOLOCK | Relation cannot be locked
DBPLUS_ERR_READ (integer) | ERR_READ | Read error on relation
DBPLUS_ERR_WRITE (integer) | ERR_WRITE | Write error on relation
DBPLUS_ERR_CREATE (integer) | ERR_CREATE | Create() system call failed
DBPLUS_ERR_LSEEK (integer) | ERR_LSEEK | Lseek() system call failed
DBPLUS_ERR_LENGTH (integer) | ERR_LENGTH | Tuple exceeds maximum length
DBPLUS_ERR_OPEN (integer) | ERR_OPEN | Open() system call failed
DBPLUS_ERR_WOPEN (integer) | ERR_WOPEN | Relation already opened for writing
DBPLUS_ERR_MAGIC (integer) | ERR_MAGIC | File is not a relation
DBPLUS_ERR_VERSION (integer) | ERR_VERSION | File is a very old relation
DBPLUS_ERR_PGSIZE (integer) | ERR_PGSIZE | Relation uses a different page size
DBPLUS_ERR_CRC (integer) | ERR_CRC | Invalid crc in the superpage
DBPLUS_ERR_PIPE (integer) | ERR_PIPE | Piped relation requires lseek()
DBPLUS_ERR_NIDX (integer) | ERR_NIDX | Too many secondary indices
DBPLUS_ERR_MALLOC (integer) | ERR_MALLOC | Malloc() call failed
DBPLUS_ERR_NUSERS (integer) | ERR_NUSERS | Error use of max users
DBPLUS_ERR_PREEXIT (integer) | ERR_PREEXIT | Caused by invalid usage
DBPLUS_ERR_ONTRAP (integer) | ERR_ONTRAP | Caused by a signal
DBPLUS_ERR_PREPROC (integer) | ERR_PREPROC | Error in the preprocessor
DBPLUS_ERR_DBPARSE (integer) | ERR_DBPARSE | Error in the parser
DBPLUS_ERR_DBRUNERR (integer) | ERR_DBRUNERR | Run error in db
DBPLUS_ERR_DBPREEXIT (integer) | ERR_DBPREEXIT | Exit condition caused by prexit() * procedure
DBPLUS_ERR_WAIT (integer) | ERR_WAIT | Wait a little (Simple only)
DBPLUS_ERR_CORRUPT_TUPLE (integer) | ERR_CORRUPT_TUPLE | A client sent a corrupt tuple
DBPLUS_ERR_WARNING0 (integer) | ERR_WARNING0 | The Simple routines encountered a non fatal error which was corrected
DBPLUS_ERR_PANIC (integer) | ERR_PANIC | The server should not really die but after a disaster send ERR_PANIC to all its clients
DBPLUS_ERR_FIFO (integer) | ERR_FIFO | Can't create a fifo
DBPLUS_ERR_PERM (integer) | ERR_PERM | Permission denied
DBPLUS_ERR_TCL (integer) | ERR_TCL | TCL_error
DBPLUS_ERR_RESTRICTED (integer) | ERR_RESTRICTED | Only two users
DBPLUS_ERR_USER (integer) | ERR_USER | An error in the use of the library by an application programmer
DBPLUS_ERR_UNKNOWN (integer) | ERR_UNKNOWN |

Predefined Constants
DB++ Functions
Predefined Constants


Installation

In order to build this extension yourself you need the db++ client libraries and header files to be installed on your system (these are included in the db++ installation archives by default). You have to run configure with option --with-dbplus to build this extension.

configure looks for the client libraries and header files under the default paths /usr/dbplus, /usr/local/dbplus and /opt/dblus. If you have installed db++ in a different place you have add the installation path to the configure option like this: --with-dbplus=/your/installation/path.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

This extension relies on external client libraries so you have to have a db++ client installed on the system you want to use this extension on.

» Concept asa provides » db++ Demo versions and » documentation for Linux, some other Unix versions. There is also a Windows version of db++, but this extension doesn't support it (yet).

Installing/Configuring
Installation
Installing/Configuring


Resource Types

dbplus_relation

Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
DB++


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

DBX Configuration Options
Name | Default | Changeable | Changelog
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0. Removed in PHP 5.1.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

dbx.colnames_case string

Columns names can be returned "unchanged" or converted to "uppercase" or "lowercase". This directive can be overridden with a flag to dbx_query().

Installation
Resource Types
Installing/Configuring


Installation

In order to have these functions available, you must compile PHP with dbx support by using the --enable-dbx option and all options for the databases that will be used, e.g. for MySQL you must also specify --with-mysql=[DIR]. To get other supported databases to work with the dbx-module refer to their specific documentation.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To be able to use a database with the dbx-module, the module must be either linked or loaded into PHP, and the database module must be supported by the dbx-module. Currently, the following databases are supported, but others will follow:

  • FrontBase (available from PHP 4.1.0).
  • Microsoft SQL Server
  • MySQL
  • ODBC
  • PostgreSQL
  • Sybase-CT (available from PHP 4.2.0).
  • Oracle (oci8) (available from PHP 4.3.0).
  • SQLite (PHP 5).

Documentation for adding additional database support to dbx can be found at » http://www.guidance.nl/php/dbx/doc/.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

There are two resource types used in the dbx module. The first one is the link-object for a database connection, the second a result-object which holds the result of a query.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
dbx


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

F_DUPFD (integer)
F_GETFD (integer)
F_GETFL (integer)
F_GETLK (integer)
F_GETOWN (integer)
F_RDLCK (integer)
F_SETFL (integer)
F_SETLK (integer)
F_SETLKW (integer)
F_SETOWN (integer)
F_UNLCK (integer)
F_WRLCK (integer)
O_APPEND (integer)
O_ASYNC (integer)
O_CREAT (integer)
O_EXCL (integer)
O_NDELAY (integer)
O_NOCTTY (integer)
O_NONBLOCK (integer)
O_RDONLY (integer)
O_RDWR (integer)
O_SYNC (integer)
O_TRUNC (integer)
O_WRONLY (integer)
S_IRGRP (integer)
S_IROTH (integer)
S_IRUSR (integer)
S_IRWXG (integer)
S_IRWXO (integer)
S_IRWXU (integer)
S_IWGRP (integer)
S_IWOTH (integer)
S_IWUSR (integer)
S_IXGRP (integer)
S_IXOTH (integer)
S_IXUSR (integer)
Resource Types
Direct IO Functions
Direct IO


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/dio.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Resource Types

One resource type is defined by this extension: a file descriptor returned by dio_open().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Direct IO


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

DIRECTORY_SEPARATOR (string)
PATH_SEPARATOR (string)

Note: The PATH_SEPARATOR was introduced with PHP 4.3.0-RC2.

Resource Types
Directory Functions
Directories


Installation

There is no installation needed to use these functions; they are part of the PHP core.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Directories
Requirements
Directories


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
Enchant


Examples

Example #1 Enchant Usage Example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);

$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
if (enchant_broker_dict_exists($r,$tag)) {
    $d = enchant_broker_request_dict($r, $tag);
    $dprovides = enchant_dict_describe($d);
    echo "dictionary $tag provides:\n";
    $wordcorrect = enchant_dict_check($d, "soong");
    print_r($dprovides);
    if (!$wordcorrect) {
        $suggs = enchant_dict_suggest($d, "soong");
        echo "Suggestions for 'soong':";
        print_r($suggs);
    }
    enchant_broker_free_dict($d);
} else {
}
enchant_broker_free($r);
?>
Predefined Constants
Enchant Functions
Enchant


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/enchant.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

This version uses the functions of the » Enchant library by Dom Lachowicz. You need Enchant 1.2.4 or later.

Enchant also requires » Glib 2.6 or greater. Pre-compiled Windows libraries are available from » http://ftp.gnome.org/pub/gnome/binaries/win32/glib/.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

There are two types of resources in this extension. The first one is the broker (backends manager) and the second is for the dictionary.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Enchant


Construct the exception

ErrorException
ErrorException::getSeverity
ErrorException
PHP Manual

ErrorException::__construct

(PHP 5 >= 5.1.0)

ErrorException::__construct — Construct the exception

Description

public ErrorException::__construct ([ string $message [, int $code [, int $severity [, string $filename [, int $lineno ]]]]] )

Constructs the Exception.

Parameters

message

The Exception message to throw.

code

The Exception code.

severity

The severity level of the exception.

filename

The filename where the exception is thrown.

lineno

The line number where the exception is thrown.

ErrorException
ErrorException::getSeverity
ErrorException


Gets the exception severity

ErrorException::__construct
Predefined Interfaces
ErrorException
PHP Manual

ErrorException::getSeverity

(PHP 5 >= 5.1.0)

ErrorException::getSeverity — Gets the exception severity

Description

final public int ErrorException::getSeverity ( void )

Returns the severity of the exception.

Parameters

This function has no parameters.

Return Values

Returns the severity level of the exception.

Examples

Example #1 ErrorException::getSeverity() example

<?php
try {
    throw new ErrorException("Exception message", 0, 75);
} catch(ErrorException $e) {
    echo "This exception severity is: " . $e->getSeverity();
}
?>

The above example will output something similar to:

This exception severity is: 75

ErrorException::__construct
Predefined Interfaces
ErrorException


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Errors and Logging Configuration Options
Name | Default | Changeable | Changelog
error_reporting | NULL | PHP_INI_ALL |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL |
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL | Available since PHP 4.3.0.
ignore_repeated_errors | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
ignore_repeated_source | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
report_memleaks | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
track_errors | "0" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.2.3.
xmlrpc_errors | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0.
xmlrpc_error_number | "0" | PHP_INI_ALL | Available since PHP 4.1.0.
docref_root | "" | PHP_INI_ALL | Available since PHP 4.3.0.
docref_ext | "" | PHP_INI_ALL | Available since PHP 4.3.2.
error_prepend_string | NULL | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

error_reporting integer

Set the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in Predefined Constants, and in php.ini. To set at runtime, use the error_reporting() function. See also the display_errors directive.

In PHP 4 and PHP 5 the default value is E_ALL & ~E_NOTICE. This setting does not show E_NOTICE level errors. You may want to show them during development.

Note: Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

Note: In PHP 5 a new error level E_STRICT is available. As E_STRICT is not included within E_ALL you have to explicitly enable this kind of error level. Enabling E_STRICT during development has some benefits. STRICT messages will help you to use the latest and greatest suggested method of coding, for example warn you about using deprecated functions.

Note: PHP Constants outside of PHP
Using PHP Constants outside of PHP, like in httpd.conf, will have no useful meaning so in such cases the integer values are required. And since error levels will be added over time, the maximum value (for E_ALL) will likely change. So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647 (includes all errors, not just E_ALL).

display_errors string

This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.

Value "stderr" sends the errors to stderr instead of stdout. The value is available as of PHP 5.2.4. In earlier versions, this directive was of type boolean.

Note: This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).

Note: Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

display_startup_errors boolean

Even when display_errors is on, errors that occur during PHP's startup sequence are not displayed. It's strongly recommended to keep display_startup_errors off, except for debugging.

log_errors boolean

Tells whether script error messages should be logged to the server's error log or error_log. This option is thus server-specific.

Note: You're strongly advised to use error logging in place of error displaying on production web sites.

log_errors_max_len integer

Set the maximum length of log_errors in bytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all. This length is applied to logged errors, displayed errors and also to $php_errormsg.

When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
ignore_repeated_errors boolean

Do not log repeated messages. Repeated errors must occur in the same file on the same line unless ignore_repeated_source is set true.

ignore_repeated_source boolean

Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.

report_memleaks boolean

If this parameter is set to Off, then memory leaks will not be shown (on stdout or in the log). This has only effect in a debug compile, and if error_reporting includes E_WARNING in the allowed list

track_errors boolean

If enabled, the last error message will always be present in the variable $php_errormsg.

html_errors boolean

Turn off HTML tags in error messages. The new format for HTML errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.

xmlrpc_errors boolean

Turns off normal error reporting and formats errors as XML-RPC error message.

xmlrpc_error_number integer

Used as the value of the XML-RPC faultCode element.

docref_root string

The new error format contains a reference to a page describing the error or function causing the error. In case of manual pages you can download the manual in your language and set this ini directive to the URL of your local copy. If your local copy of the manual can be reached by "/manual/" you can simply use docref_root=/manual/ . Additional you have to set docref_ext to match the fileextensions of your copy docref_ext=.html . It is possible to use external references. For example you can use docref_root=http://manual/en/ or docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F"

Most of the time you want the docref_root value to end with a slash "/". But see the second example above which does not have nor need it.

Note: This is a feature to support your development since it makes it easy to lookup a function description. However it should never be used on production systems (e.g. systems connected to the internet).

docref_ext string

See docref_root.

Note: The value of docref_ext must begin with a dot ".".

error_prepend_string string

String to output before an error message.

error_append_string string

String to output after an error message.

error_log string

Name of the file where script errors should be logged. The file should be writable by the web server's user. If the special value syslog is used, the errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows NT it means the event log. The system logger is not supported on Windows 95. See also: syslog(). If this directive is not set, errors are sent to the SAPI error logger. For example, it is an error log in Apache or stderr in CLI.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are always available as part of the PHP core.

Note: You may use these constant names in php.ini but not outside of PHP, like in httpd.conf, where you'd use the bitmask values instead.

Errors and Logging
Value | Constant | Description | Note
1 | E_ERROR (integer) | Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. |
2 | E_WARNING (integer) | Run-time warnings (non-fatal errors). Execution of the script is not halted. |
4 | E_PARSE (integer) | Compile-time parse errors. Parse errors should only be generated by the parser. |
8 | E_NOTICE (integer) | Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. |
16 | E_CORE_ERROR (integer) | Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. | since PHP 4
32 | E_CORE_WARNING (integer) | Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. | since PHP 4
64 | E_COMPILE_ERROR (integer) | Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. | since PHP 4
128 | E_COMPILE_WARNING (integer) | Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. | since PHP 4
256 | E_USER_ERROR (integer) | User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4
512 | E_USER_WARNING (integer) | User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4
1024 | E_USER_NOTICE (integer) | User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4
2048 | E_STRICT (integer) | Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. | since PHP 5
4096 | E_RECOVERABLE_ERROR (integer) | Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR. | since PHP 5.2.0
8192 | E_DEPRECATED (integer) | Run-time notices. Enable this to receive warnings about code that will not work in future versions. | since PHP 5.3.0
16384 | E_USER_DEPRECATED (integer) | User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 5.3.0
30719 | E_ALL (integer) | All errors and warnings, as supported, except of level E_STRICT in PHP < 6. | 32767 in PHP 6, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', '^' and '&' will be understood within php.ini.

Resource Types
Examples
Error Handling


Examples

Below we can see an example of using the error handling capabilities in PHP. We define an error handling function which logs the information into a file (using an XML format), and e-mails the developer in case a critical error in the logic happens.

Example #1 Using error handling in a script

<?php
// we will do our own error handling
error_reporting(0);

// user defined error handling function
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
    // timestamp for the error entry
    $dt = date("Y-m-d H:i:s (T)");

    // define an assoc array of error string
    // in reality the only entries we should
    // consider are E_WARNING, E_NOTICE, E_USER_ERROR,
    // E_USER_WARNING and E_USER_NOTICE
    $errortype = array (
                E_ERROR              => 'Error',
                E_WARNING            => 'Warning',
                E_PARSE              => 'Parsing Error',
                E_NOTICE             => 'Notice',
                E_CORE_ERROR         => 'Core Error',
                E_CORE_WARNING       => 'Core Warning',
                E_COMPILE_ERROR      => 'Compile Error',
                E_COMPILE_WARNING    => 'Compile Warning',
                E_USER_ERROR         => 'User Error',
                E_USER_WARNING       => 'User Warning',
                E_USER_NOTICE        => 'User Notice',
                E_STRICT             => 'Runtime Notice',
                E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'
                );
    // set of errors for which a var trace will be saved
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

    $err = "<errorentry>\n";
    $err .= "\t<datetime>" . $dt . "</datetime>\n";
    $err .= "\t<errornum>" . $errno . "</errornum>\n";
    $err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";
    $err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";
    $err .= "\t<scriptname>" . $filename . "</scriptname>\n";
    $err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";

    if (in_array($errno, $user_errors)) {
        $err .= "\t<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>\n";
    }
    $err .= "</errorentry>\n\n";

    // for testing
    // echo $err;

    // save to the error log, and e-mail me if there is a critical user error
    error_log($err, 3, "/usr/local/php4/error.log");
    if ($errno == E_USER_ERROR) {
        mail("phpdev@example.com", "Critical User Error", $err);
    }
}

function distance($vect1, $vect2)
{
    if (!is_array($vect1) || !is_array($vect2)) {
        trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
        return NULL;
    }

    if (count($vect1) != count($vect2)) {
        trigger_error("Vectors need to be of the same size", E_USER_ERROR);
        return NULL;
    }

    for ($i=0; $i<count($vect1); $i++) {
        $c1 = $vect1[$i]; $c2 = $vect2[$i];
        $d = 0.0;
        if (!is_numeric($c1)) {
            trigger_error("Coordinate $i in vector 1 is not a number, using zero",
                            E_USER_WARNING);
            $c1 = 0.0;
        }
        if (!is_numeric($c2)) {
            trigger_error("Coordinate $i in vector 2 is not a number, using zero",
                            E_USER_WARNING);
            $c2 = 0.0;
        }
        $d += $c2*$c2 - $c1*$c1;
    }
    return sqrt($d);
}

$old_error_handler = set_error_handler("userErrorHandler");

// undefined constant, generates a warning
$t = I_AM_NOT_DEFINED;

// define some "vectors"
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);

// generate a user error
$t1 = distance($c, $b) . "\n";

// generate another user error
$t2 = distance($b, "i am not an array") . "\n";

// generate a warning
$t3 = distance($a, $b) . "\n";

?>

Predefined Constants
Error Handling Functions
Error Handling


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Error Handling


Clone the exception

Exception::__toString
ErrorException
Exception
PHP Manual

Exception::__clone

(PHP 5 >= 5.1.0)

Exception::__clone — Clone the exception

Description

final private void Exception::__clone ( void )

Tries to clone the Exception, which results in Fatal error.

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

Exceptions are not clonable.

Exception::__toString
ErrorException
Exception


Construct the exception

Exception
Exception::getMessage
Exception
PHP Manual

Exception::__construct

(PHP 5 >= 5.1.0)

Exception::__construct — Construct the exception

Description

public Exception::__construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )

Constructs the Exception.

Parameters

message

The Exception message to throw.

code

The Exception code.

previous

The previous exception used for the exception chaining.

Changelog

Version | Description
5.3.0 | The previous parameter was added.

Exception
Exception::getMessage
Exception


Gets the Exception code

Exception::getPrevious
Exception::getFile
Exception
PHP Manual

Exception::getCode

(PHP 5 >= 5.1.0)

Exception::getCode — Gets the Exception code

Description

final public int Exception::getCode ( void )

Returns the Exception code.

Parameters

This function has no parameters.

Return Values

Returns the Exception code as a integer.

Examples

Example #1 Exception::getCode() example

<?php
try {
    throw new Exception("Some error message", 30);
} catch(Exception $e) {
    echo "The exception code is: " . $e->getCode();
}
?>

The above example will output something similar to:

The exception code is: 30

Exception::getPrevious
Exception::getFile
Exception


Gets the file in which the exception occurred

Exception::getCode
Exception::getLine
Exception
PHP Manual

Exception::getFile

(PHP 5 >= 5.1.0)

Exception::getFile — Gets the file in which the exception occurred

Description

final public string Exception::getFile ( void )

Get the name of the file the exception was thrown from.

Parameters

This function has no parameters.

Return Values

Returns the filename in which the exception was thrown.

Examples

Example #1 Exception::getFile() example

<?php
try {
    throw new Exception;
} catch(Exception $e) {
    echo $e->getFile();
}
?>

The above example will output something similar to:

/home/bjori/tmp/ex.php

Exception::getCode
Exception::getLine
Exception


Gets the line in which the exception occurred

Exception::getFile
Exception::getTrace
Exception
PHP Manual

Exception::getLine

(PHP 5 >= 5.1.0)

Exception::getLine — Gets the line in which the exception occurred

Description

final public int Exception::getLine ( void )

Returns line number where the exception was thrown.

Parameters

This function has no parameters.

Return Values

Returns the line number where the exception was thrown.

Examples

Example #1 Exception::getLine() example

<?php
try {
    throw new Exception("Some error message");
} catch(Exception $e) {
    echo "The exception was thrown on line: " . $e->getLine();
}
?>

The above example will output something similar to:

The exception was thrown on line: 3

Exception::getFile
Exception::getTrace
Exception


Gets the Exception message

Exception::__construct
Exception::getPrevious
Exception
PHP Manual

Exception::getMessage

(PHP 5 >= 5.1.0)

Exception::getMessage — Gets the Exception message

Description

final public string Exception::getMessage ( void )

Returns the Exception message.

Parameters

This function has no parameters.

Return Values

Returns the Exception message as a string.

Examples

Example #1 Exception::getMessage() example

<?php
try {
    throw new Exception("Some error message");
} catch(Exception $e) {
    echo $e->getMessage();
}
?>

The above example will output something similar to:

Some error message

Exception::__construct
Exception::getPrevious
Exception


Returns previous Exception

Exception::getMessage
Exception::getCode
Exception
PHP Manual

Exception::getPrevious

(PHP 5 >= 5.3.0)

Exception::getPrevious — Returns previous Exception

Description

final public Exception Exception::getPrevious ( void )

Returns previous Exception (the third parameter of Exception::__construct).

Parameters

This function has no parameters.

Return Values

Returns the previous Exception if available or NULL otherwise.

Examples

Example #1 Exception::getPrevious example

Looping over, and printing out, exception trace.

<?php
class MyCustomException extends Exception {}

function doStuff() {
    try {
        throw new InvalidArgumentException("You are doing it wrong!", 112);
    } catch(Exception $e) {
        throw new MyCustomException("Something happend", 911, $e);
    }
}

try {
    doStuff();
} catch(Exception $e) {
    do {
        printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
    } while($e = $e->getPrevious());
}
?>

The above example will output something similar to:

/home/bjori/ex.php:8 Something happend (911) [MyCustomException]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]

Exception::getMessage
Exception::getCode
Exception


Gets the stack trace

Exception::getLine
Exception::getTraceAsString
Exception
PHP Manual

Exception::getTrace

(PHP 5 >= 5.1.0)

Exception::getTrace — Gets the stack trace

Description

final public array Exception::getTrace ( void )

Returns the Exception stack trace.

Parameters

This function has no parameters.

Return Values

Returns the Exception stack trace as an array.

Examples

Example #1 Exception::getTrace() example

<?php
function test() {
 throw new Exception;
}

try {
 test();
} catch(Exception $e) {
 var_dump($e->getTrace());
}
?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(4) {
    ["file"]=>
    string(22) "/home/bjori/tmp/ex.php"
    ["line"]=>
    int(7)
    ["function"]=>
    string(4) "test"
    ["args"]=>
    array(0) {
    }
  }
}

Exception::getLine
Exception::getTraceAsString
Exception


Gets the stack trace as a string

Exception::getTrace
Exception::__toString
Exception
PHP Manual

Exception::getTraceAsString

(PHP 5 >= 5.1.0)

Exception::getTraceAsString — Gets the stack trace as a string

Description

final public string Exception::getTraceAsString ( void )

Returns the Exception stack trace as a string.

Parameters

This function has no parameters.

Return Values

Returns the Exception stack trace as a string.

Examples

Example #1 Exception::getTraceAsString() example

<?php
function test() {
    throw new Exception;
}

try {
    test();
} catch(Exception $e) {
    echo $e->getTraceAsString();
}
?>

The above example will output something similar to:

#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}

Exception::getTrace
Exception::__toString
Exception


String representation of the exception

Exception::getTraceAsString
Exception::__clone
Exception
PHP Manual

Exception::__toString

(PHP 5 >= 5.1.0)

Exception::__toString — String representation of the exception

Description

public string Exception::__toString ( void )

Returns the string representation of the exception.

Parameters

This function has no parameters.

Return Values

Returns the string representation of the exception.

Examples

Example #1 Exception::__toString() example

<?php
try {
    throw new Exception("Some error message");
} catch(Exception $e) {
    echo $e;
}
?>

The above example will output something similar to:

exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}

Exception::getTraceAsString
Exception::__clone
Exception


Predefined Constants

This extension has no constants defined.

Resource Types
Program execution Functions
Program execution


Resource Types

This extension defines a process resource, returned by proc_open().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Program execution


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Exif supports automatically conversion for Unicode and JIS character encodings of user comments when module mbstring is available. This is done by first decoding the comment using the specified characterset. The result is then encoded with another characterset which should match your HTTP output.

Exif configuration options
Name | Default | Changeable | Changelog
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.encode_jis | "" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

exif.encode_unicode string

exif.encode_unicode defines the characterset UNICODE user comments are handled. This defaults to ISO-8859-15 which should work for most non Asian countries. The setting can be empty or must be an encoding supported by mbstring. If it is empty the current internal encoding of mbstring is used.

exif.decode_unicode_motorola string

exif.decode_unicode_motorola defines the image internal characterset for Unicode encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2BE.

exif.decode_unicode_intel string

exif.decode_unicode_intel defines the image internal characterset for Unicode encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2LE.

exif.encode_jis string

exif.encode_jis defines the characterset JIS user comments are handled. This defaults to an empty value which forces the functions to use the current internal encoding of mbstring.

exif.decode_jis_motorola string

exif.decode_jis_motorola defines the image internal characterset for JIS encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

exif.decode_jis_intel string

exif.decode_jis_intel defines the image internal characterset for JIS encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

EXIF_USE_MBSTRING (integer)

The exif_imagetype() lists several related built-in constants.

Resource Types
Exif Functions
Exif


Installation

To enable exif-support configure PHP with --enable-exif

Windows users must enable both the php_mbstring.dll and php_exif.dll DLL's in php.ini. The php_mbstring.dll DLL must be loaded before the php_exif.dll DLL so adjust your php.ini accordingly.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

Your PHP must be compiled in with --enable-exif. PHP does not require any additional library for the exif module. Windows users must also have the mbstring extension enabled.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Exif


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

In order to configure expect extension, there are configuration options in the configuration file php.ini.

Expect Configure Options
Name | Default | Changeable | Changelog
expect.timeout | "10" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.logfile | "" | PHP_INI_ALL |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

expect.timeout integer

The timeout period for waiting for the data, when using the expect_expectl() function.

A value of "-1" disables a timeout from occurring.

Note: A value of "0" causes the expect_expectl() function to return immediately.

expect.loguser boolean

Whether expect should send any output from the spawned process to stdout. Since interactive programs typically echo their input, this usually suffices to show both sides of the conversation.

expect.logfile string

Name of the file, where the output from the spawned process will be written. If this file doesn't exist, it will be created.

Note: If this configuration is not empty, the output is written regardless of the value of expect.loguser.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

EXP_GLOB (integer)
Indicates that the pattern is a glob-style string pattern.
EXP_EXACT (integer)
Indicates that the pattern is an exact string.
EXP_REGEXP (integer)
Indicates that the pattern is a regexp-style string pattern.
EXP_EOF (integer)
Value, returned by expect_expectl(), when EOF is reached.
EXP_TIMEOUT (integer)
Value, returned by expect_expectl() upon timeout of seconds, specified in value of expect.timeout
EXP_FULLBUFFER (integer)
Value, returned by expect_expectl() if no pattern have been matched.
Resource Types
Examples
Expect


Examples

Table of Contents

  • Expect Usage Examples
Predefined Constants
Expect Usage Examples
Expect


Expect Usage Examples

Example #1 Expect Usage Example

This example connects to the remote host via SSH, and prints the remote uptime.

<?php
ini_set("expect.loguser", "Off");

$stream = fopen("expect://ssh root@remotehost uptime", "r");

$cases = array (
    array (0 => "password:", 1 => PASSWORD)
);

switch (expect_expectl ($stream, $cases)) {
    case PASSWORD:
        fwrite ($stream, "password\n");
        break;

    default:
        die ("Error was occurred while connecting to the remote host!\n");
}

while ($line = fgets($stream)) {
      print $line;
}
fclose ($stream);
?>

The following example connects to the remote host, determines whether installed OS is for 32 or 64 bit, then runs update for specific package.

Example #2 Another Expect Usage Example

<?php
ini_set("expect.timeout", -1);
ini_set("expect.loguser", "Off");

$stream = expect_popen("ssh root@remotehost");

while (true) {
    switch (expect_expectl ($stream, array (
            array ("password:", PASSWORD), // SSH is asking for password
            array ("yes/no)?", YESNO), // SSH is asking whether to store the host entry
            array ("~$ ", SHELL, EXP_EXACT), // We've got the shell!
    ))) {
        case PASSWORD:
            fwrite ($stream, "secret\n");
            break;

        case YESNO:
            fwrite ($stream, "yes\n");
            break;

        case SHELL:
            fwrite ($stream, "uname -a\n");
            while (true) {
                    switch (expect_expectl ($stream, array (
                            array ("~$ ", SHELL, EXP_EXACT), // We've got the shell!
                            array ("^Linux.*$", UNAME, EXP_REGEXP), // uname -a output
                    ), $match)) {
                        case UNAME:
                            $uname .= $match[0];
                            break;

                        case SHELL:
                            // Run update:
                            if (strstr ($uname, "x86_64")) {
                                    fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_64bit.rpm\n");
                            } else {
                                    fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_32bit.rpm\n");
                            }
                            fwrite ($stream, "exit\n");
                            break 2;

                        case EXP_TIMEOUT:
                        case EXP_EOF:
                            break 2;

                        default:
                            die ("Error has occurred!\n");
                    }
            }
            break 2;

        case EXP_TIMEOUT:
        case EXP_EOF:
            break 2;

        default:
            die ("Error has occurred!\n");
    }
}

fclose ($stream);
?>
Examples
Expect Functions
Examples


Installation

This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/expect.

In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile PHP with expect support by using the --with-expect[=DIR] configure option.

Windows users will enable php_expect.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

This module uses the functions of the » expect library. You need libexpect version >= 5.43.0.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

expect_popen() returns an open PTY stream used by expect_expectl().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Expect


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

FrontBase configuration options
Name | Default | Changeable | Changelog
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.2.0.
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.autocommit | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_links | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_connections | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_results | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.batchSize | "1000" | PHP_INI_SYSTEM | Available since PHP 4.2.0. Removed in PHP 5.1.0.
fbsql.default_host | NULL | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_password | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_database | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_database_password | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FBSQL_ASSOC (integer)
FBSQL_NUM (integer)
FBSQL_BOTH (integer)
FBSQL_LOCK_DEFERRED (integer)
FBSQL_LOCK_OPTIMISTIC (integer)
FBSQL_LOCK_PESSIMISTIC (integer)
FBSQL_ISO_READ_UNCOMMITTED (integer)
FBSQL_ISO_READ_COMMITTED (integer)
FBSQL_ISO_REPEATABLE_READ (integer)
FBSQL_ISO_SERIALIZABLE (integer)
FBSQL_ISO_VERSIONED (integer)
FBSQL_UNKNOWN (integer)
FBSQL_STOPPED (integer)
FBSQL_STARTING (integer)
FBSQL_RUNNING (integer)
FBSQL_STOPPING (integer)
FBSQL_NOEXEC (integer)
FBSQL_LOB_DIRECT (integer)
FBSQL_LOB_HANDLE (integer)
Resource Types
FrontBase Functions
FrontBase


Installation

In order to have these functions available, you must compile PHP with fbsql support by using the --with-fbsql[=DIR] option. If you use this option without specifying the path to fbsql, PHP will search for the fbsql client libraries in the default installation location for the platform. Users who installed FrontBase in a non standard directory should always specify the path to fbsql: --with-fbsql=/path/to/fbsql. This will force PHP to use the client libraries installed by FrontBase, avoiding any conflicts.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You must install the FrontBase database server or at least the fbsql client libraries to use this functions. You can get FrontBase from » http://www.frontbase.com/.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
FrontBase


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FDFValue (integer)
FDFStatus (integer)
FDFFile (integer)
FDFID (integer)
FDFFf (integer)
FDFSetFf (integer)
FDFClearFf (integer)
FDFFlags (integer)
FDFSetF (integer)
FDFClrF (integer)
FDFAP (integer)
FDFAS (integer)
FDFAction (integer)
FDFAA (integer)
FDFAPRef (integer)
FDFIF (integer)
FDFEnter (integer)
FDFExit (integer)
FDFDown (integer)
FDFUp (integer)
FDFFormat (integer)
FDFValidate (integer)
FDFKeystroke (integer)
FDFCalculate (integer)
FDFNormalAP (integer)
FDFRolloverAP (integer)
FDFDownAP (integer)
Resource Types
Examples
FDF


Examples

The following examples shows just the evaluation of form data.

Example #1 Evaluating a FDF document

<?php
// Open fdf from input string provided by the extension
// The pdf form contained several input text fields with the names
// volume, date, comment, publisher, preparer, and two checkboxes
// show_publisher and show_preparer.
$fdf = fdf_open_string($HTTP_FDF_DATA);
$volume = fdf_get_value($fdf, "volume");
echo "The volume field has the value '<b>$volume</b>'<br />";

$date = fdf_get_value($fdf, "date");
echo "The date field has the value '<b>$date</b>'<br />";

$comment = fdf_get_value($fdf, "comment");
echo "The comment field has the value '<b>$comment</b>'<br />";

if (fdf_get_value($fdf, "show_publisher") == "On") {
  $publisher = fdf_get_value($fdf, "publisher");
  echo "The publisher field has the value '<b>$publisher</b>'<br />";
} else
  echo "Publisher shall not be shown.<br />";

if (fdf_get_value($fdf, "show_preparer") == "On") {
  $preparer = fdf_get_value($fdf, "preparer");
  echo "The preparer field has the value '<b>$preparer</b>'<br />";
} else
  echo "Preparer shall not be shown.<br />";
fdf_close($fdf);
?>

Predefined Constants
FDF Functions
FDF


Installation

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL SVN here: » http://svn.php.net/viewvc/pecl/fdf.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0

Note: If you run into problems configuring PHP with fdftk support, check whether the header file fdftk.h and the library libfdftk.so are at the right place. The configure script supports both the directory structure of the FDF SDK distribution and the usual DIR/include / DIR/lib layout, so you can point it either directly to the unpacked distribution directory or put the header file and the appropriate library for your platform into e.g. /usr/local/include and /usr/local/lib and configure with --with-fdftk=/usr/local.

Note: Note to Win32 Users
In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: fdftk.dll

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You need the FDF toolkit SDK available from » http://partners.adobe.com/asn/acrobat/forms.jsp. As of PHP 4.3.0 you need at least SDK version 5.0. The FDF toolkit library is available in binary form only, platforms supported by Adobe are Win32, Linux, Solaris and AIX.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

Most fdf functions require a fdf resource as their first parameter. A fdf resource is a handle to an opened fdf file. fdf resources may be obtained using fdf_create(), fdf_open() and fdf_open_string().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
FDF


Features

  • HTTP authentication with PHP
  • Cookies
  • Sessions
  • Dealing with XForms
  • Handling file uploads
    • POST method uploads
    • Error Messages Explained
    • Common Pitfalls
    • Uploading multiple files
    • PUT method support
  • Using remote files
  • Connection handling
  • Persistent Database Connections
  • Safe Mode
    • Security and Safe Mode
    • Functions restricted/disabled by safe mode
  • Command line usage — Using PHP from the command line
    • Introduction
    • Differences to other SAPIs
    • Options — Command line options
    • Usage — Executing PHP files
    • I/O streams — Input/output streams
  • Garbage Collection
    • Reference Counting Basics
    • Collecting Cycles
    • Performance Considerations
Keeping Current
HTTP authentication with PHP


Using PHP from the command line

Table of Contents

  • Introduction
  • Differences to other SAPIs
  • Command line options
  • Executing PHP files
  • Input/output streams
Functions restricted/disabled by safe mode
Introduction
Features


Differences to other SAPIs

Remarkable differences of the CLI SAPI compared to other SAPIs:

  • Unlike the CGI SAPI, no headers are written to the output.

    Though the CGI SAPI provides a way to suppress HTTP headers, there's no equivalent switch to enable them in the CLI SAPI.

    CLI is started up in quiet mode by default, though the -q and --no-header switches are kept for compatibility so that you can use older CGI scripts.

    It does not change the working directory to that of the script. (-C and --no-chdir switches kept for compatibility)

    Plain text error messages (no HTML formatting).

  • There are certain php.ini directives which are overridden by the CLI SAPI because they do not make sense in shell environments:

    Overridden php.ini directives
    Directive | CLI SAPI default value | Comment
    html_errors | FALSE | It can be quite hard to read the error message in your shell when it's cluttered with all those meaningless HTML tags, therefore this directive defaults to FALSE.
    implicit_flush | TRUE | It is desired that any output coming from print(), echo() and friends is immediately written to the output and not cached in any buffer. You still can use output buffering if you want to defer or manipulate standard output.
    max_execution_time | 0 (unlimited) | Due to endless possibilities of using PHP in shell environments, the maximum execution time has been set to unlimited. Whereas applications written for the web are often executed very quickly, shell application tend to have a much longer execution time.
    register_argc_argv TRUE

    Because this setting is TRUE you will always have access to argc (number of arguments passed to the application) and argv (array of the actual arguments) in the CLI SAPI.

    The PHP variables $argc and $argv are registered and filled in with the appropriate values when using the CLI SAPI. You can also go through $_SERVER or. Example: $_SERVER['argv']

    output_buffering FALSE

    Altough the php.ini setting is hardcoded to FALSE the Output buffering functions are available.

    max_input_time FALSE

    The PHP CLI doesn't not support GET, POST or file uploads.

    Note: These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This is a limitation because those default values are applied after all configuration files have been parsed. However, their value can be changed during runtime (which does not make sense for all of those directives, e.g. register_argc_argv).

    Note: It is recommended to set ignore_user_abort for command line scripts. See ignore_user_abort() for more info.

  • To ease working in the shell environment, a number of constants are defined for I/O streams .

  • The CLI SAPI does not change the current directory to the directory of the executed script!

    Example showing the difference to the CGI SAPI:

    <?php
    // Our simple test application named test.php
    echo getcwd(), "\n";
    ?>

    When using the CGI version, the output is:

    $ pwd
/tmp

$ php -q another_directory/test.php
/tmp/another_directory

    This clearly shows that PHP changes its current directory to the one of the executed script.

    Using the CLI SAPI yields:

    $ pwd
/tmp

$ php -f another_directory/test.php
/tmp

    This allows greater flexibility when writing shell tools in PHP.

    Note: The CGI SAPI supports this CLI SAPI behaviour by means of the -C switch when run from the command line.

Introduction
Options
Command line usage


Introduction

PHP supports a CLI SAPI as of PHP 4.3.0. The main focus of this SAPI is for developing shell applications with PHP. There are quite a few differences between the CLI SAPI and other SAPIs which are explained in this chapter. It is worth mentioning that CLI and CGI are different SAPIs although they do share many of the same behaviors.

The CLI SAPI is enabled by default using --enable-cli, but may be disabled using the --disable-cli option when running ./configure.

The name, location and existence of the CLI/CGI binaries will differ depending on how PHP is installed on your system. By default when executing make, both the CGI and CLI are built and placed as sapi/cgi/php-cgi and sapi/cli/php respectively, in your PHP source directory. You will note that both are named php. What happens during make install depends on your configure line. If a module SAPI is chosen during configure, such as apxs, or the --disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there. So, for example, if --with--apxs is in your configure line then the CLI is copied to {PREFIX}/bin/php during make install. If you want to override the installation of the CGI binary, use make install-cli after make install. Alternatively you can specify --disable-cgi in your configure line.

Note: Because both --enable-cli and --enable-cgi are enabled by default, simply having --enable-cli in your configure line does not necessarily mean the CLI will be copied as {PREFIX}/bin/php during make install.

As of PHP 5, the CLI binary is distributed in the main folder as php.exe on Windows. The CGI version is distributed as php-cgi.exe. Additionally, a php-win.exe is distributed if PHP is configured using --enable-cli-win32. This does the same as the CLI version, except that it doesn't output anything and thus provides no console.

Note: What SAPI do I have?
From a shell, typing php -v will tell you whether php is CGI or CLI. See also the function php_sapi_name() and the constant PHP_SAPI.

Note: A Unix manual page is available by typing man php in your shell environment.

Command line usage
Differences to other SAPIs
Command line usage


Input/output streams

The CLI SAPI defines a few constants for I/O streams to make programming for the command line a bit easier.

CLI specific Constants
Constant Description
STDIN

An already opened stream to stdin. This saves opening it with

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

If you want to read single line from stdin, you can use

<?php
$line = trim(fgets(STDIN)); // reads one line from STDIN
fscanf(STDIN, "%d\n", $number); // reads number from STDIN
?>

STDOUT

An already opened stream to stdout. This saves opening it with

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

STDERR

An already opened stream to stderr. This saves opening it with

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

Given the above, you don't need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:

php -r 'fwrite(STDERR, "stderr\n");'

You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.

Note: These constants are not available in case of reading PHP script from stdin.

Usage
Garbage Collection
Command line usage


Command line options

The list of command line options provided by the PHP binary can be queried anytime by running PHP with the -h switch:

Usage: php [options] [-f] <file> [--] [args...]
       php [options] -r <code> [--] [args...]
       php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
       php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
       php [options] -- [args...]
       php [options] -a

  -a               Run interactively
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse and execute <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags <?..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -E <end_code>    Run PHP <end_code> after processing all input lines
  -H               Hide any passed arguments from external tools.
  -s               Output HTML syntax highlighted source.
  -v               Version number
  -w               Output source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

  --ini            Show configuration file names

  --rf <name>      Show information about function <name>.
  --rc <name>      Show information about class <name>.
  --re <name>      Show information about extension <name>.
  --ri <name>      Show configuration for extension <name>.

Command line options
Option | Long Option | Description
-a --interactive

Runs PHP interactively. If you compile PHP with the Readline extension (which is not available on Windows), you'll have a nice shell, including a completion feature (e.g. you can start typing a variable name, hit the TAB key and PHP completes its name) and a typing history that can be accessed using the arrow keys. The history is saved in the ~/.php_history file.

Note: Files included through auto_prepend_file and auto_append_file are parsed in this mode but with some restrictions - e.g. functions have to be defined before called.

Note: Autoloading is not available if using PHP in CLI interactive mode.

-b --bindpath

Bind Path for external FASTCGI Server mode (CGI only).

-C --no-chdir

Do not chdir to the script's directory (CGI only).

-q --no-header

Quiet-mode. Suppress HTTP header output (CGI only).

-T --timing

Measure execution time of script repeated count times (CGI only).

-c --php-ini

This option can either specify a directory where to look for php.ini or specify a custom INI file (which does not need to be named php.ini), e.g.:

$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php

If you don't specify this option, file is searched in default locations.

-n --no-php-ini

Ignore php.ini at all.

-d --define

This option allows you to set a custom value for any of the configuration directives allowed in php.ini. The syntax is:

 -d configuration_directive[=value]

Examples (lines are wrapped for layout reasons):

# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time=
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# The configuration directive will be set to anything passed after the '=' character
$  php -d max_execution_time=20
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php
        -d max_execution_time=doesntmakesense
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

-e --profile-info

Activate the extended information mode, to be used by a debugger/profiler.

-f --file

Parses and executes the given filename to the -f option. This switch is optional and can be left out. Only providing the filename to execute is sufficient.

Note: To pass arguments to scripts the first argument needs to be --, otherwise PHP will interperate them as PHP options.

-h and -? | --help and --usage | With this option, you can get information about the actual list of command line options and some one line descriptions about what they do.
-i | --info | This command line option calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use php -i and see whether any error messages are printed out before or in place of the information tables. Beware that when using the CGI mode the output is in HTML and therefore quite huge.
-l --syntax-check

This option provides a convenient way to only perform a syntax check on the given PHP code. On success, the text No syntax errors detected in <filename> is written to standard output and the shell return code is 0. On failure, the text Errors parsing <filename> in addition to the internal parser error message is written to standard output and the shell return code is set to -1.

This option won't find fatal errors (like undefined functions). Use -f if you would like to test for fatal errors too.

Note: This option does not work together with the -r option.

-m --modules

Using this option, PHP prints out the built in (and loaded) PHP and Zend modules:

$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-r --run

This option allows execution of PHP right from within the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parser error if present.

Note: Care has to be taken when using this form of PHP to not collide with command line variable substitution done by the shell.

Example showing a parser error

$ php -r "$foo = get_defined_constants();"
PHP Parse error:  syntax error, unexpected '=' in Command line code on line 1

Parse error: syntax error, unexpected '=' in Command line code on line 1

The problem here is that the sh/bash performs variable substitution even when using double quotes ". Since the variable $foo is unlikely to be defined, it expands to nothing which results in the code passed to PHP for execution actually reading:

$ php -r " = get_defined_constants();"

The correct way would be to use single quotes '. Variables in single-quoted strings are not expanded by sh/bash.

$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]

If you are using a shell different from sh/bash, you might experience further issues. Feel free to open a bug report at » http://bugs.php.net/. One can still easily run into troubles when trying to get shell variables into the code or using backslashes for escaping. You've been warned.

Note: -r is available in the CLI SAPI and not in the CGI SAPI.

Note: This option is meant for a very basic stuff. Thus some configuration directives (e.g. auto_prepend_file and auto_append_file) are ignored in this mode.

-B --process-begin

PHP code to execute before processing stdin. Added in PHP 5.

-R --process-code

PHP code to execute for every input line. Added in PHP 5.

There are two special variables available in this mode: $argn and $argi. $argn will contain the line PHP is processing at that moment, while $argi will contain the line number.

-F --process-file

PHP file to execute for every input line. Added in PHP 5.

-E --process-end

PHP code to execute after processing the input. Added in PHP 5.

Example #1 Using the -B, -R and -E options to count the number of lines of a project.

$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328

-s --syntax-highlight and --syntax-highlighting

Display colour syntax highlighted source.

This option uses the internal mechanism to parse the file and produces a HTML highlighted version of it and writes it to standard output. Note that all it does it to generate a block of <code> [...] </code> HTML tags, no HTML headers.

Note: This option does not work together with the -r option.

-v --version

Writes the PHP, PHP SAPI, and Zend version to standard output, e.g.

$ php -v
PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

-w --strip

Display source with stripped comments and whitespace.

Note: This option does not work together with the -r option.

-z --zend-extension

Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually specified /etc/ld.so.conf on Linux systems). Passing a filename with an absolute path information will not use the systems library search path. A relative filename with a directory information will tell PHP only to try to load the extension relative to the current directory.

--ini

Shows configuration file names and scanned directories. Available as of PHP 5.2.3.

Example #2 --ini example

$ php --ini
Configuration File (php.ini) Path: /usr/dev/php/5.2/lib
Loaded Configuration File:         /usr/dev/php/5.2/lib/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)
--rf --rfunction

Shows information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #3 basic --rf usage

$ php --rf var_dump
Function [ <internal> public function var_dump ] {

  - Parameters [2] {
    Parameter #0 [ <required> $var ]
    Parameter #1 [ <optional> $... ]
  }
}
--rc --rclass

Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #4 --rc example

$ php --rc Directory
Class [ <internal:standard> class Directory ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [3] {
    Method [ <internal> public method close ] {
    }

    Method [ <internal> public method rewind ] {
    }

    Method [ <internal> public method read ] {
    }
  }
}
--re --rextension

Show information about the given extension (list of php.ini options, defined functions, constants and classes). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #5 --re example

$ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {

  - Functions {
    Function [ <internal> function json_encode ] {
    }
    Function [ <internal> function json_decode ] {
    }
  }
}
--ri --rextinfo

Shows the configuration information for the given extension (the same information that is returned by phpinfo()). Available as of PHP 5.2.2. The core configuration information are available using "main" as extension name.

Example #6 --ri example

$ php --ri date

date

date/time support => enabled
"Olson" Timezone Database Version => 2009.20
Timezone Database => internal
Default timezone => Europe/Oslo

Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.930972 => 59.930972
date.default_longitude => 10.776699 => 10.776699
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333

Note: Options -rBRFEH, --ini and --r[fcei] are available only in CLI.

Differences to other SAPIs
Usage
Command line usage


Executing PHP files

The CLI SAPI has three different ways of getting the PHP code you want to execute:

  1. Telling PHP to execute a certain file.

    $ php my_script.php

$ php -f my_script.php

    Both ways (whether using the -f switch or not) execute the file my_script.php. You can choose any file to execute, and your PHP scripts do not have to end with the .php extension but can have any name or extension you wish.

    Note: If you need to pass arguments to your scripts you need to pass -- as the first argument when using the -f switch.

  2. Pass the PHP code to execute directly on the command line.

    $ php -r 'print_r(get_defined_constants());'

    Special care has to be taken in regards of shell variable substitution and quoting usage.

    Note: Read the example carefully, there are no beginning or ending tags! The -r switch simply does not need them. Using them will lead to a parser error.

  3. Provide the PHP code to execute via standard input (stdin).

    This gives the powerful ability to dynamically create PHP code and feed it to the binary, as shown in this (fictional) example:

    $ some_application | some_filter | php | sort -u > final_output.txt

You cannot combine any of the three ways to execute code.

Like every shell application, the PHP binary accepts a number of arguments but your PHP script can also receive arguments. The number of arguments which can be passed to your script is not limited by PHP (the shell has a certain size limit in the number of characters which can be passed; usually you won't hit this limit). The arguments passed to your script are available in the global array $argv. The zero index always contains the script name (which is - in case the PHP codeis coming from either standard input or from the command line switch -r). The second registered global variable is $argc which contains the number of elements in the $argv array (not the number of arguments passed to the script).

As long as the arguments you want to pass to your script do not start with the - character, there's nothing special to watch out for. Passing an argument to your script which starts with a - will cause trouble because PHP itself thinks it has to handle it. To prevent this, use the argument list separator --. After this separator has been parsed by PHP, every argument following it is passed untouched to your script.

# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# This will pass the '-h' argument to your script and prevent PHP from showing it's usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

However on Unix systems, there's another way of using PHP for shell scripting. You can write a script where the first line starts with #!/usr/bin/php (substitute with the path to your PHP CLI binary if necessary. Following this you can place normal PHP code included within the PHP starting and end tags. Once you have set the execution attributes of the file appropriately (e.g. chmod +x test) your script can be executed like a normal shell or perl script:

Example #1 Execute PHP script as shell script

#!/usr/bin/php
<?php
var_dump($argv);
?>

Assuming this file is named test in the current directory, we can now do the following:

$ chmod +x test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}

As you see, in this case no care needs to be taken when passing parameters which start with - to your script.

The PHP executable can be used to run PHP scripts absolutely independent from the web server. If you are on a Unix system, you should add a special first line to your PHP script, and make it executable, so the system will know, what program should run the script. On a Windows platform you can associate php.exe with the double click option of the .php files, or you can make a batch file to run the script through PHP. The first line added to the script to work on Unix won't hurt on Windows, so you can write cross platform programs this way. A simple example of writing a command line PHP program can be found below.

Example #2 Script intended to be run from command line (script.php)

#!/usr/bin/php
<?php

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

This is a command line PHP script with one option.

  Usage:
  <?php echo $argv[0]; ?> <option>

  <option> can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

<?php
} else {
    echo $argv[1];
}
?>

In the script above, we used the special first line to indicate that this file should be run by PHP. We work with a CLI version here, so there will be no HTTP header printouts. There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).

In the program above we checked if there are less or more than one arguments. Also if the argument was --help, -help, -h or -?, we printed out the help message, printing the script name dynamically. If we received some other argument we echoed that out.

If you would like to run the above script on Unix, you need to make it executable, and simply call it as script.php echothis or script.php -h. On Windows, you can make a batch file for this task:

Example #3 Batch file to run a command line PHP script (script.bat)

@echo OFF
"C:\php\php.exe" script.php %*

Assuming you named the above program script.php, and you have your CLI php.exe in C:\php\php.exe this batch file will run it for you with your added options: script.bat echothis or script.bat -h.

See also the Readline extension documentation for more functions you can use to enhance your command line applications in PHP.

If you are on Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as descibed in Command Line PHP on Microsoft Windows.

Options
I/O streams
Command line usage


Connection handling

Internally in PHP a connection status is maintained. There are 3 possible states:

  • 0 - NORMAL
  • 1 - ABORTED
  • 2 - TIMEOUT

When a PHP script is running normally the NORMAL state, is active. If the remote client disconnects the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.

You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php.ini directive as well as through the corresponding php_value ignore_user_abort Apache httpd.conf directive or with the ignore_user_abort() function. If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The one exception is if you have registered a shutdown function using register_shutdown_function(). With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client disconnect you can use the connection_aborted() function. This function will return TRUE if the connection was aborted.

Your script can also be terminated by the built-in script timer. The default timeout is 30 seconds. It can be changed using the max_execution_time php.ini directive or the corresponding php_value max_execution_time Apache httpd.conf directive as well as with the set_time_limit() function. When the timer expires the script will be aborted and as with the above client disconnect case, if a shutdown function has been registered it will be called. Within this shutdown function you can check to see if a timeout caused the shutdown function to be called by calling the connection_status() function. This function will return 2 if a timeout caused the shutdown function to be called.

One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_status() returns 3.

Using remote files
Persistent Database Connections
Features


Cookies

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers.

Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just add [] to the cookie name.

Depending on register_globals, regular PHP variables can be created from cookies. However it's not recommended to rely on them as this feature is often turned off for the sake of security. $HTTP_COOKIE_VARS is also set in earlier versions of PHP when the track_vars configuration variable is set. (This setting is always on since PHP 4.0.3.)

For more details, including notes on browser bugs, see the setcookie() and setrawcookie() function.

HTTP authentication with PHP
Sessions
Features


Handling file uploads

Table of Contents

  • POST method uploads
  • Error Messages Explained
  • Common Pitfalls
  • Uploading multiple files
  • PUT method support
Dealing with XForms
POST method uploads
Features


Common Pitfalls

The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize in the php.ini file. The default is 2 megabytes.

If a memory limit is enabled, a larger memory_limit may be needed. Make sure you set memory_limit large enough.

If max_execution_time is set too small, script execution may be exceeded by the value. Make sure you set max_execution_time large enough.

Note: max_execution_time only affects the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, time taken by the file upload process, etc. is not included when determining the maximum time that the script has been running.

Warning

max_input_time sets the maximum time, in seconds, the script is allowed to receive input; this includes file uploads. For large or multiple files, or users on slower connections, the default of 60 seconds may be exceeded.

If post_max_size is set too small, large files cannot be uploaded. Make sure you set post_max_size large enough.

Not validating which file you operate on may mean that users can access sensitive information in other directories.

Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature.

Due to the large amount of directory listing styles we cannot guarantee that files with exotic names (like containing spaces) are handled properly.

A developer may not mix normal input fields and file upload fields in the same form variable (by using an input name like foo[]).

Error Messages Explained
Uploading multiple files
Handling file uploads


Error Messages Explained

Since PHP 4.2.0, PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error'].

UPLOAD_ERR_OK

Value: 0; There is no error, the file uploaded with success.

UPLOAD_ERR_INI_SIZE

Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE

Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL

Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE

Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR

Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE

Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION

Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.

Note: These became PHP constants in PHP 4.3.0.

POST method uploads
Common Pitfalls
Handling file uploads


Uploading multiple files

Multiple files can be uploaded using different name for input.

It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes:

Example #1 Uploading multiple files

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

When the above form is submitted, the arrays $_FILES['userfile'], $_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be initialized (as well as in $HTTP_POST_FILES for PHP versions prior to 4.1.0). When register_globals is on, globals for uploaded files are also initialized. Each of these will be a numerically indexed array of the appropriate values for the submitted files.

For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth.

$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set.

Common Pitfalls
PUT method support
Handling file uploads


POST method uploads

This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded.

PHP is capable of receiving file uploads from any RFC-1867 compliant browser.

Note: Related Configurations Note
See also the file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time directives in php.ini

PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details.

Example #1 File Upload Form

A file upload screen can be built by creating a special form which looks something like this:

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

The __URL__ in the above example should be replaced, and point to a PHP file.

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.

Note: Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.

The global $_FILES exists as of PHP 4.1.0 (Use $HTTP_POST_FILES instead if using an earlier version). These arrays will contain all the uploaded file information.

The contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.

$_FILES['userfile']['name']

The original name of the file on the client machine.

$_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

$_FILES['userfile']['size']

The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name']

The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']

The error code associated with this file upload. This element was added in PHP 4.2.0

Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well.

Example #2 Validating file uploads

See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form.

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. As of PHP 4.2.0, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.

If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.

Example #3 Uploading array of files

PHP supports HTML array feature even with files.

<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "data/$name");
    }
}
?>

File upload progress bar can be implemented by apc.rfc1867.

Handling file uploads
Error Messages Explained
Handling file uploads


PUT method support

PHP provides support for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this:

PUT /path/filename.html HTTP/1.1

This would normally mean that the remote client would like to save the content that follows as: /path/filename.html in your web tree. It is obviously not a good idea for Apache or PHP to automatically let everybody overwrite any files in your web tree. So, to handle such a request you have to first tell your web server that you want a certain PHP script to handle the request. In Apache you do this with the Script directive. It can be placed almost anywhere in your Apache configuration file. A common place is inside a <Directory> block or perhaps inside a <VirtualHost> block. A line like this would do the trick:

Script PUT /put.php

This tells Apache to send all PUT requests for URIs that match the context in which you put this line to the put.php script. This assumes, of course, that you have PHP enabled for the .php extension and PHP is active. The destination resource for all PUT requests to this script has to be the script itself, not a filename the uploaded file should have.

With PHP you would then do something like the following in your put.php. This would copy the contents of the uploaded file to the file myputfile.ext on the server. You would probably want to perform some checks and/or authenticate the user before performing this file copy.

Example #1 Saving HTTP PUT files

<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");

/* Read the data 1 KB at a time
   and write to the file */
while ($data = fread($putdata, 1024))
  fwrite($fp, $data);

/* Close the streams */
fclose($fp);
fclose($putdata);
?>

Uploading multiple files
Using remote files
Handling file uploads


Garbage Collection

Table of Contents

  • Reference Counting Basics
  • Collecting Cycles
  • Performance Considerations

This section explains the merits of the new Garbage Collection (also known as GC) mechanism that is part of PHP 5.3.

I/O streams
Reference Counting Basics
Features


Collecting Cycles

Traditionally, reference counting memory mechanisms, such as that used previously by PHP, fail to address circular reference memory leaks. As of 5.3.0 PHP however implements the synchronous algorithm from the » Concurrent Cycle Collection in Reference Counted Systems paper which addresses that issue.

A full explanation of how the algorithm works would be slightly beyond the scope of this section, but the basics are explained here. First of all, we have to establish a few ground rules. If a refcount is increased, it's still in use and therefore, not garbage. If the refcount is decreased and hits zero, the zval can be freed. This means that garbage cycles can only be created when a refcount argument is decreased to a non-zero value. Secondly, in a garbage cycle, it is possible to discover which parts are garbage by checking whether it is possible to decrease their refcount by one, and then checking which of the zvals have a refcount of zero.

Garbage collection algorithm

To avoid having to call the checking of garbage cycles with every possible decrease of a refcount, the algorithm instead puts all possible roots (zvals) in the "root buffer" (marking them "purple"). It also makes sure that each possible garbage root ends up in the buffer only once. Only when the root buffer is full does the collection mechanism start for all the different zvals inside. See step A in the figure above.

In step B, the algorithm runs a depth-first search on all possible roots to decrease by one the refcounts of each zval it finds, making sure not to decrease a refcount on the same zval twice (by marking them as "grey"). In step C, the algorithm again runs a depth-first search from each root node, to check the refcount of each zval again. If it finds that the refcount is zero, the zval is marked "white" (blue in the figure). If it's larger than zero, it reverts the decreasing of the refcount by one with a depth-first search from that point on, and they are marked "black" again. In the last step (D), the algorithm walks over the root buffer removing the zval roots from there, and meanwhile, checks which zvals have been marked "white" in the previous step. Every zval marked as "white" will be freed.

Now that you have a basic understanding of how the algorithm works, we will look back at how this integrates with PHP. By default, PHP's garbage collector is turned on. There is, however, a php.ini setting that allows you to change this: zend.enable_gc.

When the garbage collector is turned on, the cycle-finding algorithm as described above is executed whenever the root buffer runs full. The root buffer has a fixed size of 10,000 possible roots (although you can alter this by changing the GC_ROOT_BUFFER_MAX_ENTRIES constant in Zend/zend_gc.c in the PHP source code, and re-compiling PHP). When the garbage collector is turned off, the cycle-finding algorithm will never run. However, possible roots will always be recorded in the root buffer, no matter whether the garbage collection mechanism has been activated with this configuration setting.

If the root buffer becomes full with possible roots while the garbage collection mechanism is turned off, further possible roots will simply not be recorded. Those possible roots that are not recorded will never be analyzed by the algorithm. If they were part of a circular reference cycle, they would never be cleaned up and would create a memory leak.

The reason why possible roots are recorded even if the mechanism has been disabled is because it's faster to record possible roots than to have to check whether the mechanism is turned on every time a possible root could be found. The garbage collection and analysis mechanism itself, however, can take a considerable amount of time.

Besides changing the zend.enable_gc configuration setting, it is also possible to turn the garbage collecting mechanism on and off by calling gc_enable() or gc_disable() respectively. Calling those functions has the same effect as turning on or off the mechanism with the configuration setting. It is also possible to force the collection of cycles even if the possible root buffer is not full yet. For this, you can use the gc_collect_cycles() function. This function will return how many cycles were collected by the algorithm.

The rationale behind the ability to turn the mechanism on and off, and to initiate cycle collection yourself, is that some parts of your application could be highly time-sensitive. In those cases, you might not want the garbage collection mechanism to kick in. Of course, by turning off the garbage collection for certain parts of your application, you do risk creating memory leaks because some possible roots might not fit into the limited root buffer. Therefore, it is probably wise to call gc_collect_cycles() just before you call gc_disable() to free up the memory that could be lost through possible roots that are already recorded in the root buffer. This then leaves an empty buffer so that there is more space for storing possible roots while the cycle collecting mechanism is turned off.

Reference Counting Basics
Performance Considerations
Garbage Collection


Performance Considerations

We have already mentioned in the previous section that simply collecting the possible roots had a very tiny performance impact, but this is when you compare PHP 5.2 against PHP 5.3. Although the recording of possible roots compared to not recording them at all, like in PHP 5.2, is slower, other changes to the PHP runtime in PHP 5.3 prevented this particular performance loss from even showing.

There are two major areas in which performance is affected. The first area is reduced memory usage, and the second area is run-time delay when the garbage collection mechanism performs its memory cleanups. We will look at both of those issues.

Reduced Memory Usage

First of all, the whole reason for implementing the garbage collection mechanism is to reduce memory usage by cleaning up circular-referenced variables as soon as the prerequisites are fulfilled. In PHP's implementation, this happens as soon as the root-buffer is full, or when the function gc_collect_cycles() is called. In the graph below, we display the memory usage of the script below, in both PHP 5.2 and PHP 5.3, excluding the base memory that PHP itself uses when starting up.

Example #1 Memory usage example

<?php
class Foo
{
    public $var = '3.1415962654';
}

$baseMemory = memory_get_usage();

for ( $i = 0; $i <= 100000; $i++ )
{
    $a = new Foo;
    $a->self = $a;
    if ( $i % 500 === 0 )
    {
        echo sprintf( '%8d: ', $i ), memory_get_usage() - $baseMemory, "\n";
    }
}
?>
Comparison of memory usage between PHP 5.2 and PHP 5.3

In this very academic example, we are creating an object in which a property is set to point back to the object itself. When the $a variable in the script is re-assigned in the next iteration of the loop, a memory leak would typically occur. In this case, two zval-containers are leaked (the object zval, and the property zval), but only one possible root is found: the variable that was unset. When the root-buffer is full after 10,000 iterations (with a total of 10,000 possible roots), the garbage collection mechanism kicks in and frees the memory associated with those possible roots. This can very clearly be seen in the jagged memory-usage graph for PHP 5.3. After each 10,000 iterations, the mechanism kicks in and frees the memory associated with the circular referenced variables. The mechanism itself does not have to do a whole lot of work in this example, because the structure that is leaked is extremely simple. From the diagram, you see that the maximum memory usage in PHP 5.3 is about 9 Mb, whereas in PHP 5.2 the memory usage keeps increasing.

Run-Time Slowdowns

The second area where the garbage collection mechanism influences performance is the time taken when the garbage collection mechanism kicks in to free the "leaked" memory. In order to see how much this is, we slightly modify the previous script to allow for a larger number of iterations and the removal of the intermediate memory usage figures. The second script is here:

Example #2 GC performance influences

<?php
class Foo
{
    public $var = '3.1415962654';
}

for ( $i = 0; $i <= 1000000; $i++ )
{
    $a = new Foo;
    $a->self = $a;
}

echo memory_get_peak_usage(), "\n";
?>

We will run this script two times, once with the zend.enable_gc setting turned on, and once with it turned off:

Example #3 Running the above script

time php -dzend.enable_gc=0 -dmemory_limit=-1 -n example2.php
# and
time php -dzend.enable_gc=1 -dmemory_limit=-1 -n example2.php

On my machine, the first command seems to take consistently about 10.7 seconds, whereas the second command takes about 11.4 seconds. This is a slowdown of about 7%. However, the maximum amount of memory used by the script is reduced by 98% from 931Mb to 10Mb. This benchmark is not very scientific, or even representative of real-life applications, but it does demonstrate the memory usage benefits that this garbage collection mechanism provides. The good thing is that the slowdown is always the same 7%, for this particular script, while the memory saving capabilities save more and more memory as more circular references are found during script execution.

PHP's Internal GC Statistics

It is possible to coax a little bit more information about how the garbage collection mechanism is run from within PHP. But in order to do so, you will have to re-compile PHP to enable the benchmark and data-collecting code. You will have to set the CFLAGS environment variable to -DGC_BENCH=1 prior to running ./configure with your desired options. The following sequence should do the trick:

Example #4 Recompiling PHP to enable GC benchmarking

export CFLAGS=GC_BENCH=1
./config.nice
make clean
make

When you run the above example code again with the newly built PHP binary, you will see the following being shown after PHP has finished execution:

Example #5 GC statistics

GC Statistics
-------------
Runs:               110
Collected:          2072204
Root buffer length: 0
Root buffer peak:   10000

      Possible            Remove from  Marked
        Root    Buffered     buffer     grey
      --------  --------  -----------  ------
ZVAL   7175487   1491291    1241690   3611871
ZOBJ  28506264   1527980     677581   1025731

The most informative statistics are displayed in the first block. You can see here that the garbage collection mechanism ran 110 times, and in total, more than 2 million memory allocations were freed during those 110 runs. As soon as the garbage collection mechanism has run at least one time, the "Root buffer peak" is always 10000.

Conclusion

In general the garbage collector in PHP will only cause a slowdown when the cycle collecting algorithm actually runs, whereas in normal (smaller) scripts there should be no performance hit at all.

However, in the cases where the cycle collection mechanism does run for normal scripts, the memory reduction it will provide allows more of those scripts to run concurrently on your server, since not so much memory is used in total.

The benefits are most apparent for longer-running scripts, such as lengthy test suites or daemon scripts. Also, for » PHP-GTK applications that generally tend to run longer than scripts for the Web, the new mechanism should make quite a bit of a difference regarding memory leaks creeping in over time.

Collecting Cycles
Function Reference
Garbage Collection


Reference Counting Basics

A PHP variable is stored in a container called a "zval". A zval container contains, besides the variable's type and value, two additional bits of information. The first is called "is_ref" and is a boolean value indicating whether or not the variable is part of a "reference set". With this bit, PHP's engine knows how to differentiate between normal variables and references. Since PHP allows user-land references, as created by the & operator, a zval container also has an internal reference counting mechanism to optimize memory usage. This second piece of additional information, called "refcount", contains how many variable names (also called symbols) point to this one zval container. All symbols are stored in a symbol table, of which there is one per scope. There is a scope for the main script (i.e., the one requested through the browser), as well as one for every function or method.

A zval container is created when a new variable is created with a constant value, such as:

Example #1 Creating a new zval container

<?php
$a = "new string";
?>

In this case, the new symbol name, a, is created in the current scope, and a new variable container is created with the type string and the value new string. The "is_ref" bit is by default set to FALSE because no user-land reference has been created. The "refcount" is set to 1 as there is only one symbol that makes use of this variable container. Note that if "refcount" is 1, "is_ref" is always FALSE. If you have » Xdebug installed, you can display this information by calling xdebug_debug_zval().

Example #2 Displaying zval information

<?php
xdebug_debug_zval('a');
?>

The above example will output:

a: (refcount=1, is_ref=0)='new string'

Assigning this variable to another variable name will increase the refcount.

Example #3 Increasing refcount of a zval

<?php
$a = "new string";
$b = $a;
xdebug_debug_zval( 'a' );
?>

The above example will output:

a: (refcount=2, is_ref=0)='new string'

The refcount is 2 here, because the same variable container is linked with both a and b. PHP is smart enough not to copy the actual variable container when it is not necessary. Variable containers get destroyed when the "refcount" reaches zero. The "refcount" gets decreased by one when any symbol linked to the variable container leaves the scope (e.g. when the function ends) or when unset() is called on a symbol. The following example shows this:

Example #4 Decreasing zval refcount

<?php
$a = "new string";
$c = $b = $a;
xdebug_debug_zval( 'a' );
unset( $b, $c );
xdebug_debug_zval( 'a' );
?>

The above example will output:

a: (refcount=3, is_ref=0)='new string'
a: (refcount=1, is_ref=0)='new string'

If we now call unset($a);, the variable container, including the type and value, will be removed from memory.

Compound Types

Things get a tad more complex with compound types such as arrays and objects. Instead of a scalar value, arrays and objects store their properties in a symbol table of their own. This means that the following example creates three zval containers:

Example #5 Creating a array zval

<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
xdebug_debug_zval( 'a' );
?>

The above example will output something similar to:

a: (refcount=1, is_ref=0)=array (
   'meaning' => (refcount=1, is_ref=0)='life',
   'number' => (refcount=1, is_ref=0)=42
)

Or graphically

Zvals for a simple array

The three zval containers are: a, meaning, and number. Similar rules apply for increasing and decreasing "refcounts". Below, we add another element to the array, and set its value to the contents of an already existing element:

Example #6 Adding already existing element to an array

<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
xdebug_debug_zval( 'a' );
?>

The above example will output something similar to:

a: (refcount=1, is_ref=0)=array (
   'meaning' => (refcount=2, is_ref=0)='life',
   'number' => (refcount=1, is_ref=0)=42,
   'life' => (refcount=2, is_ref=0)='life'
)

Or graphically

Zvals for a simple array with a reference

From the above Xdebug output, we see that both the old and new array element now point to a zval container whose "refcount" is 2. Of course, there are now two zval containers, but they are the same one. The xdebug_debug_zval() function does not show this, but you could see this by also displaying the memory pointer. Removing an element from the array is like removing a symbol from a scope. By doing so, the "refcount" of a container that an array element points to is decreased. Again, when the "refcount" reaches zero, the variable container is removed from memory. Again, an example to show this:

Example #7 Removing an element from an array

<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
unset( $a['meaning'], $a['number'] );
xdebug_debug_zval( 'a' );
?>

The above example will output something similar to:

a: (refcount=1, is_ref=0)=array (
   'life' => (refcount=1, is_ref=0)='life'
)

Now, things get interesting if we add the array itself as an element of the array, which we do in the next example, in which we also sneak in a reference operator, since otherwise PHP would create a copy:

Example #8 Adding the array itself as an element of it self

<?php
$a = array( 'one' );
$a[] =& $a;
xdebug_debug_zval( 'a' );
?>

The above example will output something similar to:

a: (refcount=2, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=2, is_ref=1)=...
)

Or graphically

Zvals for an array with a circular reference

You can see that the array variable (a) as well as the second element (1) now point to a variable container that has a "refcount" of 2. The "..." in the display above shows that there is recursion involved, which, of course, in this case means that the "..." points back to the original array.

Just like before, unsetting a variable removes the symbol, and the reference count of the variable container it points to is decreased by one. So, if we unset variable $a after running the above code, the reference count of the variable container that $a and element "1" point to gets decreased by one, from "2" to "1". This can be represented as:

Example #9 Unsetting $a

(refcount=1, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=1, is_ref=1)=...
)

Or graphically

Zvals after removal of array with a circular reference demonstrating the memory leak

Cleanup Problems

Although there is no longer a symbol in any scope pointing to this structure, it cannot be cleaned up because the array element "1" still points to this same array. Because there is no external symbol pointing to it, there is no way for a user to clean up this structure; thus you get a memory leak. Fortunately, PHP will clean up this data structure at the end of the request, but before then, this is taking up valuable space in memory. This situation happens often if you're implementing parsing algorithms or other things where you have a child point back at a "parent" element. The same situation can also happen with objects of course, where it actually is more likely to occur, as objects are always implicitly used by reference.

This might not be a problem if this only happens once or twice, but if there are thousands, or even millions, of these memory losses, this obviously starts being a problem. This is especially problematic in long running scripts, such as daemons where the request basically never ends, or in large sets of unit tests. The latter caused problems while running the unit tests for the Template component of the eZ Components library. In some cases, it would require over 2 GB of memory, which the test server didn't quite have.

Garbage Collection
Collecting Cycles
Garbage Collection


HTTP authentication with PHP

The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version. In an Apache module PHP script, it is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays. Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods are supported. See the header() function for more information.

Note: PHP Version Note
Superglobals, such as $_SERVER, became available in PHP » 4.1.0.

An example script fragment which would force client authentication on a page is as follows:

Example #1 Basic HTTP Authentication example

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

Example #2 Digest HTTP Authentication example

This example shows you how to implement a simple Digest HTTP authentication script. For more information read the » RFC 2617.

<?php
$realm = 'Restricted area';

//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');

if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.
           '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

    die('Text to send if user hits Cancel button');
}

// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
    !isset($users[$data['username']]))
    die('Wrong Credentials!');

// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if ($data['response'] != $valid_response)
    die('Wrong Credentials!');

// ok, valid username & password
echo 'Your are logged in as: ' . $data['username'];

// function to parse the http auth header
function http_digest_parse($txt)
{
    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}
?>

Note: Compatibility Note
Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line. Authentication parameters have to be comma-separated as seen in the digest example above.

Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.

Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.

As of PHP 4.3.0, in order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and safe mode is enabled. Regardless, REMOTE_USER can be used to identify the externally-authenticated user. So, you can use $_SERVER['REMOTE_USER'].

Note: Configuration Note
PHP uses the presence of an AuthType directive to determine whether external authentication is in effect.

Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server.

Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.

Example #3 HTTP Authentication example forcing a new name/password

<?php
function authenticate() {
    header('WWW-Authenticate: Basic realm="Test Authentication System"');
    header('HTTP/1.0 401 Unauthorized');
    echo "You must enter a valid login ID and password to access this resource\n";
    exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) ||
    ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
    authenticate();
} else {
    echo "<p>Welcome: {$_SERVER['PHP_AUTH_USER']}<br />";
    echo "Old: {$_REQUEST['OldAuth']}";
    echo "<form action='{$_SERVER['PHP_SELF']}' METHOD='post'>\n";
    echo "<input type='hidden' name='SeenBefore' value='1' />\n";
    echo "<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}' />\n";
    echo "<input type='submit' value='Re Authenticate' />\n";
    echo "</form></p>\n";
}
?>

This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.

Also note that until PHP 4.3.3, HTTP Authentication did not work using Microsoft's IIS server with the CGI version of PHP due to a limitation of IIS. In order to get it to work in PHP 4.3.3+, you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked.

Another limitation is if you're using the IIS module (ISAPI) and PHP 4, you may not use the PHP_AUTH_* variables but instead, the variable HTTP_AUTHORIZATION is available. For example, consider the following code: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

Note: IIS Note:
For HTTP Authentication to work with IIS, the PHP directive cgi.rfc2616_headers must be set to 0 (the default value).

Note: If safe mode is enabled, the uid of the script is added to the realm part of the WWW-Authenticate header.

Features
Cookies
Features


Persistent Database Connections

Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).

People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.

Why?

This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages.

The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.

The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When a request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be served by a different child process than the first time. When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server.

The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before.

If persistent connections don't have any added functionality, what are they good for?

The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.

Note, however, that this can have some drawbacks if you are using a database with connection limits that are exceeded by persistent child connections. If your database has a limit of 16 simultaneous connections, and in the course of a busy server session, 17 child threads attempt to connect, one will not be able to. If there are bugs in your scripts which do not allow the connections to shut down (such as infinite loops), the database with only 16 connections may be rapidly swamped. Check your database documentation for information on handling abandoned or idle connections.

Warning

There are a couple of additional caveats to keep in mind when using persistent connections. One is that when using table locking on a persistent connection, if the script for whatever reason cannot release the lock, then subsequent scripts using the same connection will block indefinitely and may require that you either restart the httpd server or the database server. Another is that when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does. In either case, you can use register_shutdown_function() to register a simple cleanup function to unlock your tables or roll back your transactions. Better yet, avoid the problem entirely by not using persistent connections in scripts which use table locks or transactions (you can still use them elsewhere).

An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior!

See also fbsql_pconnect(),
ibase_pconnect(), ifx_pconnect(),
ingres_pconnect(),
msql_pconnect(), mssql_pconnect(),
mysql_pconnect(), ociplogon(),
odbc_pconnect(), oci_pconnect(),
pfsockopen(), pg_pconnect(), and
sybase_pconnect().

Connection handling
Safe Mode
Features


Using remote files

As long as allow_url_fopen is enabled in php.ini, you can use HTTP and FTP URLs with most of the functions that take a filename as a parameter. In addition, URLs can be used with the include(), include_once(), require() and require_once() statements (since PHP 5.2.0, allow_url_include must be enabled for these). See List of Supported Protocols/Wrappers for more information about the protocols supported by PHP.

Note: In PHP 4.0.3 and older, in order to use URL wrappers, you were required to configure PHP using the configure option --enable-url-fopen-wrapper.

Note: The Windows versions of PHP earlier than PHP 4.3 did not support remote file accessing for the following functions: include(), include_once(), require(), require_once(), and the imagecreatefromXXX functions in the GD and Image Functions extension.

For example, you can use this to open a file on a remote web server, parse the output for the data you want, and then use that data in a database query, or simply to output it in a style matching the rest of your website.

Example #1 Getting the title of a remote page

<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
    echo "<p>Unable to open remote file.\n";
    exit;
}
while (!feof ($file)) {
    $line = fgets ($file, 1024);
    /* This only works if the title and its tags are on one line */
    if (preg_match ("@\<title\>(.*)\</title\>@i", $line, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?>

You can also write to files on an FTP server (provided that you have connected as a user with the correct access rights). You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail.

To connect as a user other than 'anonymous', you need to specify the username (and possibly password) within the URL, such as 'ftp://user:password@ftp.example.com/path/to/file'. (You can use the same sort of syntax to access files via HTTP when they require Basic authentication.)

Example #2 Storing data on a remote server

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

Note: You might get the idea from the example above that you can use this technique to write to a remote log file. Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To do distributed logging like that, you should take a look at syslog().

PUT method support
Connection handling
Features


Safe Mode

Table of Contents

  • Security and Safe Mode
  • Functions restricted/disabled by safe mode

The PHP safe mode is an attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP level, but since the alternatives at the web server and OS levels aren't very realistic, many people, especially ISP's, use safe mode for now.

Warning

Safe Mode is deprecated in PHP 5.3.0 and is removed in PHP 6.0.0.

Persistent Database Connections
Security and Safe Mode
Features


Functions restricted/disabled by safe mode

This is a still probably incomplete and possibly incorrect listing of the functions limited by safe mode.

Safe mode limited functions
Function | Limitations
dbmopen() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
dbase_open() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
filepro() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
filepro_rowcount() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
filepro_retrieve() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
ifx_* | sql_safe_mode restrictions, (!= safe mode)
ingres_* | sql_safe_mode restrictions, (!= safe mode)
mysql_* | sql_safe_mode restrictions, (!= safe mode)
pg_lo_import() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
posix_mkfifo() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
putenv() | Obeys the safe_mode_protected_env_vars and safe_mode_allowed_env_vars ini-directives. See also the documentation on putenv()
move_uploaded_file() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
chdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
dl() | This function is disabled when PHP is running in safe mode.
backtick operator | This function is disabled when PHP is running in safe mode.
shell_exec() (functional equivalent of backticks) | This function is disabled when PHP is running in safe mode.
exec() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
system() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
passthru() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
popen() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
fopen() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
mkdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
rmdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
rename() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
unlink() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
copy() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (on source and target )
chgrp() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
chown() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
chmod() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits
touch() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
symlink() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (note: only the target is checked)
link() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (note: only the target is checked)
apache_request_headers() | In safe mode, headers beginning with authorization (case-insensitive) will not be returned.
header() | In safe mode, the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).
PHP_AUTH variables | In safe mode, the variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE are not available in $_SERVER. Regardless, you can still use REMOTE_USER for the USER. (note: only affected since PHP 4.3.0)
highlight_file(), show_source() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (note: only affected since PHP 4.2.1)
parse_ini_file() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (note: only affected since PHP 4.2.1)
set_time_limit() | Has no effect when PHP is running in safe mode.
max_execution_time | Has no effect when PHP is running in safe mode.
mail() | In safe mode, the fifth parameter is disabled. (note: only affected since PHP 4.2.3)
session_start() | The owner of a script must be the same as owner of a session.save_path directory if the default files session.save_handler is used.
All filesystem and stream functions. | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (see the safe_mode_include_dir php.ini option.

Security and Safe Mode
Command line usage
Safe Mode


Sessions

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. All information is in the Session reference section.

Cookies
Dealing with XForms
Features


Dealing with XForms

» XForms defines a variation on traditional webforms which allows them to be used on a wider variety of platforms and browsers or even non-traditional media such as PDF documents.

The first key difference in XForms is how the form is sent to the client. » XForms for HTML Authors contains a detailed description of how to create XForms, for the purpose of this tutorial we'll only be looking at a simple example.

Example #1 A simple XForms search form

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

The above form displays a text input box (named q ), and a submit button. When the submit button is clicked, the form will be sent to the page referred to by action.

Here's where it starts to look different from your web application's point of view. In a normal HTML form, the data would be sent as application/x-www-form-urlencoded, in the XForms world however, this information is sent as XML formatted data.

If you're choosing to work with XForms then you probably want that data as XML, in that case, look in $HTTP_RAW_POST_DATA where you'll find the XML document generated by the browser which you can pass into your favorite XSLT engine or document parser.

If you're not interested in formatting and just want your data to be loaded into the traditional $_POST variable, you can instruct the client browser to send it as application/x-www-form-urlencoded by changing the method attribute to urlencoded-post.

Example #2 Using an XForm to populate $_POST

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="urlencoded-post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

Note: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.

Sessions
Handling file uploads
Features


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FILEINFO_NONE (integer)
No special handling.
FILEINFO_SYMLINK (integer)
Follow symlinks.
FILEINFO_MIME_TYPE (integer)
Return the mime type. Available since PHP 5.3.0.
FILEINFO_MIME_ENCODING (integer)
Return the mime encoding of the file. Available since PHP 5.3.0.
FILEINFO_MIME (integer)
Return the mime type and mime encoding as defined by RFC 2045.
FILEINFO_COMPRESS (integer)
Decompress compressed files. Disabled since PHP 5.3.0 due to thread safety issues.
FILEINFO_DEVICES (integer)
Look at the contents of blocks or character special devices.
FILEINFO_CONTINUE (integer)
Return all matches, not just the first.
FILEINFO_PRESERVE_ATIME (integer)
If possible preserve the original access time.
FILEINFO_RAW (integer)
Don't translate unprintable characters to a \ooo octal representation.
Resource Types
Fileinfo Functions
Fileinfo


Installation

This extension is enabled by default as of PHP 5.3.0. Before this time, fileinfo was a PECL extension but is no longer maintained there.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

Before PHP 5.3.0, the magic_open library is needed to build this extension.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

There is one resource used in Fileinfo extension: a magic database descriptor returned by finfo_open().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Fileinfo


Predefined Constants

This extension has no constants defined.

Resource Types
filePro Functions
filePro


Installation

filePro support in PHP is not enabled by default. To enable the bundled read-only filePro support you need to use the--enable-filepro configuration option when compiling PHP.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
filePro


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Filesystem and Streams Configuration Options
Name | Default | Changeable | Changelog
allow_url_fopen | "1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.3.4. PHP_INI_SYSTEM in PHP < 6. Available since PHP 4.0.4.
allow_url_include | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 5. Available since PHP 5.2.0.
user_agent | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
default_socket_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.0.
from | "" | PHP_INI_ALL |
auto_detect_line_endings | "0" | PHP_INI_ALL | Available since PHP 4.3.0.

Here's a short explanation of the configuration directives.

allow_url_fopen boolean

This option enables the URL-aware fopen wrappers that enable accessing URL object like files. Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib may register additional wrappers.

Note: This setting can only be set in php.ini due to security reasons.

Note: This option was introduced immediately after the release of version 4.0.3. For versions up to and including 4.0.3 you can only disable this feature at compile time by using the configuration switch --disable-url-fopen-wrapper .

Warning

On Windows versions prior to PHP 4.3.0, the following functions do not
support remote file accessing: include(),
include_once(), require(),
require_once() and the imagecreatefromXXX
functions in the GD and Image Functions extension.

allow_url_include boolean

This option allows the use of URL-aware fopen wrappers with the following functions: include(), include_once(), require(), require_once().

Note: This setting requires allow_url_fopen to be on.

user_agent string

Define the user agent for PHP to send.

default_socket_timeout integer

Default timeout (in seconds) for socket based streams.

Note: This configuration option was introduced in PHP 4.3.0

from string

Define the anonymous ftp password (your email address).

auto_detect_line_endings boolean

When turned on, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Macintosh line-ending conventions.

This enables PHP to interoperate with Macintosh systems, but defaults to Off, as there is a very small performance penalty when detecting the EOL conventions for the first line, and also because people using carriage-returns as item separators under Unix systems would experience non-backwards-compatible behaviour.

Note: This configuration option was introduced in PHP 4.3.0

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GLOB_BRACE (integer)
GLOB_ONLYDIR (integer)
GLOB_MARK (integer)
GLOB_NOSORT (integer)
GLOB_NOCHECK (integer)
GLOB_NOESCAPE (integer)
GLOB_AVAILABLE_FLAGS (integer)
PATHINFO_DIRNAME (integer)
PATHINFO_BASENAME (integer)
PATHINFO_EXTENSION (integer)
PATHINFO_FILENAME (integer)
Since PHP 5.2.0.
FILE_USE_INCLUDE_PATH (integer)
Search for filename in include_path (since PHP 5).
FILE_NO_DEFAULT_CONTEXT (integer)
FILE_APPEND (integer)
Append content to existing file.
FILE_IGNORE_NEW_LINES (integer)
Strip EOL characters (since PHP 5).
FILE_SKIP_EMPTY_LINES (integer)
Skip empty lines (since PHP 5).
FILE_BINARY (integer)

Binary mode (since PHP 5.2.7).

Note: This constant has no effect prior to PHP 6. It is only available for forward compatibility.

FILE_TEXT (integer)

Text mode (since PHP 5.2.7).

Note: This constant has no effect prior to PHP 6. It is only available for forward compatibility.

INI_SCANNER_NORMAL (integer)
Normal INI scanner mode (since PHP 5.3).
INI_SCANNER_RAW (integer)
Raw INI scanner mode (since PHP 5.3).
FNM_NOESCAPE (integer)
Disable backslash escaping.
FNM_PATHNAME (integer)
Slash in string only matches slash in the given pattern.
FNM_PERIOD (integer)
Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD (integer)
Caseless match. Part of the GNU extension.
Resource Types
Filesystem Functions
Filesystem


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Filesystem


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FRIBIDI_CHARSET_UTF8 (integer)
Unicode
FRIBIDI_CHARSET_8859_6 (integer)
Arabic
FRIBIDI_CHARSET_8859_8 (integer)
Hebrew
FRIBIDI_CHARSET_CP1255 (integer)
Hebrew/Yiddish
FRIBIDI_CHARSET_CP1256 (integer)
Arabic
FRIBIDI_CHARSET_ISIRI_3342 (integer)
Persian
FRIBIDI_CHARSET_CAP_RTL (integer)
Used for test purposes, will treat CAPS as non-English letters
FRIBIDI_RTL (integer)
Right to left
FRIBIDI_LTR (integer)
Left to right
FRIBIDI_AUTO (integer)
Autodetect the base direction
Resource Types
FriBiDi Functions
FriBiDi


Installation

This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/fribidi.

In order to use these functions you must compile PHP with Fribidi support by using the --with-fribidi[=DIR] configure option.

Windows users will enable php_fribidi.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You must download and install the » FriBiDi package.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
FriBiDi


Function Reference

Tip

See also Extension List/Categorization.

  • Affecting PHP's Behaviour
    • APC — Alternative PHP Cache
    • APD — Advanced PHP debugger
    • bcompiler — PHP bytecode Compiler
    • Error Handling — Error Handling and Logging
    • htscanner — htaccess-like support for all SAPIs
    • inclued — Inclusion hierarchy viewer
    • PHP Options/Info — PHP Options and Information
    • Memtrack
    • Object overloading — Object property and method call overloading
    • Output Control — Output Buffering Control
    • runkit
    • scream — Break the silence operator
    • WinCache — Windows Cache for PHP
  • Audio Formats Manipulation
    • ID3 — ID3 Tags
    • KTaglib
    • oggvorbis — OGG/Vorbis
    • OpenAL — OpenAL Audio Bindings
  • Authentication Services
    • KADM5 — Kerberos V
    • Radius
  • Date and Time Related Extensions
    • Calendar
    • Date/Time — Date and Time
  • Command Line Specific Extensions
    • Newt
    • Ncurses — Ncurses Terminal Screen Control
    • Readline — GNU Readline
  • Compression and Archive Extensions
    • Bzip2
    • LZF
    • Phar
    • Rar — Rar Archiving
    • Zip
    • Zlib — Zlib Compression
  • Credit Card Processing
    • MCVE — MCVE (Monetra) Payment
    • SPPLUS — SPPLUS Payment System
  • Cryptography Extensions
    • Crack — Cracklib
    • Hash — HASH Message Digest Framework
    • Mcrypt
    • Mhash
    • OpenSSL
  • Database Extensions
    • Abstraction Layers
    • Vendor Specific Database Extensions
  • File System Related Extensions
    • Direct IO
    • Directories
    • Fileinfo — File Information
    • Filesystem
    • Inotify
    • Mimetype
    • xattr
    • xdiff
  • Human Language and Character Encoding Support
    • Enchant — Enchant spelling library
    • FriBiDi
    • Gettext
    • i18n — Internationalization
    • iconv
    • intl — Internationalization Functions
    • Multibyte String
    • Pspell
    • Recode — GNU Recode
    • Unicode
  • Image Processing and Generation
    • Exif — Exchangeable image information
    • GD — Image Processing and GD
    • ImageMagick — Image Processing (ImageMagick)
    • Gmagick
    • Cairo
  • Mail Related Extensions
    • Cyrus — Cyrus IMAP administration
    • IMAP — IMAP, POP3 and NNTP
    • Mail
    • Mailparse
    • vpopmail
  • Mathematical Extensions
    • BC Math — BCMath Arbitrary Precision Mathematics
    • GMP — GNU Multiple Precision
    • Math — Mathematical Functions
    • Statistics
  • Non-Text MIME Output
    • FDF — Forms Data Format
    • GnuPG — GNU Privacy Guard
    • haru — Haru PDF
    • Ming — Ming (flash)
    • PDF
    • PS — PostScript document creation
    • RPM Reader — RPM Header Reading
    • SWF — Shockwave Flash
  • Process Control Extensions
    • Program execution — System program execution
    • Expect
    • Libevent
    • PCNTL — Process Control
    • POSIX
    • Semaphore — Semaphore, Shared Memory and IPC
    • Shared Memory
  • Other Basic Extensions
    • GeoIP — Geo IP Location
    • JSON — JavaScript Object Notation
    • Misc. — Miscellaneous Functions
    • Parsekit
    • SPL — Standard PHP Library (SPL)
    • SPL Types — SPL Type Handling
    • Streams
    • Tidy
    • Tokenizer
    • URLs
    • Yaml — YAML Data Serialization
  • Other Services
    • cURL — Client URL Library
    • FAM — File Alteration Monitor
    • FTP
    • Gupnp
    • Hyperwave
    • Hyperwave API
    • HTTP
    • Java — PHP / Java Integration
    • LDAP — Lightweight Directory Access Protocol
    • Lotus Notes
    • Memcache
    • Memcached
    • Gearman
    • mqseries
    • Gopher — Net Gopher
    • Network
    • SAM — Simple Asynchronous Messaging
    • SNMP
    • Sockets
    • SSH2 — Secure Shell2
    • Stomp — Stomp Client
    • SVN — Subversion
    • TCP — TCP Wrappers
    • YAZ
    • YP/NIS
  • Search Engine Extensions
    • mnoGoSearch
    • Sphinx — Sphinx Client
    • Swish — Swish Indexing
    • Solr — Apache Solr
  • Server Specific Extensions
    • Apache
    • IIS — IIS Administration
    • NSAPI
  • Session Extensions
    • Msession — Mohawk Software Session Handler Functions
    • Sessions — Session Handling
    • Session PgSQL — PostgreSQL Session Save Handler
  • Text Processing
    • BBCode — Bulletin Board Code
    • PCRE — Regular Expressions (Perl-Compatible)
    • POSIX Regex — Regular Expression (POSIX Extended)
    • Strings
  • Variable and Type Related Extensions
    • Arrays
    • Classes/Objects — Class/Object Information
    • Classkit
    • Ctype — Character type checking
    • Filter — Data Filtering
    • Function Handling
    • Object Aggregation — Object Aggregation/Composition [PHP 4]
    • Reflection
    • Variable handling
  • Web Services
    • OAuth
    • SCA
    • SOAP
    • XML-RPC
  • Windows Only Extensions
    • .NET
    • COM — COM and .Net (Windows)
    • Printer
    • W32api
    • win32ps
    • win32service
  • XML Manipulation
    • DOM — Document Object Model
    • DOM XML (PHP 4)
    • libxml
    • qtdom
    • SDO — Service Data Objects
    • SDO-DAS-Relational — SDO Relational Data Access Service
    • SDO DAS XML — SDO XML Data Access Service
    • SimpleXML
    • WDDX
    • XML Parser
    • XMLReader
    • XMLWriter
    • XSL
    • XSLT (PHP4)
Performance Considerations
Affecting PHP's Behaviour


Absolute value

Math Functions
acos
Math Functions
PHP Manual

abs

(PHP 4, PHP 5)

abs — Absolute value

Description

number abs ( mixed $number )

Returns the absolute value of number .

Parameters

number

The numeric value to process

Return Values

The absolute value of number . If the argument number is of type float, the return type is also float, otherwise it is integer (as float usually has a bigger value range than integer).

Examples

Example #1 abs() example

<?php
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5);   // $abs2 = 5; (integer)
$abs3 = abs(-5);  // $abs3 = 5; (integer)
?>

Math Functions
acos
Math Functions


Arc cosine

abs
acosh
Math Functions
PHP Manual

acos

(PHP 4, PHP 5)

acos — Arc cosine

Description

float acos ( float $arg )

Returns the arc cosine of arg in radians. acos() is the complementary function of cos(), which means that a==cos(acos(a)) for every value of a that is within acos()' range.

Parameters

arg

The argument to process

Return Values

The arc cosine of arg in radians.

See Also

  • cos() - Cosine
  • acosh() - Inverse hyperbolic cosine
  • asin() - Arc sine
  • atan() - Arc tangent

abs
acosh
Math Functions


Inverse hyperbolic cosine

acos
asin
Math Functions
PHP Manual

acosh

(PHP 4 >= 4.1.0, PHP 5)

acosh — Inverse hyperbolic cosine

Description

float acosh ( float $arg )

Returns the inverse hyperbolic cosine of arg , i.e. the value whose hyperbolic cosine is arg .

Parameters

arg

The value to process

Return Values

The inverse hyperbolic cosine of arg

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • cosh() - Hyperbolic cosine
  • acos() - Arc cosine
  • asinh() - Inverse hyperbolic sine
  • atanh() - Inverse hyperbolic tangent

acos
asin
Math Functions


Cache a variable in the data store

APC Functions
apc_cache_info
APC Functions
PHP Manual

apc_add

(PECL apc >= 3.0.13)

apc_add — Cache a variable in the data store

Description

bool apc_add ( string $key , mixed $var [, int $ttl = 0 ] )

Caches a variable in the data store, only if it's not already stored.

Note: Unlike many other mechanisms in PHP, variables stored using apc_add() will persist between requests (until the value is removed from the cache).

Parameters

key

Store the variable using this name. key s are cache-unique, so attempting to use apc_add() to store data with a key that already exists will not overwrite the existing data, and will instead return FALSE. (This is the only difference between apc_add() and apc_store().)

var

The variable to store

ttl

Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A apc_add() example

<?php
$bar = 'BAR';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
$bar = 'NEVER GETS SET';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
?>

The above example will output:

string(3) "BAR"
string(3) "BAR"

See Also

  • apc_store() - Cache a variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache
  • apc_delete() - Removes a stored variable from the cache

APC Functions
apc_cache_info
APC Functions


Retrieves cached information from APC's data store

apc_add
apc_clear_cache
APC Functions
PHP Manual

apc_cache_info

(PECL apc >= 2.0.0)

apc_cache_info — Retrieves cached information from APC's data store

Description

array apc_cache_info ([ string $cache_type [, bool $limited = false ]] )

Retrieves cached information and meta-data from APC's data store.

Return Values

Array of cached data (and meta-data) or FALSE on failure

Note: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.

Parameters

cache_type

If cache_type is "user", information about the user cache will be returned.

If cache_type is "filehits", information about which files have been served from the bytecode cache for the current request will be returned. This feature must be enabled at compile time using --enable-filehits.

If an invalid or no cache_type is specified, information about the system cache (cached files) will be returned.

limited

If limited is TRUE, the return value will exclude the individual list of cache entries. This is useful when trying to optimize calls for statistics gathering.

Changelog

Version | Description
3.0.11 | The limited parameter was introduced.
3.0.16 | The "filehits" option for the cache_type parameter was introduced.

Examples

Example #1 A apc_cache_info() example

<?php
print_r(apc_cache_info());
?>

The above example will output something similar to:

Array
(
    [num_slots] => 2000
    [ttl] => 0
    [num_hits] => 9
    [num_misses] => 3
    [start_time] => 1123958803
    [cache_list] => Array
        (
            [0] => Array
                (
                    [filename] => /path/to/apc_test.php
                    [device] => 29954
                    [inode] => 1130511
                    [type] => file
                    [num_hits] => 1
                    [mtime] => 1123960686
                    [creation_time] => 1123960696
                    [deletion_time] => 0
                    [access_time] => 1123962864
                    [ref_count] => 1
                    [mem_size] => 677
                )
            [1] => Array (...iterates for each cached file)
)

See Also

  • APC configuration directives

apc_add
apc_clear_cache
APC Functions


Clears the APC cache

apc_cache_info
apc_compile_file
APC Functions
PHP Manual

apc_clear_cache

(PECL apc >= 2.0.0)

apc_clear_cache — Clears the APC cache

Description

bool apc_clear_cache ([ string $cache_type ] )

Clears the user/system cache.

Return Values

Returns TRUE on success or FALSE on failure.

Parameters

cache_type

If cache_type is "user", the user cache will be cleared; otherwise, the system cache (cached files) will be cleared.

See Also

  • apc_cache_info() - Retrieves cached information from APC's data store

apc_cache_info
apc_compile_file
APC Functions


Stores a file in the bytecode cache, bypassing all filters.

apc_clear_cache
apc_define_constants
APC Functions
PHP Manual

apc_compile_file

(PECL apc >= 3.0.13)

apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.

Description

bool apc_compile_file ( string $filename )

Stores a file in the bytecode cache, bypassing all filters.

Parameters

filename

Full or relative path to a PHP file that will be compiled and stored in the bytecode cache.

Return Values

Returns TRUE on success or FALSE on failure.

apc_clear_cache
apc_define_constants
APC Functions


Defines a set of constants for retrieval and mass-definition

apc_compile_file
apc_delete
APC Functions
PHP Manual

apc_define_constants

(PECL apc >= 3.0.0)

apc_define_constants — Defines a set of constants for retrieval and mass-definition

Description

bool apc_define_constants ( string $key , array $constants [, bool $case_sensitive = true ] )

define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition. However, this function does not perform as well as anticipated.

For a better-performing solution, try the » hidef extension from PECL.

Note: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the constants parameter, effectively clearing the stored value(s).

Parameters

key

The key serves as the name of the constant set being stored. This key is used to retrieve the stored constants in apc_load_constants().

constants

An associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apc_define_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
echo ONE, TWO, THREE;
?>

The above example will output:

123

See Also

  • apc_load_constants() - Loads a set of constants from the cache
  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • Or the PHP constants reference

apc_compile_file
apc_delete
APC Functions


Removes a stored variable from the cache

apc_define_constants
apc_fetch
APC Functions
PHP Manual

apc_delete

(PECL apc >= 3.0.0)

apc_delete — Removes a stored variable from the cache

Description

bool apc_delete ( string $key )

Removes a stored variable from the cache.

Parameters

key

The key used to store the value (with apc_store()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A apc_delete() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
apc_delete('foo');
// this is obviously useless in this form
?>

See Also

  • apc_store() - Cache a variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache

apc_define_constants
apc_fetch
APC Functions


Fetch a stored variable from the cache

apc_delete
apc_load_constants
APC Functions
PHP Manual

apc_fetch

(PECL apc >= 3.0.0)

apc_fetch — Fetch a stored variable from the cache

Description

mixed apc_fetch ( mixed $key [, bool &$success ] )

Fetchs a stored variable from the cache.

Parameters

key

The key used to store the value (with apc_store()). If an array is passed then each element is fetched and returned.

success

Set to TRUE in success and FALSE in failure.

Return Values

The stored variable or array of variables on success; FALSE on failure

Examples

Example #1 A apc_fetch() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

The above example will output:

string(3) "BAR"

See Also

  • apc_store() - Cache a variable in the data store
  • apc_delete() - Removes a stored variable from the cache

apc_delete
apc_load_constants
APC Functions


Loads a set of constants from the cache

apc_fetch
apc_sma_info
APC Functions
PHP Manual

apc_load_constants

(PECL apc >= 3.0.0)

apc_load_constants — Loads a set of constants from the cache

Description

bool apc_load_constants ( string $key [, bool $case_sensitive = true ] )

Loads a set of constants from the cache.

Parameters

key

The name of the constant set (that was stored with apc_define_constants()) to be retrieved.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apc_load_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>

The above example will output:

123

See Also

  • apc_define_constants() - Defines a set of constants for retrieval and mass-definition
  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • Or the PHP constants reference

apc_fetch
apc_sma_info
APC Functions


Retrieves APC's Shared Memory Allocation information

apc_load_constants
apc_store
APC Functions
PHP Manual

apc_sma_info

(PECL apc >= 2.0.0)

apc_sma_info — Retrieves APC's Shared Memory Allocation information

Description

array apc_sma_info ([ bool $limited = false ] )

Retrieves APC's Shared Memory Allocation information.

Parameters

limited

When set to FALSE (default) apc_sma_info() will return a detailed information about each segment.

Return Values

Array of Shared Memory Allocation data; FALSE on failure.

Examples

Example #1 A apc_sma_info() example

<?php
print_r(apc_sma_info());
?>

The above example will output something similar to:

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)

See Also

  • APC configuration directives

apc_load_constants
apc_store
APC Functions


Cache a variable in the data store

apc_sma_info
APD
APC Functions
PHP Manual

apc_store

(PECL apc >= 3.0.0)

apc_store — Cache a variable in the data store

Description

bool apc_store ( string $key , mixed $var [, int $ttl = 0 ] )

Cache a variable in the data store.

Note: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).

Parameters

key

Store the variable using this name. key s are cache-unique, so storing a second value with the same key will overwrite the original value.

var

The variable to store

ttl

Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A apc_store() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

The above example will output:

string(3) "BAR"

See Also

  • apc_add() - Cache a variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache
  • apc_delete() - Removes a stored variable from the cache

apc_sma_info
APD
APC Functions


Stops the interpreter and waits on a CR from the socket

APD Functions
apd_callstack
APD Functions
PHP Manual

apd_breakpoint

(PECL apd >= 0.2)

apd_breakpoint — Stops the interpreter and waits on a CR from the socket

Description

bool apd_breakpoint ( int $debug_level )

This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Typical session using tcplisten

bash#tcplisten localhost 7777

APD - Advanced PHP Debugger Trace File
---------------------------------------------------------------------------
Process Pid (6118)
Trace Begun at Sun Mar 10 23:13:12 2002
---------------------------------------------------------------------------
(  0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test.
php:5
(  0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes
t.php:5 returned.  Elapsed (0.074824)
(  0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7
              ++ argv[0] $(??) = 9
apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned.  Elapsed (
-2089521468.1073275368)
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:10
>apd_echo($i);
EXEC: apd_echo($i);
0
>apd_echo(serialize(apd_get_active_symbols()));
EXEC:  apd_echo(serialize(apd_get_active_symbols()));
a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:"
COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE
SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:"
MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP
LAY";i:15;s:8:"LOGNAME";i:16;s:6:"
>apd_echo(system('ls /home/mydir'));
........
>apd_continue(0);

APD Functions
apd_callstack
APD Functions


Returns the current call stack as an array

apd_breakpoint
apd_clunk
APD Functions
PHP Manual

apd_callstack

(PECL apd 0.2-0.4)

apd_callstack — Returns the current call stack as an array

Description

array apd_callstack ( void )

Returns the current call stack as an array

Return Values

An array containing the current call stack.

Examples

Example #1 apd_callstack() example

<?php
print_r(apd_callstack());
?>

apd_breakpoint
apd_clunk
APD Functions


Throw a warning and a callstack

apd_callstack
apd_continue
APD Functions
PHP Manual

apd_clunk

(PECL apd 0.2-0.4)

apd_clunk — Throw a warning and a callstack

Description

void apd_clunk ( string $warning [, string $delimiter ] )

Behaves like perl's Carp::cluck. Throw a warning and a callstack.

Parameters

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Return Values

No value is returned.

Examples

Example #1 apd_clunk() example

<?php
apd_clunk("Some Warning", "<br/>");
?>

See Also

  • apd_croak() - Throw an error, a callstack and then exit

apd_callstack
apd_continue
APD Functions


Restarts the interpreter

apd_clunk
apd_croak
APD Functions
PHP Manual

apd_continue

(PECL apd >= 0.2)

apd_continue — Restarts the interpreter

Description

bool apd_continue ( int $debug_level )

Usually sent via the socket to restart the interpreter.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apd_continue() example

<?php
apd_continue(0);
?>

apd_clunk
apd_croak
APD Functions


Throw an error, a callstack and then exit

apd_continue
apd_dump_function_table
APD Functions
PHP Manual

apd_croak

(PECL apd 0.2-0.4)

apd_croak — Throw an error, a callstack and then exit

Description

void apd_croak ( string $warning [, string $delimiter ] )

Behaves like perl's Carp::croak. Throw an error, a callstack and then exit.

Parameters

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Return Values

No value is returned.

Examples

Example #1 apd_croak() example

<?php
apd_croak("Some Warning","<P>");
?>

See Also

  • apd_clunk() - Throw a warning and a callstack

apd_continue
apd_dump_function_table
APD Functions


Outputs the current function table

apd_croak
apd_dump_persistent_resources
APD Functions
PHP Manual

apd_dump_function_table

(Unknown)

apd_dump_function_table — Outputs the current function table

Description

void apd_dump_function_table ( void )

Outputs the current function table.

Return Values

No value is returned.

Examples

Example #1 apd_dump_function_table() example

<?php
apd_dump_function_table();
?>

apd_croak
apd_dump_persistent_resources
APD Functions


Return all persistent resources as an array

apd_dump_function_table
apd_dump_regular_resources
APD Functions
PHP Manual

apd_dump_persistent_resources

(PECL apd 0.2-0.4)

apd_dump_persistent_resources — Return all persistent resources as an array

Description

array apd_dump_persistent_resources ( void )

Return all persistent resources as an array.

Return Values

An array containing the current call stack.

Examples

Example #1 apd_dump_persistent_resources() example

<?php
print_r(apd_dump_persistent_resources());
?>

See Also

  • apd_dump_regular_resources() - Return all current regular resources as an array

apd_dump_function_table
apd_dump_regular_resources
APD Functions


Return all current regular resources as an array

apd_dump_persistent_resources
apd_echo
APD Functions
PHP Manual

apd_dump_regular_resources

(PECL apd 0.2-0.4)

apd_dump_regular_resources — Return all current regular resources as an array

Description

array apd_dump_regular_resources ( void )

Return all current regular resources as an array.

Return Values

An array containing the current regular resources.

Examples

Example #1 apd_dump_regular_resources() example

<?php
print_r(apd_dump_regular_resources());
?>

See Also

  • apd_dump_persistent_resources() - Return all persistent resources as an array

apd_dump_persistent_resources
apd_echo
APD Functions


Echo to the debugging socket

apd_dump_regular_resources
apd_get_active_symbols
APD Functions
PHP Manual

apd_echo

(PECL apd >= 0.2)

apd_echo — Echo to the debugging socket

Description

bool apd_echo ( string $output )

Usually sent via the socket to request information about the running script.

Parameters

output

The debugged variable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apd_echo() example

<?php
apd_echo($i);
?>

apd_dump_regular_resources
apd_get_active_symbols
APD Functions


Get an array of the current variables names in the local scope

apd_echo
apd_set_pprof_trace
APD Functions
PHP Manual

apd_get_active_symbols

(PECL apd 0.2)

apd_get_active_symbols — Get an array of the current variables names in the local scope

Description

array apd_get_active_symbols ( void )

Returns the names of all the variables defined in the active scope, (not their values).

Return Values

A multidimensional array with all the variables.

Examples

Example #1 apd_get_active_symbols() example

<?php
apd_echo(apd_get_active_symbols());
?>

apd_echo
apd_set_pprof_trace
APD Functions


Starts the session debugging

apd_get_active_symbols
apd_set_session_trace_socket
APD Functions
PHP Manual

apd_set_pprof_trace

(PECL apd >= 0.2)

apd_set_pprof_trace — Starts the session debugging

Description

string apd_set_pprof_trace ([ string $dump_directory [, string $fragment = "pprof" ]] )

Starts debugging to pprof_{process_id} in the dump directory.

Parameters

dump_directory

The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

fragment

Return Values

Returns path of the destination file.

Examples

Example #1 apd_set_pprof_trace() example

<?php
apd_set_pprof_trace();
?>

See Also

  • apd_set_session_trace() - Starts the session debugging

apd_get_active_symbols
apd_set_session_trace_socket
APD Functions


Changes or sets the current debugging level

apd_set_session_trace
override_function
APD Functions
PHP Manual

apd_set_session

(PECL apd 0.2-0.4)

apd_set_session — Changes or sets the current debugging level

Description

void apd_set_session ( int $debug_level )

This can be used to increase or decrease debugging in a different area of your application.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

No value is returned.

Examples

Example #1 apd_set_session() example

<?php
apd_set_session(9);
?>

apd_set_session_trace
override_function
APD Functions


Starts the session debugging

apd_set_session_trace_socket
apd_set_session
APD Functions
PHP Manual

apd_set_session_trace

(PECL apd 0.2-0.4)

apd_set_session_trace — Starts the session debugging

Description

void apd_set_session_trace ( int $debug_level [, string $dump_directory ] )

Starts debugging to apd_dump_{process_id} in the dump directory.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

dump_directory

The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

Return Values

No value is returned.

Examples

Example #1 apd_set_session_trace() example

<?php
apd_set_session_trace(99);
?>

apd_set_session_trace_socket
apd_set_session
APD Functions


Starts the remote session debugging

apd_set_pprof_trace
apd_set_session_trace
APD Functions
PHP Manual

apd_set_session_trace_socket

(PECL apd >= 0.2)

apd_set_session_trace_socket — Starts the remote session debugging

Description

bool apd_set_session_trace_socket ( string $tcp_server , int $socket_type , int $port , int $debug_level )

Connects to the specified tcp_server (eg. tcplisten) and sends debugging data to the socket.

Parameters

tcp_server

IP or Unix Domain socket (like a file) of the TCP server.

socket_type

Can be AF_UNIX for file based sockets or APD_AF_INET for standard tcp/ip.

port

You can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apd_set_session_trace_socket() example

<?php
  apd_set_session_trace_socket("127.0.0.1",APD_AF_INET,7112,0);
?>

apd_set_pprof_trace
apd_set_session_trace
APD Functions


Arc sine

acosh
asinh
Math Functions
PHP Manual

asin

(PHP 4, PHP 5)

asin — Arc sine

Description

float asin ( float $arg )

Returns the arc sine of arg in radians. asin() is the complementary function of sin(), which means that a==sin(asin(a)) for every value of a that is within asin()'s range.

Parameters

arg

The argument to process

Return Values

The arc sine of arg in radians

See Also

  • sin() - Sine
  • asinh() - Inverse hyperbolic sine
  • acos() - Arc cosine
  • atan() - Arc tangent

acosh
asinh
Math Functions


Inverse hyperbolic sine

asin
atan2
Math Functions
PHP Manual

asinh

(PHP 4 >= 4.1.0, PHP 5)

asinh — Inverse hyperbolic sine

Description

float asinh ( float $arg )

Returns the inverse hyperbolic sine of arg , i.e. the value whose hyperbolic sine is arg .

Parameters

arg

The argument to process

Return Values

The inverse hyperbolic sine of arg

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • sinh() - Hyperbolic sine
  • asin() - Arc sine
  • acosh() - Inverse hyperbolic cosine
  • atanh() - Inverse hyperbolic tangent

asin
atan2
Math Functions


Checks if assertion is FALSE

assert_options
dl
PHP Options/Info Functions
PHP Manual

assert

(PHP 4, PHP 5)

assert — Checks if assertion is FALSE

Description

bool assert ( mixed $assertion )

assert() will check the given assertion and take appropriate action if its result is FALSE.

If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails. This means that if you pass a boolean condition as assertion this condition will not show up as parameter to the assertion function which you may have defined with the assert_options() function, the condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.

Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.

The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.

assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!

The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)

Parameters

assertion

The assertion.

Return Values

FALSE if the assertion is false, TRUE otherwise.

Examples

Example #1 Handle a failed assertion with a custom handler

<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code)
{
    echo "<hr>Assertion Failed:
        File '$file'<br />
        Line '$line'<br />
        Code '$code'<br /><hr />";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('mysql_query("")');
?>

See Also

  • assert_options() - Set/get the various assert flags

assert_options
dl
PHP Options/Info Functions


Set/get the various assert flags

PHP Options/Info Functions
assert
PHP Options/Info Functions
PHP Manual

assert_options

(PHP 4, PHP 5)

assert_options — Set/get the various assert flags

Description

mixed assert_options ( int $what [, mixed $value ] )

Set the various assert() control options or just query their current settings.

Parameters

what

Assert Options
Option | INI Setting | Default value | Description
ASSERT_ACTIVE | assert.active | 1 | enable assert() evaluation
ASSERT_WARNING | assert.warning | 1 | issue a PHP warning for each failed assertion
ASSERT_BAIL | assert.bail | 0 | terminate execution on failed assertions
ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | disable error_reporting during assertion expression evaluation
ASSERT_CALLBACK | assert.callback | (NULL) | Callback to call on failed assertions

value

An optional new value for the option.

Return Values

Returns the original setting of any option or FALSE on errors.

Examples

Example #1 assert_options() example

<?php
// This is our function to handle
// assert failures
function assert_failure()
{
    echo 'Assert failed';
}

// This is our test function
function test_assert($parameter)
{
    assert(is_bool($parameter));
}

// Set our assert options
assert_options(ASSERT_ACTIVE,   true);
assert_options(ASSERT_BAIL,     true);
assert_options(ASSERT_WARNING,  false);
assert_options(ASSERT_CALLBACK, 'assert_failure');

// Make an assert that would fail
test_assert(1);

// This is never reached due to ASSERT_BAIL
// being true
echo 'Never reached';
?>

See Also

  • assert() - Checks if assertion is FALSE

PHP Options/Info Functions
assert
PHP Options/Info Functions


Arc tangent

atan2
atanh
Math Functions
PHP Manual

atan

(PHP 4, PHP 5)

atan — Arc tangent

Description

float atan ( float $arg )

Returns the arc tangent of arg in radians. atan() is the complementary function of tan(), which means that a==tan(atan(a)) for every value of a that is within atan()'s range.

Parameters

arg

The argument to process

Return Values

The arc tangent of arg in radians.

See Also

  • tan() - Tangent
  • atanh() - Inverse hyperbolic tangent
  • asin() - Arc sine
  • acos() - Arc cosine

atan2
atanh
Math Functions


Arc tangent of two variables

asinh
atan
Math Functions
PHP Manual

atan2

(PHP 4, PHP 5)

atan2 — Arc tangent of two variables

Description

float atan2 ( float $y , float $x )

This function calculates the arc tangent of the two variables x and y . It is similar to calculating the arc tangent of y / x , except that the signs of both arguments are used to determine the quadrant of the result.

The function returns the result in radians, which is between -PI and PI (inclusive).

Parameters

y

Dividend parameter

x

Divisor parameter

Return Values

The arc tangent of y /x in radians.

See Also

  • atan() - Arc tangent

asinh
atan
Math Functions


Inverse hyperbolic tangent

atan
base_convert
Math Functions
PHP Manual

atanh

(PHP 4 >= 4.1.0, PHP 5)

atanh — Inverse hyperbolic tangent

Description

float atanh ( float $arg )

Returns the inverse hyperbolic tangent of arg , i.e. the value whose hyperbolic tangent is arg .

Parameters

arg

The argument to process

Return Values

Inverse hyperbolic tangent of arg

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • tanh() - Hyperbolic tangent
  • atan() - Arc tangent
  • asinh() - Inverse hyperbolic sine
  • acosh() - Inverse hyperbolic cosine

atan
base_convert
Math Functions


Convert a number between arbitrary bases

atanh
bindec
Math Functions
PHP Manual

base_convert

(PHP 4, PHP 5)

base_convert — Convert a number between arbitrary bases

Description

string base_convert ( string $number , int $frombase , int $tobase )

Returns a string containing number represented in base tobase . The base in which number is given is specified in frombase . Both frombase and tobase have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35.

Warning

base_convert() may lose precision on large numbers due to properties related to the internal "double" or "float" type used. Please see the Floating point numbers section in the manual for more specific information and limitations.

Parameters

number

The number to convert

frombase

The base number is in

tobase

The base to convert number to

Return Values

number converted to base tobase

Examples

Example #1 base_convert() example

<?php
$hexadecimal = 'A37334';
echo base_convert($hexadecimal, 16, 2);
?>

The above example will output:

101000110111001100110100

See Also

  • intval() - Get the integer value of a variable

atanh
bindec
Math Functions


Returns filename component of path

Filesystem Functions
chgrp
Filesystem Functions
PHP Manual

basename

(PHP 4, PHP 5)

basename — Returns filename component of path

Description

string basename ( string $path [, string $suffix ] )

Given a string containing a path to a file, this function will return the base name of the file.

Parameters

path

A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

suffix

If the filename ends in suffix this will also be cut off.

Return Values

Returns the base name of the given path .

Changelog

Version | Description
4.1.0 | The suffix parameter was added

Examples

Example #1 basename() example

<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>

See Also

  • dirname() - Returns directory name component of path
  • pathinfo() - Returns information about a file path

Filesystem Functions
chgrp
Filesystem Functions


Add two arbitrary precision numbers

BC Math Functions
bccomp
BC Math Functions
PHP Manual

bcadd

(PHP 4, PHP 5)

bcadd — Add two arbitrary precision numbers

Description

string bcadd ( string $left_operand , string $right_operand [, int $scale ] )

Sums left_operand and right_operand .

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

The sum of the two operands, as a string.

Examples

Example #1 bcadd() example

<?php

$a = '1.234';
$b = '5';

echo bcadd($a, $b);     // 6
echo bcadd($a, $b, 4);  // 6.2340

?>

See Also

  • bcsub() - Subtract one arbitrary precision number from another

BC Math Functions
bccomp
BC Math Functions


Compare two arbitrary precision numbers

bcadd
bcdiv
BC Math Functions
PHP Manual

bccomp

(PHP 4, PHP 5)

bccomp — Compare two arbitrary precision numbers

Description

int bccomp ( string $left_operand , string $right_operand [, int $scale ] )

Compares the left_operand to the right_operand and returns the result as an integer.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparison.

Return Values

Returns 0 if the two operands are equal, 1 if the left_operand is larger than the right_operand , -1 otherwise.

Examples

Example #1 bccomp() example

<?php

echo bccomp('1', '2') . "\n";   // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?>
bcadd
bcdiv
BC Math Functions


Divide two arbitrary precision numbers

bccomp
bcmod
BC Math Functions
PHP Manual

bcdiv

(PHP 4, PHP 5)

bcdiv — Divide two arbitrary precision numbers

Description

string bcdiv ( string $left_operand , string $right_operand [, int $scale ] )

Divides the left_operand by the right_operand .

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result of the division as a string, or NULL if right_operand is 0.

Examples

Example #1 bcdiv() example

<?php

echo bcdiv('105', '6.55957', 3);  // 16.007

?>

See Also

  • bcmul() - Multiply two arbitrary precision number

bccomp
bcmod
BC Math Functions


Get modulus of an arbitrary precision number

bcdiv
bcmul
BC Math Functions
PHP Manual

bcmod

(PHP 4, PHP 5)

bcmod — Get modulus of an arbitrary precision number

Description

string bcmod ( string $left_operand , string $modulus )

Get the modulus of the left_operand using modulus .

Parameters

left_operand

The left operand, as a string.

modulus

The modulus, as a string.

Return Values

Returns the modulus as a string, or NULL if modulus is 0.

Examples

Example #1 bcmod() example

<?php
echo bcmod('4', '2'); // 0
echo bcmod('2', '4'); // 2
?>

See Also

  • bcdiv() - Divide two arbitrary precision numbers

bcdiv
bcmul
BC Math Functions


Multiply two arbitrary precision number

bcmod
bcpow
BC Math Functions
PHP Manual

bcmul

(PHP 4, PHP 5)

bcmul — Multiply two arbitrary precision number

Description

string bcmul ( string $left_operand , string $right_operand [, int $scale ] )

Multiply the left_operand by the right_operand .

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result as a string.

Examples

Example #1 bcmul() example

<?php
echo bcmul('1.34747474747', '35', 3); // 47.161
echo bcmul('2', '4'); // 8
?>

See Also

  • bcdiv() - Divide two arbitrary precision numbers

bcmod
bcpow
BC Math Functions


Reads and creates classes from a bz compressed file

bcompiler_load_exe
bcompiler_parse_class
bcompiler Functions
PHP Manual

bcompiler_load

(PECL bcompiler >= 0.4)

bcompiler_load — Reads and creates classes from a bz compressed file

Description

bool bcompiler_load ( string $filename )

Reads data from a bzcompressed file and creates classes from the bytecodes.

Parameters

filename

The bzcompressed file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_load() example

<?php

bcompiler_load("/tmp/example");

print_r(get_defined_classes());

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Note: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Please note that this function won't execute script body code contained in the bytecode file.

See Also

  • bcompiler_load_exe() - Reads and creates classes from a bcompiler exe file

bcompiler_load_exe
bcompiler_parse_class
bcompiler Functions


Reads and creates classes from a bcompiler exe file

bcompiler Functions
bcompiler_load
bcompiler Functions
PHP Manual

bcompiler_load_exe

(PECL bcompiler >= 0.4)

bcompiler_load_exe — Reads and creates classes from a bcompiler exe file

Description

bool bcompiler_load_exe ( string $filename )

Reads data from a bcompiler exe file and creates classes from the bytecodes.

Parameters

filename

The exe file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_load_exe() example

<?php

bcompiler_load_exe("/tmp/example.exe");
print_r(get_defined_classes());

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_load() - Reads and creates classes from a bz compressed file

bcompiler Functions
bcompiler_load
bcompiler Functions


Reads the bytecodes of a class and calls back to a user function

bcompiler_load
bcompiler_read
bcompiler Functions
PHP Manual

bcompiler_parse_class

(PECL bcompiler >= 0.4)

bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function

Description

bool bcompiler_parse_class ( string $class , string $callback )

Reads the bytecodes of a class and calls back to a user function.

Parameters

class

The class name, as a string.

callback

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_parse_class() example

<?php

function readByteCodes($data) {
    print_r($data);
}

bcompiler_parse_class("DB","readByteCodes");

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Note: This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.

bcompiler_load
bcompiler_read
bcompiler Functions


Reads and creates classes from a filehandle

bcompiler_parse_class
bcompiler_write_class
bcompiler Functions
PHP Manual

bcompiler_read

(PECL bcompiler >= 0.4)

bcompiler_read — Reads and creates classes from a filehandle

Description

bool bcompiler_read ( resource $filehandle )

Reads data from a open file handle and creates classes from the bytecodes.

Parameters

filehandle

A file handle as returned by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_read() example

<?php
$fh = fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Note: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Please note that this function won't execute script body code contained in the bytecode file.

bcompiler_parse_class
bcompiler_write_class
bcompiler Functions


Writes an defined class as bytecodes

bcompiler_read
bcompiler_write_constant
bcompiler Functions
PHP Manual

bcompiler_write_class

(PECL bcompiler >= 0.4)

bcompiler_write_class — Writes an defined class as bytecodes

Description

bool bcompiler_write_class ( resource $filehandle , string $className [, string $extends ] )

Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

className

The class name, as a string.

extends

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_class() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
// you must write DB_common before DB_mysql, as DB_mysql extends DB_common.
bcompiler_write_class($fh,"DB_common");
bcompiler_write_class($fh,"DB_mysql");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Note: This function does not perform dependency checking, so make sure you write the classes in an order that will not result in an undefined class error occurring when you load it.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_read
bcompiler_write_constant
bcompiler Functions


Writes a defined constant as bytecodes

bcompiler_write_class
bcompiler_write_exe_footer
bcompiler Functions
PHP Manual

bcompiler_write_constant

(PECL bcompiler >= 0.5)

bcompiler_write_constant — Writes a defined constant as bytecodes

Description

bool bcompiler_write_constant ( resource $filehandle , string $constantName )

Reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

constantName

The name of the defined constant, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_constant() example

<?php
define("MODULE_MAX", 30);

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_constant($fh,"MODULE_MAX");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_class
bcompiler_write_exe_footer
bcompiler Functions


Writes the start pos, and sig to the end of a exe type file

bcompiler_write_constant
bcompiler_write_file
bcompiler Functions
PHP Manual

bcompiler_write_exe_footer

(PECL bcompiler >= 0.4)

bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file

Description

bool bcompiler_write_exe_footer ( resource $filehandle , int $startpos )

An EXE (or self executable) file consists of 3 parts:

  • The stub (executable code, e.g. a compiled C program) that loads PHP interpreter, bcompiler extension, stored Bytecodes and initiates a call for the specified function (e.g. main) or class method (e.g. main::main)
  • The Bytecodes (uncompressed only for the moment)
  • The bcompiler EXE footer

To obtain a suitable stub you can compile php_embed-based stub phpe.c located in the examples/embed directory on bcompiler's CVS.

Parameters

filehandle

A file handle as returned by fopen().

startpos

The file position at which the Bytecodes start, and can be obtained using ftell().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_exe_footer() example

<?php

/* creating the output file (example.exe) */
$fh = fopen("example.exe", "w");

/* 1) writing a stub (phpe.exe) */
$size = filesize("phpe.exe");
$fr = fopen("phpe.exe", "r");
fwrite($fh, fread($fr, $size), $size);
$startpos = ftell($fh);

/* 2) writing bytecodes */
bcompiler_write_header($fh);
bcompiler_write_class($fh, "myclass");
bcompiler_write_function($fh, "main");
bcompiler_write_footer($fh);

/* 3) writing EXE footer */
bcompiler_write_exe_footer($fh, $startpos);

/* closing the output file */
fclose($fh);
?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_class() - Writes an defined class as bytecodes
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_constant
bcompiler_write_file
bcompiler Functions


Writes a php source file as bytecodes

bcompiler_write_exe_footer
bcompiler_write_footer
bcompiler Functions
PHP Manual

bcompiler_write_file

(PECL bcompiler >= 0.6)

bcompiler_write_file — Writes a php source file as bytecodes

Description

bool bcompiler_write_file ( resource $filehandle , string $filename )

This function complies specified source file into bytecodes, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

filename

The source file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_file() example

<?php
$fh = fopen("example.phb", "w");
bcompiler_write_header($fh);
bcompiler_write_file($fh, "example.php");
bcompiler_write_footer($fh);
fclose($fh);
/* the following should be equivalent:
include "example.php";
   and
include "example.phb";
*/
?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_exe_footer
bcompiler_write_footer
bcompiler Functions


Writes the single character \x00 to indicate End of compiled data

bcompiler_write_file
bcompiler_write_function
bcompiler Functions
PHP Manual

bcompiler_write_footer

(PECL bcompiler >= 0.4)

bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data

Description

bool bcompiler_write_footer ( resource $filehandle )

Writes the single character \x00 to indicate End of compiled data.

Parameters

filehandle

A file handle as returned by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_footer() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_class($fh,"DB_common");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header

bcompiler_write_file
bcompiler_write_function
bcompiler Functions


Writes an defined function as bytecodes

bcompiler_write_footer
bcompiler_write_functions_from_file
bcompiler Functions
PHP Manual

bcompiler_write_function

(PECL bcompiler >= 0.5)

bcompiler_write_function — Writes an defined function as bytecodes

Description

bool bcompiler_write_function ( resource $filehandle , string $functionName )

Reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).

Parameters

filehandle

A file handle as returned by fopen().

functionName

The function name, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_function() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_function($fh,"my_function_a");
bcompiler_write_function($fh,"my_function_b");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_footer
bcompiler_write_functions_from_file
bcompiler Functions


Writes all functions defined in a file as bytecodes

bcompiler_write_function
bcompiler_write_header
bcompiler Functions
PHP Manual

bcompiler_write_functions_from_file

(PECL bcompiler >= 0.5)

bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes

Description

bool bcompiler_write_functions_from_file ( resource $filehandle , string $fileName )

Searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

fileName

The file to be compiled. You must always include or require the file you intend to compile.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_functions_from_file() example

<?php
require('module.php');

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_functions_from_file($fh,'module.php');
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_function
bcompiler_write_header
bcompiler Functions


Writes the bcompiler header

bcompiler_write_functions_from_file
bcompiler_write_included_filename
bcompiler Functions
PHP Manual

bcompiler_write_header

(PECL bcompiler >= 0.3)

bcompiler_write_header — Writes the bcompiler header

Description

bool bcompiler_write_header ( resource $filehandle [, string $write_ver ] )

Writes the header part of a bcompiler file.

Parameters

filehandle

A file handle as returned by fopen().

write_ver

Can be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_header() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_functions_from_file
bcompiler_write_included_filename
bcompiler Functions


Writes an included file as bytecodes

bcompiler_write_header
Error Handling
bcompiler Functions
PHP Manual

bcompiler_write_included_filename

(PECL bcompiler >= 0.5)

bcompiler_write_included_filename — Writes an included file as bytecodes

Description

bool bcompiler_write_included_filename ( resource $filehandle , string $filename )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

bcompiler_write_header
Error Handling
bcompiler Functions


Raise an arbitrary precision number to another

bcmul
bcpowmod
BC Math Functions
PHP Manual

bcpow

(PHP 4, PHP 5)

bcpow — Raise an arbitrary precision number to another

Description

string bcpow ( string $left_operand , string $right_operand [, int $scale ] )

Raise left_operand to the power right_operand .

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result as a string.

Examples

Example #1 bcpow() example

<?php

echo bcpow('4.2', '3', 2); // 74.08

?>

See Also

  • bcpowmod() - Raise an arbitrary precision number to another, reduced by a specified modulus
  • bcsqrt() - Get the square root of an arbitrary precision number

bcmul
bcpowmod
BC Math Functions


Raise an arbitrary precision number to another, reduced by a specified modulus

bcpow
bcscale
BC Math Functions
PHP Manual

bcpowmod

(PHP 5)

bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus

Description

string bcpowmod ( string $left_operand , string $right_operand , string $modulus [, int $scale ] )

Use the fast-exponentiation method to raise left_operand to the power right_operand with respect to the modulus modulus .

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

modulus

The modulus, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result as a string, or NULL if modulus is 0.

Notes

Note: Because this method uses the modulus operation, non-natural numbers may give unexpected results. A natural number is any positive non-zero integer.

Examples

The following two statements are functionally identical. The bcpowmod() version however, executes in less time and can accept larger parameters.

<?php
$a = bcpowmod($x, $y, $mod);

$b = bcmod(bcpow($x, $y), $mod);

// $a and $b are equal to each other.

?>

See Also

  • bcpow() - Raise an arbitrary precision number to another
  • bcmod() - Get modulus of an arbitrary precision number

bcpow
bcscale
BC Math Functions


Set default scale parameter for all bc math functions

bcpowmod
bcsqrt
BC Math Functions
PHP Manual

bcscale

(PHP 4, PHP 5)

bcscale — Set default scale parameter for all bc math functions

Description

bool bcscale ( int $scale )

Sets the default scale parameter for all subsequent bc math functions that do not explicitly specify a scale parameter.

Parameters

scale

The scale factor.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcscale() example

<?php

// default scale : 3
bcscale(3);
echo bcdiv('105', '6.55957'); // 16.007

// this is the same without bcscale()
echo bcdiv('105', '6.55957', 3); // 16.007

?>

bcpowmod
bcsqrt
BC Math Functions


Get the square root of an arbitrary precision number

bcscale
bcsub
BC Math Functions
PHP Manual

bcsqrt

(PHP 4, PHP 5)

bcsqrt — Get the square root of an arbitrary precision number

Description

string bcsqrt ( string $operand [, int $scale ] )

Return the square root of the operand .

Parameters

operand

The operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the square root as a string, or NULL if operand is negative.

Examples

Example #1 bcsqrt() example

<?php

echo bcsqrt('2', 3); // 1.414

?>

See Also

  • bcpow() - Raise an arbitrary precision number to another

bcscale
bcsub
BC Math Functions


Subtract one arbitrary precision number from another

bcsqrt
GMP
BC Math Functions
PHP Manual

bcsub

(PHP 4, PHP 5)

bcsub — Subtract one arbitrary precision number from another

Description

string bcsub ( string $left_operand , string $right_operand [, int $scale ] )

Subtracts the right_operand from the left_operand .

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

The result of the subtraction, as a string.

Examples

Example #1 bcsub() example

<?php

$a = '1.234';
$b = '5';

echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?>

See Also

  • bcadd() - Add two arbitrary precision numbers

bcsqrt
GMP
BC Math Functions


Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Gettext Functions
bindtextdomain
Gettext Functions
PHP Manual

bind_textdomain_codeset

(PHP 4 >= 4.2.0, PHP 5)

bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Description

string bind_textdomain_codeset ( string $domain , string $codeset )

With bind_textdomain_codeset(), you can set in which encoding will be messages from domain returned by gettext() and similar functions.

Parameters

domain

The domain

codeset

The code set

Return Values

A string on success.

Gettext Functions
bindtextdomain
Gettext Functions


Binary to decimal

base_convert
ceil
Math Functions
PHP Manual

bindec

(PHP 4, PHP 5)

bindec — Binary to decimal

Description

number bindec ( string $binary_string )

Returns the decimal equivalent of the binary number represented by the binary_string argument.

bindec() converts a binary number to an integer or, if needed for size reasons, float.

bindec() interprets all binary_string values as unsigned integers. This is because bindec() sees the most significant bit as another order of magnitude rather than as the sign bit.

Parameters

binary_string

The binary string to convert

Warning

The parameter must be a string. Using other data types will produce unexpected results.

Return Values

The decimal value of binary_string

Changelog

Version | Description
Since 4.1.0 | The function can now convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

Examples

Example #1 bindec() example

<?php
echo bindec('110011') . "\n";
echo bindec('000110011') . "\n";

echo bindec('111');
?>

The above example will output:

51
51
7

Example #2 bindec() interprets input as unsigned integers

<?php
/*
 * The lesson from this example is in the output
 * rather than the PHP code itself.
 */

$magnitude_lower = pow(2, (PHP_INT_SIZE * 8) - 2);
p($magnitude_lower - 1);
p($magnitude_lower, 'See the rollover?  Watch it next time around...');

p(PHP_INT_MAX, 'PHP_INT_MAX');
p(~PHP_INT_MAX, 'interpreted to be one more than PHP_INT_MAX');

if (PHP_INT_SIZE == 4) {
    $note = 'interpreted to be the largest unsigned integer';
} else {
    $note = 'interpreted to be the largest unsigned integer
              (18446744073709551615) but skewed by float precision';
}
p(-1, $note);

function p($input, $note = '') {
    echo "input:        $input\n";

    $format = '%0' . (PHP_INT_SIZE * 8) . 'b';
    $bin = sprintf($format, $input);
    echo "binary:       $bin\n";

    ini_set('precision', 20);  // For readability on 64 bit boxes.
    $dec = bindec($bin);
    echo 'bindec():     ' . $dec . "\n";

    if ($note) {
        echo "NOTE:         $note\n";
    }

    echo "\n";
}
?>

Output of the above example on 32 bit machines:

input:        1073741823
binary:       00111111111111111111111111111111
bindec():     1073741823

input:        1073741824
binary:       01000000000000000000000000000000
bindec():     1073741824
NOTE:         See the rollover?  Watch it next time around...

input:        2147483647
binary:       01111111111111111111111111111111
bindec():     2147483647
NOTE:         PHP_INT_MAX

input:        -2147483648
binary:       10000000000000000000000000000000
bindec():     2147483648
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       11111111111111111111111111111111
bindec():     4294967295
NOTE:         interpreted to be the largest unsigned integer

Output of the above example on 64 bit machines:

input:        4611686018427387903
binary:       0011111111111111111111111111111111111111111111111111111111111111
bindec():     4611686018427387903

input:        4611686018427387904
binary:       0100000000000000000000000000000000000000000000000000000000000000
bindec():     4611686018427387904
NOTE:         See the rollover?  Watch it next time around...

input:        9223372036854775807
binary:       0111111111111111111111111111111111111111111111111111111111111111
bindec():     9223372036854775807
NOTE:         PHP_INT_MAX

input:        -9223372036854775808
binary:       1000000000000000000000000000000000000000000000000000000000000000
bindec():     9223372036854775808
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       1111111111111111111111111111111111111111111111111111111111111111
bindec():     18446744073709551616
NOTE:         interpreted to be the largest unsigned integer
              (18446744073709551615) but skewed by float precision

See Also

  • decbin() - Decimal to binary
  • octdec() - Octal to decimal
  • hexdec() - Hexadecimal to decimal
  • base_convert() - Convert a number between arbitrary bases

base_convert
ceil
Math Functions


Sets the path for a domain

bind_textdomain_codeset
dcgettext
Gettext Functions
PHP Manual

bindtextdomain

(PHP 4, PHP 5)

bindtextdomain — Sets the path for a domain

Description

string bindtextdomain ( string $domain , string $directory )

The bindtextdomain() function sets the path for a domain.

Parameters

domain

The domain

directory

The directory path

Return Values

The full pathname for the domain currently being set.

Examples

Example #1 bindtextdomain() example

<?php

$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale');

?>

The above example will output:

/usr/share/myapp/locale

bind_textdomain_codeset
dcgettext
Gettext Functions


Deserializes a BSON object into a PHP array

Mongo Functions
bson_encode
Mongo Functions
PHP Manual

bson_decode

(PECL mongo >=1.0.1)

bson_decode — Deserializes a BSON object into a PHP array

Description

array bson_decode ( string $bson )

Parameters

bson

The BSON to be deserialized.

Return Values

Returns the deserialized BSON object.

Mongo Functions
bson_encode
Mongo Functions


Serializes a PHP variable into a BSON string

bson_decode
Exceptions
Mongo Functions
PHP Manual

bson_encode

(PECL mongo >=1.0.1)

bson_encode — Serializes a PHP variable into a BSON string

Description

string bson_encode ( mixed $anything )

Parameters

anything

The variable to be serialized.

Return Values

Returns the serialized string.

bson_decode
Exceptions
Mongo Functions


Close a bzip2 file

Bzip2 Functions
bzcompress
Bzip2 Functions
PHP Manual

bzclose

(PHP 4 >= 4.0.4, PHP 5)

bzclose — Close a bzip2 file

Description

int bzclose ( resource $bz )

Closes the given bzip2 file pointer.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • bzopen() - Opens a bzip2 compressed file

Bzip2 Functions
bzcompress
Bzip2 Functions


Compress a string into bzip2 encoded data

bzclose
bzdecompress
Bzip2 Functions
PHP Manual

bzcompress

(PHP 4 >= 4.0.4, PHP 5)

bzcompress — Compress a string into bzip2 encoded data

Description

mixed bzcompress ( string $source [, int $blocksize = 4 [, int $workfactor = 0 ]] )

bzcompress() compresses the given string and returns it as bzip2 encoded data.

Parameters

source

The string to compress.

blocksize

Specifies the blocksize used during compression and should be a number from 1 to 9 with 9 giving the best compression, but using more resources to do so.

workfactor

Controls how the compression phase behaves when presented with worst case, highly repetitive, input data. The value can be between 0 and 250 with 0 being a special case.

Regardless of the workfactor , the generated output is the same.

Return Values

The compressed string or number of error in case of error.

Examples

Example #1 Compressing data

<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>

See Also

  • bzdecompress() - Decompresses bzip2 encoded data

bzclose
bzdecompress
Bzip2 Functions


Decompresses bzip2 encoded data

bzcompress
bzerrno
Bzip2 Functions
PHP Manual

bzdecompress

(PHP 4 >= 4.0.4, PHP 5)

bzdecompress — Decompresses bzip2 encoded data

Description

mixed bzdecompress ( string $source [, int $small = 0 ] )

bzdecompress() decompresses the given string containing bzip2 encoded data.

Parameters

source

The string to decompress.

small

If TRUE, an alternative decompression algorithm will be used which uses less memory (the maximum memory requirement drops to around 2300K) but works at roughly half the speed.

See the » bzip2 documentation for more information about this feature.

Return Values

The decompressed string or number of error in case of error.

Examples

Example #1 Decompressing a String

<?php
$start_str = "This is not an honest face?";
$bzstr = bzcompress($start_str);

echo "Compressed String: ";
echo $bzstr;
echo "\n<br />\n";

$str = bzdecompress($bzstr);
echo "Decompressed String: ";
echo $str;
echo "\n<br />\n";
?>

See Also

  • bzcompress() - Compress a string into bzip2 encoded data

bzcompress
bzerrno
Bzip2 Functions


Returns a bzip2 error number

bzdecompress
bzerror
Bzip2 Functions
PHP Manual

bzerrno

(PHP 4 >= 4.0.4, PHP 5)

bzerrno — Returns a bzip2 error number

Description

int bzerrno ( resource $bz )

Returns the error number of any bzip2 error returned by the given file pointer.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns the error number as an integer.

See Also

  • bzerror() - Returns the bzip2 error number and error string in an array
  • bzerrstr() - Returns a bzip2 error string

bzdecompress
bzerror
Bzip2 Functions


Returns the bzip2 error number and error string in an array

bzerrno
bzerrstr
Bzip2 Functions
PHP Manual

bzerror

(PHP 4 >= 4.0.4, PHP 5)

bzerror — Returns the bzip2 error number and error string in an array

Description

array bzerror ( resource $bz )

Returns the error number and error string of any bzip2 error returned by the given file pointer.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns an associative array, with the error code in the errno entry, and the error message in the errstr entry.

Examples

Example #1 bzerror() example

<?php
$error = bzerror($bz);

echo $error["errno"];
echo $error["errstr"];
?>

See Also

  • bzerrno() - Returns a bzip2 error number
  • bzerrstr() - Returns a bzip2 error string

bzerrno
bzerrstr
Bzip2 Functions


Returns a bzip2 error string

bzerror
bzflush
Bzip2 Functions
PHP Manual

bzerrstr

(PHP 4 >= 4.0.4, PHP 5)

bzerrstr — Returns a bzip2 error string

Description

string bzerrstr ( resource $bz )

Gets the error string of any bzip2 error returned by the given file pointer.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns a string containing the error message.

See Also

  • bzerrno() - Returns a bzip2 error number
  • bzerror() - Returns the bzip2 error number and error string in an array

bzerror
bzflush
Bzip2 Functions


Force a write of all buffered data

bzerrstr
bzopen
Bzip2 Functions
PHP Manual

bzflush

(PHP 4 >= 4.0.4, PHP 5)

bzflush — Force a write of all buffered data

Description

int bzflush ( resource $bz )

Forces a write of all buffered bzip2 data for the file pointer bz .

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • bzread() - Binary safe bzip2 file read
  • bzwrite() - Binary safe bzip2 file write

bzerrstr
bzopen
Bzip2 Functions


Opens a bzip2 compressed file

bzflush
bzread
Bzip2 Functions
PHP Manual

bzopen

(PHP 4 >= 4.0.4, PHP 5)

bzopen — Opens a bzip2 compressed file

Description

resource bzopen ( string $filename , string $mode )

bzopen() opens a bzip2 (.bz2) file for reading or writing.

Parameters

filename

The name of the file to open.

mode

Similar to the fopen() function, only 'r' (read) and 'w' (write) are supported. Everything else will cause bzopen to return FALSE.

Return Values

If the open fails, bzopen() returns FALSE, otherwise it returns a pointer to the newly opened file.

Examples

Example #1 bzopen() example

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file for reading");

bzclose($bz);

?>

See Also

  • bzclose() - Close a bzip2 file

bzflush
bzread
Bzip2 Functions


Binary safe bzip2 file read

bzopen
bzwrite
Bzip2 Functions
PHP Manual

bzread

(PHP 4 >= 4.0.4, PHP 5)

bzread — Binary safe bzip2 file read

Description

string bzread ( resource $bz [, int $length = 1024 ] )

bzread() reads from the given bzip2 file pointer.

Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

length

If not specified, bzread() will read 1024 (uncompressed) bytes at a time.

Return Values

Returns the uncompressed data, or FALSE on error.

Examples

Example #1 bzread() example

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file");

$decompressed_file = '';
while (!feof($bz)) {
  $decompressed_file .= bzread($bz, 4096);
}
bzclose($bz);

echo "The contents of $file are: <br />\n";
echo $decompressed_file;

?>

See Also

  • bzwrite() - Binary safe bzip2 file write
  • feof() - Tests for end-of-file on a file pointer
  • bzopen() - Opens a bzip2 compressed file

bzopen
bzwrite
Bzip2 Functions


Binary safe bzip2 file write

bzread
LZF
Bzip2 Functions
PHP Manual

bzwrite

(PHP 4 >= 4.0.4, PHP 5)

bzwrite — Binary safe bzip2 file write

Description

int bzwrite ( resource $bz , string $data [, int $length ] )

bzwrite() writes a string into the given bzip2 file stream.

Parameters

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

data

The written data.

length

If supplied, writing will stop after length (uncompressed) bytes have been written or the end of data is reached, whichever comes first.

Return Values

Returns the number of bytes written, or FALSE on error.

Examples

Example #1 bzwrite() example

<?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

See Also

  • bzread() - Binary safe bzip2 file read
  • bzopen() - Opens a bzip2 compressed file

bzread
LZF
Bzip2 Functions


Cairo Functions
cairo_font_face_get_type
Cairo Functions
PHP Manual

cairo_create

(PECL cairo >= 0.1.0)

cairo_create — Description

Description

Cairo cairo_create ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

Cairo Functions
cairo_font_face_get_type
Cairo Functions


cairo_create
cairo_font_face_status
Cairo Functions
PHP Manual

cairo_font_face_get_type

(PECL cairo >= 0.1.0)

cairo_font_face_get_type — Description

Description

int cairo_font_face_get_type ( CairoFontFace $fontface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fontface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_face_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_create
cairo_font_face_status
Cairo Functions


cairo_font_face_get_type
cairo_font_options_create
Cairo Functions
PHP Manual

cairo_font_face_status

(PECL cairo >= 0.1.0)

cairo_font_face_status — Description

Description

int cairo_font_face_status ( CairoFontFace $fontface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fontface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_face_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_face_get_type
cairo_font_options_create
Cairo Functions


cairo_font_face_status
cairo_font_options_equal
Cairo Functions
PHP Manual

cairo_font_options_create

(PECL cairo >= 0.1.0)

cairo_font_options_create — Description

Description

CairoFontOptions cairo_font_options_create ( void )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_face_status
cairo_font_options_equal
Cairo Functions


cairo_font_options_create
cairo_font_options_get_antialias
Cairo Functions
PHP Manual

cairo_font_options_equal

(PECL cairo >= 0.1.0)

cairo_font_options_equal — Description

Description

bool cairo_font_options_equal ( CairoFontOptions $options , CairoFontOptions $other )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

other

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_equal() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_create
cairo_font_options_get_antialias
Cairo Functions


cairo_font_options_equal
cairo_font_options_get_hint_metrics
Cairo Functions
PHP Manual

cairo_font_options_get_antialias

(PECL cairo >= 0.1.0)

cairo_font_options_get_antialias — Description

Description

int cairo_font_options_get_antialias ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_antialias() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_equal
cairo_font_options_get_hint_metrics
Cairo Functions


cairo_font_options_get_antialias
cairo_font_options_get_hint_style
Cairo Functions
PHP Manual

cairo_font_options_get_hint_metrics

(PECL cairo >= 0.1.0)

cairo_font_options_get_hint_metrics — Description

Description

int cairo_font_options_get_hint_metrics ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_hint_metrics() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_get_antialias
cairo_font_options_get_hint_style
Cairo Functions


cairo_font_options_get_hint_metrics
cairo_font_options_get_subpixel_order
Cairo Functions
PHP Manual

cairo_font_options_get_hint_style

(PECL cairo >= 0.1.0)

cairo_font_options_get_hint_style — Description

Description

int cairo_font_options_get_hint_style ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_hint_style() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_get_hint_metrics
cairo_font_options_get_subpixel_order
Cairo Functions


cairo_font_options_get_hint_style
cairo_font_options_hash
Cairo Functions
PHP Manual

cairo_font_options_get_subpixel_order

(PECL cairo >= 0.1.0)

cairo_font_options_get_subpixel_order — Description

Description

int cairo_font_options_get_subpixel_order ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_subpixel_order() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_get_hint_style
cairo_font_options_hash
Cairo Functions


cairo_font_options_get_subpixel_order
cairo_font_options_merge
Cairo Functions
PHP Manual

cairo_font_options_hash

(PECL cairo >= 0.1.0)

cairo_font_options_hash — Description

Description

int cairo_font_options_hash ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_hash() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_get_subpixel_order
cairo_font_options_merge
Cairo Functions


cairo_font_options_hash
cairo_font_options_set_antialias
Cairo Functions
PHP Manual

cairo_font_options_merge

(PECL cairo >= 0.1.0)

cairo_font_options_merge — Description

Description

void cairo_font_options_merge ( CairoFontOptions $options , CairoFontOptions $other )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

other

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_merge() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_hash
cairo_font_options_set_antialias
Cairo Functions


cairo_font_options_merge
cairo_font_options_set_hint_metrics
Cairo Functions
PHP Manual

cairo_font_options_set_antialias

(PECL cairo >= 0.1.0)

cairo_font_options_set_antialias — Description

Description

void cairo_font_options_set_antialias ( CairoFontOptions $options , string $antialias )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

antialias

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_antialias() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_merge
cairo_font_options_set_hint_metrics
Cairo Functions


cairo_font_options_set_antialias
cairo_font_options_set_hint_style
Cairo Functions
PHP Manual

cairo_font_options_set_hint_metrics

(PECL cairo >= 0.1.0)

cairo_font_options_set_hint_metrics — Description

Description

void cairo_font_options_set_hint_metrics ( CairoFontOptions $options , string $hint_metrics )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

hint_metrics

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_hint_metrics() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_set_antialias
cairo_font_options_set_hint_style
Cairo Functions


cairo_font_options_set_hint_metrics
cairo_font_options_set_subpixel_order
Cairo Functions
PHP Manual

cairo_font_options_set_hint_style

(PECL cairo >= 0.1.0)

cairo_font_options_set_hint_style — Description

Description

void cairo_font_options_set_hint_style ( CairoFontOptions $options , string $hint_style )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

hint_style

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_hint_style() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_set_hint_metrics
cairo_font_options_set_subpixel_order
Cairo Functions


cairo_font_options_set_hint_style
cairo_font_options_status
Cairo Functions
PHP Manual

cairo_font_options_set_subpixel_order

(PECL cairo >= 0.1.0)

cairo_font_options_set_subpixel_order — Description

Description

void cairo_font_options_set_subpixel_order ( CairoFontOptions $options , string $subpixel_order )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

subpixel_order

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_subpixel_order() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_set_hint_style
cairo_font_options_status
Cairo Functions


cairo_font_options_set_subpixel_order
cairo_format_stride_for_width
Cairo Functions
PHP Manual

cairo_font_options_status

(PECL cairo >= 0.1.0)

cairo_font_options_status — Description

Description

int cairo_font_options_status ( CairoFontOptions $options )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_set_subpixel_order
cairo_format_stride_for_width
Cairo Functions


cairo_font_options_status
cairo_image_surface_create_for_data
Cairo Functions
PHP Manual

cairo_format_stride_for_width

(PECL cairo >= 0.1.0)

cairo_format_stride_for_width — Description

Description

int cairo_format_stride_for_width ( int $format , int $width )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

format

Description...

width

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_format_stride_for_width() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_font_options_status
cairo_image_surface_create_for_data
Cairo Functions


cairo_image_surface_create_from_png
cairo_image_surface_get_data
Cairo Functions
PHP Manual

cairo_image_surface_create

(PECL cairo >= 0.1.0)

cairo_image_surface_create — Description

Description

CairoImageSurface cairo_image_surface_create ( int $format , int $width , int $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

format

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_image_surface_create_from_png
cairo_image_surface_get_data
Cairo Functions


cairo_format_stride_for_width
cairo_image_surface_create_from_png
Cairo Functions
PHP Manual

cairo_image_surface_create_for_data

(PECL cairo >= 0.1.0)

cairo_image_surface_create_for_data — Description

Description

CairoImageSurface cairo_image_surface_create_for_data ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

Description...

format

Description...

width

Description...

height

Description...

stride

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_create_for_data() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_format_stride_for_width
cairo_image_surface_create_from_png
Cairo Functions


cairo_image_surface_create_for_data
cairo_image_surface_create
Cairo Functions
PHP Manual

cairo_image_surface_create_from_png

(PECL cairo >= 0.1.0)

cairo_image_surface_create_from_png — Description

Description

CairoImageSurface cairo_image_surface_create_from_png ( string $file )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_create_from_png() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_image_surface_create_for_data
cairo_image_surface_create
Cairo Functions


cairo_image_surface_create
cairo_image_surface_get_format
Cairo Functions
PHP Manual

cairo_image_surface_get_data

(PECL cairo >= 0.1.0)

cairo_image_surface_get_data — Description

Description

string cairo_image_surface_get_data ( CairoImageSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_data() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_image_surface_create
cairo_image_surface_get_format
Cairo Functions


cairo_image_surface_get_data
cairo_image_surface_get_height
Cairo Functions
PHP Manual

cairo_image_surface_get_format

(PECL cairo >= 0.1.0)

cairo_image_surface_get_format — Description

Description

int cairo_image_surface_get_format ( CairoImageSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_format() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_image_surface_get_data
cairo_image_surface_get_height
Cairo Functions


cairo_image_surface_get_format
cairo_image_surface_get_stride
Cairo Functions
PHP Manual

cairo_image_surface_get_height

(PECL cairo >= 0.1.0)

cairo_image_surface_get_height — Description

Description

int cairo_image_surface_get_height ( CairoImageSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_height() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_image_surface_get_format
cairo_image_surface_get_stride
Cairo Functions


cairo_image_surface_get_height
cairo_image_surface_get_width
Cairo Functions
PHP Manual

cairo_image_surface_get_stride

(PECL cairo >= 0.1.0)

cairo_image_surface_get_stride — Description

Description

int cairo_image_surface_get_stride ( CairoImageSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_stride() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_image_surface_get_height
cairo_image_surface_get_width
Cairo Functions


cairo_image_surface_get_stride
cairo_matrix_create_scale
Cairo Functions
PHP Manual

cairo_image_surface_get_width

(PECL cairo >= 0.1.0)

cairo_image_surface_get_width — Description

Description

int cairo_image_surface_get_width ( CairoImageSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_width() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_image_surface_get_stride
cairo_matrix_create_scale
Cairo Functions


Alias of CairoMatrix::initScale

cairo_image_surface_get_width
cairo_matrix_create_translate
Cairo Functions
PHP Manual

cairo_matrix_create_scale

(PECL cairo >= 0.1.0)

cairo_matrix_create_scale — Alias of CairoMatrix::initScale

Description

This function is an alias of: CairoMatrix::initScale.

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

cairo_image_surface_get_width
cairo_matrix_create_translate
Cairo Functions


Alias of CairoMatrix::initTranslate

cairo_matrix_create_scale
cairo_matrix_invert
Cairo Functions
PHP Manual

cairo_matrix_create_translate

(PECL cairo >= 0.1.0)

cairo_matrix_create_translate — Alias of CairoMatrix::initTranslate

Description

This function is an alias of: CairoMatrix::initTranslate.

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

cairo_matrix_create_scale
cairo_matrix_invert
Cairo Functions


cairo_matrix_create_translate
cairo_matrix_multiply
Cairo Functions
PHP Manual

cairo_matrix_invert

(PECL cairo >= 0.1.0)

cairo_matrix_invert — Description

Description

void cairo_matrix_invert ( CairoMatrix $matrix )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_invert() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_matrix_create_translate
cairo_matrix_multiply
Cairo Functions


cairo_matrix_invert
cairo_matrix_rotate
Cairo Functions
PHP Manual

cairo_matrix_multiply

(PECL cairo >= 0.1.0)

cairo_matrix_multiply — Description

Description

CairoMatrix cairo_matrix_multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix1

Description...

matrix2

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_multiply() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_matrix_invert
cairo_matrix_rotate
Cairo Functions


cairo_matrix_multiply
cairo_matrix_transform_distance
Cairo Functions
PHP Manual

cairo_matrix_rotate

(PECL cairo >= 0.1.0)

cairo_matrix_rotate — Description

Description

void cairo_matrix_rotate ( CairoMatrix $matrix , string $radians )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

radians

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_rotate() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_matrix_multiply
cairo_matrix_transform_distance
Cairo Functions


cairo_matrix_rotate
cairo_matrix_transform_point
Cairo Functions
PHP Manual

cairo_matrix_transform_distance

(PECL cairo >= 0.1.0)

cairo_matrix_transform_distance — Description

Description

array cairo_matrix_transform_distance ( CairoMatrix $matrix , string $dx , string $dy )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

dx

Description...

dy

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_transform_distance() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_matrix_rotate
cairo_matrix_transform_point
Cairo Functions


cairo_matrix_transform_distance
cairo_matrix_translate
Cairo Functions
PHP Manual

cairo_matrix_transform_point

(PECL cairo >= 0.1.0)

cairo_matrix_transform_point — Description

Description

array cairo_matrix_transform_point ( CairoMatrix $matrix , string $dx , string $dy )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

dx

Description...

dy

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_transform_point() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_matrix_transform_distance
cairo_matrix_translate
Cairo Functions


cairo_matrix_transform_point
cairo_pattern_add_color_stop_rgb
Cairo Functions
PHP Manual

cairo_matrix_translate

(PECL cairo >= 0.1.0)

cairo_matrix_translate — Description

Description

void cairo_matrix_translate ( CairoMatrix $matrix , string $tx , string $ty )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

tx

Description...

ty

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_translate() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_matrix_transform_point
cairo_pattern_add_color_stop_rgb
Cairo Functions


cairo_matrix_translate
cairo_pattern_add_color_stop_rgba
Cairo Functions
PHP Manual

cairo_pattern_add_color_stop_rgb

(PECL cairo >= 0.1.0)

cairo_pattern_add_color_stop_rgb — Description

Description

void cairo_pattern_add_color_stop_rgb ( CairoGradientPattern $pattern , string $offset , string $red , string $green , string $blue )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

offset

Description...

red

Description...

green

Description...

blue

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_add_color_stop_rgb() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_matrix_translate
cairo_pattern_add_color_stop_rgba
Cairo Functions


cairo_pattern_add_color_stop_rgb
cairo_pattern_create_for_surface
Cairo Functions
PHP Manual

cairo_pattern_add_color_stop_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_add_color_stop_rgba — Description

Description

void cairo_pattern_add_color_stop_rgba ( CairoGradientPattern $pattern , string $offset , string $red , string $green , string $blue , string $alpha )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

offset

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_add_color_stop_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_add_color_stop_rgb
cairo_pattern_create_for_surface
Cairo Functions


cairo_pattern_add_color_stop_rgba
cairo_pattern_create_linear
Cairo Functions
PHP Manual

cairo_pattern_create_for_surface

(PECL cairo >= 0.1.0)

cairo_pattern_create_for_surface — Description

Description

CairoPattern cairo_pattern_create_for_surface ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_for_surface() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_add_color_stop_rgba
cairo_pattern_create_linear
Cairo Functions


cairo_pattern_create_for_surface
cairo_pattern_create_radial
Cairo Functions
PHP Manual

cairo_pattern_create_linear

(PECL cairo >= 0.1.0)

cairo_pattern_create_linear — Description

Description

CairoPattern cairo_pattern_create_linear ( float $x0 , float $y0 , float $x1 , float $y1 )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x0

Description...

y0

Description...

x1

Description...

y1

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_linear() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_create_for_surface
cairo_pattern_create_radial
Cairo Functions


cairo_pattern_create_linear
cairo_pattern_create_rgb
Cairo Functions
PHP Manual

cairo_pattern_create_radial

(PECL cairo >= 0.1.0)

cairo_pattern_create_radial — Description

Description

CairoPattern cairo_pattern_create_radial ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x0

Description...

y0

Description...

r0

Description...

x1

Description...

y1

Description...

r1

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_radial() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_create_linear
cairo_pattern_create_rgb
Cairo Functions


cairo_pattern_create_radial
cairo_pattern_create_rgba
Cairo Functions
PHP Manual

cairo_pattern_create_rgb

(PECL cairo >= 0.1.0)

cairo_pattern_create_rgb — Description

Description

CairoPattern cairo_pattern_create_rgb ( float $red , float $green , float $blue )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

red

Description...

green

Description...

blue

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_rgb() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_create_radial
cairo_pattern_create_rgba
Cairo Functions


cairo_pattern_create_rgb
cairo_pattern_get_color_stop_count
Cairo Functions
PHP Manual

cairo_pattern_create_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_create_rgba — Description

Description

CairoPattern cairo_pattern_create_rgba ( float $red , float $green , float $blue , float $alpha )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_create_rgb
cairo_pattern_get_color_stop_count
Cairo Functions


cairo_pattern_create_rgba
cairo_pattern_get_color_stop_rgba
Cairo Functions
PHP Manual

cairo_pattern_get_color_stop_count

(PECL cairo >= 0.1.0)

cairo_pattern_get_color_stop_count — Description

Description

int cairo_pattern_get_color_stop_count ( CairoGradientPattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_color_stop_count() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_create_rgba
cairo_pattern_get_color_stop_rgba
Cairo Functions


cairo_pattern_get_color_stop_count
cairo_pattern_get_extend
Cairo Functions
PHP Manual

cairo_pattern_get_color_stop_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_get_color_stop_rgba — Description

Description

array cairo_pattern_get_color_stop_rgba ( CairoGradientPattern $pattern , string $index )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

index

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_color_stop_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_get_color_stop_count
cairo_pattern_get_extend
Cairo Functions


cairo_pattern_get_color_stop_rgba
cairo_pattern_get_filter
Cairo Functions
PHP Manual

cairo_pattern_get_extend

(PECL cairo >= 0.1.0)

cairo_pattern_get_extend — Description

Description

int cairo_pattern_get_extend ( string $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_extend() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_get_color_stop_rgba
cairo_pattern_get_filter
Cairo Functions


cairo_pattern_get_extend
cairo_pattern_get_linear_points
Cairo Functions
PHP Manual

cairo_pattern_get_filter

(PECL cairo >= 0.1.0)

cairo_pattern_get_filter — Description

Description

int cairo_pattern_get_filter ( CairoSurfacePattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_filter() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_get_extend
cairo_pattern_get_linear_points
Cairo Functions


cairo_pattern_get_filter
cairo_pattern_get_matrix
Cairo Functions
PHP Manual

cairo_pattern_get_linear_points

(PECL cairo >= 0.1.0)

cairo_pattern_get_linear_points — Description

Description

array cairo_pattern_get_linear_points ( CairoLinearGradient $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_linear_points() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_get_filter
cairo_pattern_get_matrix
Cairo Functions


cairo_pattern_get_linear_points
cairo_pattern_get_radial_circles
Cairo Functions
PHP Manual

cairo_pattern_get_matrix

(PECL cairo >= 0.1.0)

cairo_pattern_get_matrix — Description

Description

CairoMatrix cairo_pattern_get_matrix ( CairoPattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_get_linear_points
cairo_pattern_get_radial_circles
Cairo Functions


cairo_pattern_get_matrix
cairo_pattern_get_rgba
Cairo Functions
PHP Manual

cairo_pattern_get_radial_circles

(PECL cairo >= 0.1.0)

cairo_pattern_get_radial_circles — Description

Description

array cairo_pattern_get_radial_circles ( CairoRadialGradient $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_radial_circles() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_get_matrix
cairo_pattern_get_rgba
Cairo Functions


cairo_pattern_get_radial_circles
cairo_pattern_get_surface
Cairo Functions
PHP Manual

cairo_pattern_get_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_get_rgba — Description

Description

array cairo_pattern_get_rgba ( CairoSolidPattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_get_radial_circles
cairo_pattern_get_surface
Cairo Functions


cairo_pattern_get_rgba
cairo_pattern_get_type
Cairo Functions
PHP Manual

cairo_pattern_get_surface

(PECL cairo >= 0.1.0)

cairo_pattern_get_surface — Description

Description

CairoSurface cairo_pattern_get_surface ( CairoSurfacePattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_surface() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_get_rgba
cairo_pattern_get_type
Cairo Functions


cairo_pattern_get_surface
cairo_pattern_set_extend
Cairo Functions
PHP Manual

cairo_pattern_get_type

(PECL cairo >= 0.1.0)

cairo_pattern_get_type — Description

Description

int cairo_pattern_get_type ( CairoPattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_get_surface
cairo_pattern_set_extend
Cairo Functions


cairo_pattern_get_type
cairo_pattern_set_filter
Cairo Functions
PHP Manual

cairo_pattern_set_extend

(PECL cairo >= 0.1.0)

cairo_pattern_set_extend — Description

Description

void cairo_pattern_set_extend ( string $pattern , string $extend )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

extend

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_set_extend() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_get_type
cairo_pattern_set_filter
Cairo Functions


cairo_pattern_set_extend
cairo_pattern_set_matrix
Cairo Functions
PHP Manual

cairo_pattern_set_filter

(PECL cairo >= 0.1.0)

cairo_pattern_set_filter — Description

Description

void cairo_pattern_set_filter ( CairoSurfacePattern $pattern [, string $filter ] )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

filter

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_set_filter() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_set_extend
cairo_pattern_set_matrix
Cairo Functions


cairo_pattern_set_filter
cairo_pattern_status
Cairo Functions
PHP Manual

cairo_pattern_set_matrix

(PECL cairo >= 0.1.0)

cairo_pattern_set_matrix — Description

Description

void cairo_pattern_set_matrix ( CairoPattern $pattern [, CairoMatrix $matrix ] )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

matrix

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_set_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_set_filter
cairo_pattern_status
Cairo Functions


cairo_pattern_set_matrix
cairo_pdf_surface_create
Cairo Functions
PHP Manual

cairo_pattern_status

(PECL cairo >= 0.1.0)

cairo_pattern_status — Description

Description

int cairo_pattern_status ( CairoPattern $pattern )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_set_matrix
cairo_pdf_surface_create
Cairo Functions


cairo_pattern_status
cairo_pdf_surface_set_size
Cairo Functions
PHP Manual

cairo_pdf_surface_create

(PECL cairo >= 0.1.0)

cairo_pdf_surface_create — Description

Description

CairoPdfSurface cairo_pdf_surface_create ( string $file , float $width , float $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pdf_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pattern_status
cairo_pdf_surface_set_size
Cairo Functions


cairo_pdf_surface_create
cairo_ps_get_levels
Cairo Functions
PHP Manual

cairo_pdf_surface_set_size

(PECL cairo >= 0.1.0)

cairo_pdf_surface_set_size — Description

Description

void cairo_pdf_surface_set_size ( CairoPdfSurface $surface , string $width , string $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pdf_surface_set_size() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pdf_surface_create
cairo_ps_get_levels
Cairo Functions


cairo_pdf_surface_set_size
cairo_ps_level_to_string
Cairo Functions
PHP Manual

cairo_ps_get_levels

(PECL cairo >= 0.1.0)

cairo_ps_get_levels — Description

Description

array cairo_ps_get_levels ( void )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_get_levels() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_pdf_surface_set_size
cairo_ps_level_to_string
Cairo Functions


cairo_ps_get_levels
cairo_ps_surface_create
Cairo Functions
PHP Manual

cairo_ps_level_to_string

(PECL cairo >= 0.1.0)

cairo_ps_level_to_string — Description

Description

string cairo_ps_level_to_string ( string $level )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_level_to_string() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_ps_get_levels
cairo_ps_surface_create
Cairo Functions


cairo_ps_level_to_string
cairo_ps_surface_dsc_begin_page_setup
Cairo Functions
PHP Manual

cairo_ps_surface_create

(PECL cairo >= 0.1.0)

cairo_ps_surface_create — Description

Description

CairoPsSurface cairo_ps_surface_create ( string $file , float $width , float $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_ps_level_to_string
cairo_ps_surface_dsc_begin_page_setup
Cairo Functions


cairo_ps_surface_create
cairo_ps_surface_dsc_begin_setup
Cairo Functions
PHP Manual

cairo_ps_surface_dsc_begin_page_setup

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_begin_page_setup — Description

Description

void cairo_ps_surface_dsc_begin_page_setup ( CairoPsSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_dsc_begin_page_setup() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_ps_surface_create
cairo_ps_surface_dsc_begin_setup
Cairo Functions


cairo_ps_surface_dsc_begin_page_setup
cairo_ps_surface_dsc_comment
Cairo Functions
PHP Manual

cairo_ps_surface_dsc_begin_setup

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_begin_setup — Description

Description

void cairo_ps_surface_dsc_begin_setup ( CairoPsSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_dsc_begin_setup() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_ps_surface_dsc_begin_page_setup
cairo_ps_surface_dsc_comment
Cairo Functions


cairo_ps_surface_dsc_begin_setup
cairo_ps_surface_get_eps
Cairo Functions
PHP Manual

cairo_ps_surface_dsc_comment

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_comment — Description

Description

void cairo_ps_surface_dsc_comment ( CairoPsSurface $surface , string $comment )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

comment

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_dsc_comment() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_ps_surface_dsc_begin_setup
cairo_ps_surface_get_eps
Cairo Functions


cairo_ps_surface_dsc_comment
cairo_ps_surface_restrict_to_level
Cairo Functions
PHP Manual

cairo_ps_surface_get_eps

(PECL cairo >= 0.1.0)

cairo_ps_surface_get_eps — Description

Description

bool cairo_ps_surface_get_eps ( CairoPsSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_get_eps() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_ps_surface_dsc_comment
cairo_ps_surface_restrict_to_level
Cairo Functions


cairo_ps_surface_get_eps
cairo_ps_surface_set_eps
Cairo Functions
PHP Manual

cairo_ps_surface_restrict_to_level

(PECL cairo >= 0.1.0)

cairo_ps_surface_restrict_to_level — Description

Description

void cairo_ps_surface_restrict_to_level ( CairoPsSurface $surface , string $level )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

level

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_restrict_to_level() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_ps_surface_get_eps
cairo_ps_surface_set_eps
Cairo Functions


cairo_ps_surface_restrict_to_level
cairo_ps_surface_set_size
Cairo Functions
PHP Manual

cairo_ps_surface_set_eps

(PECL cairo >= 0.1.0)

cairo_ps_surface_set_eps — Description

Description

void cairo_ps_surface_set_eps ( CairoPsSurface $surface , string $level )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

level

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_set_eps() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_ps_surface_restrict_to_level
cairo_ps_surface_set_size
Cairo Functions


cairo_ps_surface_set_eps
cairo_scaled_font_create
Cairo Functions
PHP Manual

cairo_ps_surface_set_size

(PECL cairo >= 0.1.0)

cairo_ps_surface_set_size — Description

Description

void cairo_ps_surface_set_size ( CairoPsSurface $surface , string $width , string $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_set_size() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_ps_surface_set_eps
cairo_scaled_font_create
Cairo Functions


cairo_ps_surface_set_size
cairo_scaled_font_extents
Cairo Functions
PHP Manual

cairo_scaled_font_create

(PECL cairo >= 0.1.0)

cairo_scaled_font_create — Description

Description

CairoScaledFont cairo_scaled_font_create ( CairoFontFace $fontface , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $fontoptions )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fontface

Description...

matrix

Description...

ctm

Description...

fontoptions

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_ps_surface_set_size
cairo_scaled_font_extents
Cairo Functions


cairo_scaled_font_create
cairo_scaled_font_get_ctm
Cairo Functions
PHP Manual

cairo_scaled_font_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_extents — Description

Description

array cairo_scaled_font_extents ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_create
cairo_scaled_font_get_ctm
Cairo Functions


cairo_scaled_font_extents
cairo_scaled_font_get_font_face
Cairo Functions
PHP Manual

cairo_scaled_font_get_ctm

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_ctm — Description

Description

CairoMatrix cairo_scaled_font_get_ctm ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_ctm() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_extents
cairo_scaled_font_get_font_face
Cairo Functions


cairo_scaled_font_get_ctm
cairo_scaled_font_get_font_matrix
Cairo Functions
PHP Manual

cairo_scaled_font_get_font_face

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_face — Description

Description

CairoFontFace cairo_scaled_font_get_font_face ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_font_face() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_get_ctm
cairo_scaled_font_get_font_matrix
Cairo Functions


cairo_scaled_font_get_font_face
cairo_scaled_font_get_font_options
Cairo Functions
PHP Manual

cairo_scaled_font_get_font_matrix

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_matrix — Description

Description

CairoFontOptions cairo_scaled_font_get_font_matrix ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_font_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_get_font_face
cairo_scaled_font_get_font_options
Cairo Functions


cairo_scaled_font_get_font_matrix
cairo_scaled_font_get_scale_matrix
Cairo Functions
PHP Manual

cairo_scaled_font_get_font_options

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_options — Description

Description

CairoFontOptions cairo_scaled_font_get_font_options ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_font_options() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_get_font_matrix
cairo_scaled_font_get_scale_matrix
Cairo Functions


cairo_scaled_font_get_font_options
cairo_scaled_font_get_type
Cairo Functions
PHP Manual

cairo_scaled_font_get_scale_matrix

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_scale_matrix — Description

Description

CairoMatrix cairo_scaled_font_get_scale_matrix ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_scale_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_get_font_options
cairo_scaled_font_get_type
Cairo Functions


cairo_scaled_font_get_scale_matrix
cairo_scaled_font_glyph_extents
Cairo Functions
PHP Manual

cairo_scaled_font_get_type

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_type — Description

Description

int cairo_scaled_font_get_type ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_get_scale_matrix
cairo_scaled_font_glyph_extents
Cairo Functions


cairo_scaled_font_get_type
cairo_scaled_font_status
Cairo Functions
PHP Manual

cairo_scaled_font_glyph_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_glyph_extents — Description

Description

array cairo_scaled_font_glyph_extents ( CairoScaledFont $scaledfont , string $glyphs )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

glyphs

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_glyph_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_get_type
cairo_scaled_font_status
Cairo Functions


cairo_scaled_font_glyph_extents
cairo_scaled_font_text_extents
Cairo Functions
PHP Manual

cairo_scaled_font_status

(PECL cairo >= 0.1.0)

cairo_scaled_font_status — Description

Description

int cairo_scaled_font_status ( CairoScaledFont $scaledfont )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_glyph_extents
cairo_scaled_font_text_extents
Cairo Functions


cairo_scaled_font_status
cairo_surface_copy_page
Cairo Functions
PHP Manual

cairo_scaled_font_text_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_text_extents — Description

Description

array cairo_scaled_font_text_extents ( CairoScaledFont $scaledfont , string $text )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

text

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_text_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_status
cairo_surface_copy_page
Cairo Functions


cairo_scaled_font_text_extents
cairo_surface_create_similar
Cairo Functions
PHP Manual

cairo_surface_copy_page

(PECL cairo >= 0.1.0)

cairo_surface_copy_page — Description

Description

void cairo_surface_copy_page ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_copy_page() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_scaled_font_text_extents
cairo_surface_create_similar
Cairo Functions


cairo_surface_copy_page
cairo_surface_finish
Cairo Functions
PHP Manual

cairo_surface_create_similar

(PECL cairo >= 0.1.0)

cairo_surface_create_similar — Description

Description

CairoSurface cairo_surface_create_similar ( CairoSurface $surface , string $content , string $width , string $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

content

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_create_similar() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_copy_page
cairo_surface_finish
Cairo Functions


cairo_surface_create_similar
cairo_surface_flush
Cairo Functions
PHP Manual

cairo_surface_finish

(PECL cairo >= 0.1.0)

cairo_surface_finish — Description

Description

void cairo_surface_finish ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_finish() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_create_similar
cairo_surface_flush
Cairo Functions


cairo_surface_finish
cairo_surface_get_content
Cairo Functions
PHP Manual

cairo_surface_flush

(PECL cairo >= 0.1.0)

cairo_surface_flush — Description

Description

void cairo_surface_flush ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_flush() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_finish
cairo_surface_get_content
Cairo Functions


cairo_surface_flush
cairo_surface_get_device_offset
Cairo Functions
PHP Manual

cairo_surface_get_content

(PECL cairo >= 0.1.0)

cairo_surface_get_content — Description

Description

int cairo_surface_get_content ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_content() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_flush
cairo_surface_get_device_offset
Cairo Functions


cairo_surface_get_content
cairo_surface_get_font_options
Cairo Functions
PHP Manual

cairo_surface_get_device_offset

(PECL cairo >= 0.1.0)

cairo_surface_get_device_offset — Description

Description

array cairo_surface_get_device_offset ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_device_offset() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_get_content
cairo_surface_get_font_options
Cairo Functions


cairo_surface_get_device_offset
cairo_surface_get_type
Cairo Functions
PHP Manual

cairo_surface_get_font_options

(PECL cairo >= 0.1.0)

cairo_surface_get_font_options — Description

Description

CairoFontOptions cairo_surface_get_font_options ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_font_options() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_get_device_offset
cairo_surface_get_type
Cairo Functions


cairo_surface_get_font_options
cairo_surface_mark_dirty_rectangle
Cairo Functions
PHP Manual

cairo_surface_get_type

(PECL cairo >= 0.1.0)

cairo_surface_get_type — Description

Description

int cairo_surface_get_type ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_get_font_options
cairo_surface_mark_dirty_rectangle
Cairo Functions


cairo_surface_mark_dirty_rectangle
cairo_surface_set_device_offset
Cairo Functions
PHP Manual

cairo_surface_mark_dirty

(PECL cairo >= 0.1.0)

cairo_surface_mark_dirty — Description

Description

void cairo_surface_mark_dirty ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_mark_dirty() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_mark_dirty_rectangle
cairo_surface_set_device_offset
Cairo Functions


cairo_surface_get_type
cairo_surface_mark_dirty
Cairo Functions
PHP Manual

cairo_surface_mark_dirty_rectangle

(PECL cairo >= 0.1.0)

cairo_surface_mark_dirty_rectangle — Description

Description

void cairo_surface_mark_dirty_rectangle ( CairoSurface $surface , string $x , string $y , string $width , string $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

x

Description...

y

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_mark_dirty_rectangle() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_get_type
cairo_surface_mark_dirty
Cairo Functions


cairo_surface_mark_dirty
cairo_surface_set_fallback_resolution
Cairo Functions
PHP Manual

cairo_surface_set_device_offset

(PECL cairo >= 0.1.0)

cairo_surface_set_device_offset — Description

Description

void cairo_surface_set_device_offset ( CairoSurface $surface , string $x , string $y )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

x

Description...

y

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_set_device_offset() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_mark_dirty
cairo_surface_set_fallback_resolution
Cairo Functions


cairo_surface_set_device_offset
cairo_surface_show_page
Cairo Functions
PHP Manual

cairo_surface_set_fallback_resolution

(PECL cairo >= 0.1.0)

cairo_surface_set_fallback_resolution — Description

Description

void cairo_surface_set_fallback_resolution ( CairoSurface $surface , string $x , string $y )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

x

Description...

y

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_set_fallback_resolution() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_set_device_offset
cairo_surface_show_page
Cairo Functions


cairo_surface_set_fallback_resolution
cairo_surface_status
Cairo Functions
PHP Manual

cairo_surface_show_page

(PECL cairo >= 0.1.0)

cairo_surface_show_page — Description

Description

void cairo_surface_show_page ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_show_page() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_set_fallback_resolution
cairo_surface_status
Cairo Functions


cairo_surface_show_page
cairo_surface_write_to_png
Cairo Functions
PHP Manual

cairo_surface_status

(PECL cairo >= 0.1.0)

cairo_surface_status — Description

Description

int cairo_surface_status ( CairoSurface $surface )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_show_page
cairo_surface_write_to_png
Cairo Functions


cairo_surface_status
cairo_svg_surface_create
Cairo Functions
PHP Manual

cairo_surface_write_to_png

(PECL cairo >= 0.1.0)

cairo_surface_write_to_png — Description

Description

void cairo_surface_write_to_png ( CairoSurface $surface , string $x , string $y )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

x

Description...

y

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_write_to_png() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_status
cairo_svg_surface_create
Cairo Functions


cairo_surface_write_to_png
cairo_svg_surface_restrict_to_version
Cairo Functions
PHP Manual

cairo_svg_surface_create

(PECL cairo >= 0.1.0)

cairo_svg_surface_create — Description

Description

CairoSvgSurface cairo_svg_surface_create ( string $file , float $width , float $height )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_svg_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_surface_write_to_png
cairo_svg_surface_restrict_to_version
Cairo Functions


cairo_svg_surface_create
cairo_svg_version_to_string
Cairo Functions
PHP Manual

cairo_svg_surface_restrict_to_version

(PECL cairo >= 0.1.0)

cairo_svg_surface_restrict_to_version — Description

Description

void cairo_svg_surface_restrict_to_version ( CairoSvgSurface $surface , string $version )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

version

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_svg_surface_restrict_to_version() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_svg_surface_create
cairo_svg_version_to_string
Cairo Functions


cairo_svg_surface_restrict_to_version
Cairo
Cairo Functions
PHP Manual

cairo_svg_version_to_string

(PECL cairo >= 0.1.0)

cairo_svg_version_to_string — Description

Description

string cairo_svg_version_to_string ( int $version )

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

version

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_svg_version_to_string() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()

cairo_svg_surface_restrict_to_version
Cairo
Cairo Functions


Return the number of days in a month for a given year and calendar

Calendar Functions
cal_from_jd
Calendar Functions
PHP Manual

cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5)

cal_days_in_month — Return the number of days in a month for a given year and calendar

Description

int cal_days_in_month ( int $calendar , int $month , int $year )

This function will return the number of days in the month of year for the specified calendar .

Parameters

calendar

Calendar to use for calculation

month

Month in the selected calendar

year

Year in the selected calendar

Return Values

The length in days of the selected month in the given calendar

Examples

Example #1 cal_days_in_month() example

<?php
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There was $num days in August 2003";
?>

Calendar Functions
cal_from_jd
Calendar Functions


Converts from Julian Day Count to a supported calendar

cal_days_in_month
cal_info
Calendar Functions
PHP Manual

cal_from_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_from_jd — Converts from Julian Day Count to a supported calendar

Description

array cal_from_jd ( int $jd , int $calendar )

cal_from_jd() converts the Julian day given in jd into a date of the specified calendar . Supported calendar values are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters

jd

Julian day as integer

calendar

Calendar to convert to

Return Values

Returns an array containing calendar information like month, day, year, day of week, abbreviated and full names of weekday and month and the date in string form "month/day/year".

Examples

Example #1 cal_from_jd() example

<?php
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_GREGORIAN));
?>

The above example will output:

Array
(
    [date] => 8/16/2003
    [month] => 8
    [day] => 16
    [year] => 2003
    [dow] => 6
    [abbrevdayname] => Sat
    [dayname] => Saturday
    [abbrevmonth] => Aug
    [monthname] => August
)

See Also

  • cal_to_jd() - Converts from a supported calendar to Julian Day Count
  • jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
  • jdtogregorian() - Converts Julian Day Count to Gregorian date
  • jdtojewish() - Converts a Julian day count to a Jewish calendar date
  • jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
  • jdtounix() - Convert Julian Day to Unix timestamp

cal_days_in_month
cal_info
Calendar Functions


Returns information about a particular calendar

cal_from_jd
cal_to_jd
Calendar Functions
PHP Manual

cal_info

(PHP 4 >= 4.1.0, PHP 5)

cal_info — Returns information about a particular calendar

Description

array cal_info ([ int $calendar = -1 ] )

cal_info() returns information on the specified calendar .

Calendar information is returned as an array containing the elements calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar are as follows:

  • 0 or CAL_GREGORIAN - Gregorian Calendar
  • 1 or CAL_JULIAN - Julian Calendar
  • 2 or CAL_JEWISH - Jewish Calendar
  • 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array.

Parameters

calendar

Calendar to return information for. If no calendar is specified information about all calendars is returned.

Return Values

Changelog

Version | Description
Since 5.0 | The calendar parameter becomes optional and defaults to "all calendars" if omitted.

Examples

Example #1 cal_info() example

<?php
$info = cal_info(0);
print_r($info);
?>

The above example will output:

Array
(
    [months] => Array
        (
            [1] => January
            [2] => February
            [3] => March
            [4] => April
            [5] => May
            [6] => June
            [7] => July
            [8] => August
            [9] => September
            [10] => October
            [11] => November
            [12] => December
        )

    [abbrevmonths] => Array
        (
            [1] => Jan
            [2] => Feb
            [3] => Mar
            [4] => Apr
            [5] => May
            [6] => Jun
            [7] => Jul
            [8] => Aug
            [9] => Sep
            [10] => Oct
            [11] => Nov
            [12] => Dec
        )

    [maxdaysinmonth] => 31
    [calname] => Gregorian
    [calsymbol] => CAL_GREGORIAN
)

cal_from_jd
cal_to_jd
Calendar Functions


Converts from a supported calendar to Julian Day Count

cal_info
easter_date
Calendar Functions
PHP Manual

cal_to_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_to_jd — Converts from a supported calendar to Julian Day Count

Description

int cal_to_jd ( int $calendar , int $month , int $day , int $year )

cal_to_jd() calculates the Julian day count for a date in the specified calendar . Supported calendar s are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters

calendar

Calendar to convert from, one of CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH or CAL_FRENCH.

month

The month as a number, the valid range depends on the calendar

day

The day as a number, the valid range depends on the calendar

year

The year as a number, the valid range depends on the calendar

Return Values

A Julian Day number.

See Also

  • cal_from_jd() - Converts from Julian Day Count to a supported calendar
  • frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
  • gregoriantojd() - Converts a Gregorian date to Julian Day Count
  • jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
  • juliantojd() - Converts a Julian Calendar date to Julian Day Count
  • unixtojd() - Convert Unix timestamp to Julian Day

cal_info
easter_date
Calendar Functions


Obtain a hmac key (needs 8 arguments)

SPPLUS Functions
calculhmac
SPPLUS Functions
PHP Manual

calcul_hmac

(PECL spplus >= 1.0.0)

calcul_hmac — Obtain a hmac key (needs 8 arguments)

Description

string calcul_hmac ( string $clent , string $siretcode , string $price , string $reference , string $validity , string $taxation , string $devise , string $language )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

SPPLUS Functions
calculhmac
SPPLUS Functions


Obtain a hmac key (needs 2 arguments)

calcul_hmac
nthmac
SPPLUS Functions
PHP Manual

calculhmac

(PECL spplus >= 1.0.0)

calculhmac — Obtain a hmac key (needs 2 arguments)

Description

string calculhmac ( string $clent , string $data )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

calcul_hmac
nthmac
SPPLUS Functions


Round fractions up

bindec
cos
Math Functions
PHP Manual

ceil

(PHP 4, PHP 5)

ceil — Round fractions up

Description

float ceil ( float $value )

Returns the next highest integer value by rounding up value if necessary.

Parameters

value

The value to round

Return Values

value rounded up to the next highest integer. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer.

Examples

Example #1 ceil() example

<?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?>

See Also

  • floor() - Round fractions down
  • round() - Rounds a float

bindec
cos
Math Functions


Change directory

Directory Functions
chroot
Directory Functions
PHP Manual

chdir

(PHP 4, PHP 5)

chdir — Change directory

Description

bool chdir ( string $directory )

Changes PHP's current directory to directory .

Parameters

directory

The new current directory

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 chdir() example

<?php

// current directory
echo getcwd() . "\n";

chdir('public_html');

// current directory
echo getcwd() . "\n";

?>

The above example will output something similar to:

/home/vincent
/home/vincent/public_html

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • getcwd() - Gets the current working directory

Directory Functions
chroot
Directory Functions


Validate a Gregorian date

Date/Time Functions
date_add
Date/Time Functions
PHP Manual

checkdate

(PHP 4, PHP 5)

checkdate — Validate a Gregorian date

Description

bool checkdate ( int $month , int $day , int $year )

Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.

Parameters

month

The month is between 1 and 12 inclusive.

day

The day is within the allowed number of days for the given month . Leap year s are taken into consideration.

year

The year is between 1 and 32767 inclusive.

Return Values

Returns TRUE if the date given is valid; otherwise returns FALSE.

Examples

Example #1 checkdate() example

<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>

The above example will output:

bool(true)
bool(false)

See Also

  • mktime() - Get Unix timestamp for a date
  • strtotime() - Parse about any English textual datetime description into a Unix timestamp

Date/Time Functions
date_add
Date/Time Functions


Changes file group

basename
chmod
Filesystem Functions
PHP Manual

chgrp

(PHP 4, PHP 5)

chgrp — Changes file group

Description

bool chgrp ( string $filename , mixed $group )

Attempts to change the group of the file filename to group .

Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.

Parameters

filename

Path to the file.

group

A group name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing a file's group

<?php
$filename = 'shared_file.txt';
$format = "%s's Group ID @ %s: %d\n";
printf($format, $filename, date('r'), filegroup($filename));
chgrp($filename, 8);
printf($format, $filename, date('r'), filegroup($filename));
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

See Also

  • chown() - Changes file owner
  • chmod() - Changes file mode

basename
chmod
Filesystem Functions


Changes file mode

chgrp
chown
Filesystem Functions
PHP Manual

chmod

(PHP 4, PHP 5)

chmod — Changes file mode

Description

bool chmod ( string $filename , int $mode )

Attempts to change the mode of the specified file to that given in mode .

Parameters

filename

Path to the file.

mode

Note that mode is not automatically assumed to be an octal value, so strings (such as "g+w") will not work properly. To ensure the expected operation, you need to prefix mode with a zero (0):

<?php
chmod("/somedir/somefile", 755);   // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755);  // octal; correct value of mode
?>

The mode parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'.

<?php
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);

// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);

// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);

// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile", 0750);
?>

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems.

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits.

See Also

  • chown() - Changes file owner
  • chgrp() - Changes file group
  • fileperms() - Gets file permissions
  • stat() - Gives information about a file

chgrp
chown
Filesystem Functions


Changes file owner

chmod
clearstatcache
Filesystem Functions
PHP Manual

chown

(PHP 4, PHP 5)

chown — Changes file owner

Description

bool chown ( string $filename , mixed $user )

Attempts to change the owner of the file filename to user user . Only the superuser may change the owner of a file.

Parameters

filename

Path to the file.

user

A user name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Simple chown() usage

<?php

// File name and username to use
$file_name= "foo.php";
$path = "/home/sites/php.net/public_html/sandbox/" . $file_name ;
$user_name = "root";

// Set the user
chown($path, $user_name);

// Check the result
$stat = stat($path);
print_r(posix_getpwuid($stat['uid']));

?>

The above example will output something similar to:

array(7) {
  ["name"]=>
  string(13) "php.net"
  ["passwd"]=>
  string(1) "x"
  ["uid"]=>
  int(148864)
  ["gid"]=>
  int(148910)
  ["gecos"]=>
  string(13) "php.net"
  ["dir"]=>
  string(25) "/home/sites/php.net"
  ["shell"]=>
  string(13) "/sbin/nologin"
}

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

See Also

  • chmod() - Changes file mode

chmod
clearstatcache
Filesystem Functions


Change the root directory

chdir
dir
Directory Functions
PHP Manual

chroot

(PHP 4 >= 4.0.5, PHP 5)

chroot — Change the root directory

Description

bool chroot ( string $directory )

Changes the root directory of the current process to directory .

This function is only available if your system supports it and you're using the CLI, CGI or Embed SAPI. Also, this function requires root privileges.

Parameters

directory

The new directory

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is not implemented on Windows platforms.

chdir
dir
Directory Functions


Clears file status cache

chown
copy
Filesystem Functions
PHP Manual

clearstatcache

(PHP 4, PHP 5)

clearstatcache — Clears file status cache

Description

void clearstatcache ([ bool $clear_realpath_cache = false [, string $filename ]] )

When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.

You should also note that PHP doesn't cache information about non-existent files. So, if you call file_exists() on a file that doesn't exist, it will return FALSE until you create the file. If you create the file, it will return TRUE even if you then delete the file. However unlink() clears the cache automatically.

Note: This function caches information about specific filenames, so you only need to call clearstatcache() if you are performing multiple operations on the same filename and require the information about that particular file to not be cached.

Affected functions include stat(),
lstat(),
file_exists(),
is_writable(),
is_readable(),
is_executable(),
is_file(),
is_dir(),
is_link(),
filectime(),
fileatime(),
filemtime(),
fileinode(),
filegroup(),
fileowner(),
filesize(),
filetype(), and
fileperms().

Parameters

clear_realpath_cache

Whenever to clear realpath cache or not.

filename

Clear realpath cache on a specific filename, only used if clear_realpath_cache is TRUE.

Return Values

No value is returned.

Changelog

Version | Description
5.3.0 | Added optional clear_realpath_cache and filename parameters.

Examples

Example #1 clearstatcache() example

<?php
$file = 'output_log.txt';

function get_owner($file)
{
    $stat = stat($file);
    $user = posix_getpwuid($stat['uid']);
    return $user['name'];
}

$format = "UID @ %s: %s\n";

printf($format, date('r'), get_owner($file));

chown($file, 'ross');
printf($format, date('r'), get_owner($file));

clearstatcache();
printf($format, date('r'), get_owner($file));
?>

The above example will output something similar to:

UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross

chown
copy
Filesystem Functions


Close directory handle

dir
getcwd
Directory Functions
PHP Manual

closedir

(PHP 4, PHP 5)

closedir — Close directory handle

Description

void closedir ([ resource $dir_handle ] )

Closes the directory stream indicated by dir_handle . The stream must have previously been opened by opendir().

Parameters

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Examples

Example #1 closedir() example

<?php
$dir = "/etc/php5/";

// Open a known directory, read directory into variable and then close
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $directory = readdir($dh);
        closedir($dh);
    }
}
?>

dir
getcwd
Directory Functions


Check whether client disconnected

Misc. Functions
connection_status
Misc. Functions
PHP Manual

connection_aborted

(PHP 4, PHP 5)

connection_aborted — Check whether client disconnected

Description

int connection_aborted ( void )

Checks whether the client disconnected.

Return Values

Returns 1 if client disconnected, 0 otherwise.

See Also

  • connection_status() - Returns connection status bitfield
  • ignore_user_abort() - Set whether a client disconnect should abort script execution
  • Connection Handling for a complete description of connection handling in PHP.

Misc. Functions
connection_status
Misc. Functions


Returns connection status bitfield

connection_aborted
connection_timeout
Misc. Functions
PHP Manual

connection_status

(PHP 4, PHP 5)

connection_status — Returns connection status bitfield

Description

int connection_status ( void )

Gets the connection status bitfield.

Return Values

Returns the connection status bitfield, which can be used against the CONNECTION_XXX constants to determine the connection status.

See Also

  • connection_aborted() - Check whether client disconnected
  • ignore_user_abort() - Set whether a client disconnect should abort script execution
  • Connection Handling for a complete description of connection handling in PHP.

connection_aborted
connection_timeout
Misc. Functions


Check if the script timed out

connection_status
constant
Misc. Functions
PHP Manual

connection_timeout

(PHP 4 <= 4.0.4)

connection_timeout — Check if the script timed out

Description

int connection_timeout ( void )

Determines whether the script timed out.

Return Values

Returns 1 if the script timed out, 0 otherwise.

Notes

Warning

Deprecated

This function is deprecated, and doesn't even exist anymore as of 4.0.5.

See Also

  • connection_status() - Returns connection status bitfield
  • Connection Handling for a complete description of connection handling in PHP.

connection_status
constant
Misc. Functions


Returns the value of a constant

connection_timeout
define
Misc. Functions
PHP Manual

constant

(PHP 4 >= 4.0.4, PHP 5)

constant — Returns the value of a constant

Description

mixed constant ( string $name )

Return the value of the constant indicated by name .

constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.

This function works also with class constants.

Parameters

name

The constant name.

Return Values

Returns the value of the constant, or NULL if the constant is not defined.

Examples

Example #1 constant() example

<?php

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

interface bar {
    const test = 'foobar!';
}

class foo {
    const test = 'foobar!';
}

$const = 'test';

var_dump(constant('bar::'. $const)); // string(7) "foobar!"
var_dump(constant('foo::'. $const)); // string(7) "foobar!"

?>

See Also

  • define() - Defines a named constant
  • defined() - Checks whether a given named constant exists
  • The section on Constants

connection_timeout
define
Misc. Functions


Copies file

clearstatcache
delete
Filesystem Functions
PHP Manual

copy

(PHP 4, PHP 5)

copy — Copies file

Description

bool copy ( string $source , string $dest [, resource $context ] )

Makes a copy of the file source to dest .

If you wish to move a file, use the rename() function.

Parameters

source

Path to the source file.

dest

The destination path. If dest is a URL, the copy operation may fail if the wrapper does not support overwriting of existing files.

Warning

If the destination file already exists, it will be overwritten.

context

A valid context resource created with stream_context_create().

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | Added context support.
4.3.0 | Both source and dest may now be URLs if the "fopen wrappers" have been enabled. See fopen() for more details.

Examples

Example #1 copy() example

<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}
?>

See Also

  • move_uploaded_file() - Moves an uploaded file to a new location
  • rename() - Renames a file or directory
  • The section of the manual about handling file uploads

clearstatcache
delete
Filesystem Functions


Cosine

ceil
cosh
Math Functions
PHP Manual

cos

(PHP 4, PHP 5)

cos — Cosine

Description

float cos ( float $arg )

cos() returns the cosine of the arg parameter. The arg parameter is in radians.

Parameters

arg

An angle in radians

Return Values

The cosine of arg

Examples

Example #1 cos() example

<?php

echo cos(M_PI); // -1

?>

See Also

  • acos() - Arc cosine
  • sin() - Sine
  • tan() - Tangent
  • deg2rad() - Converts the number in degrees to the radian equivalent

ceil
cosh
Math Functions


Hyperbolic cosine

cos
decbin
Math Functions
PHP Manual

cosh

(PHP 4 >= 4.1.0, PHP 5)

cosh — Hyperbolic cosine

Description

float cosh ( float $arg )

Returns the hyperbolic cosine of arg , defined as (exp(arg) + exp(-arg))/2.

Parameters

arg

The argument to process

Return Values

The hyperbolic cosine of arg

See Also

  • cos() - Cosine
  • acosh() - Inverse hyperbolic cosine
  • sinh() - Hyperbolic sine
  • cosh()

cos
decbin
Math Functions


Performs an obscure check with the given password

Crack Functions
crack_closedict
Crack Functions
PHP Manual

crack_check

(PECL crack >= 0.1)

crack_check — Performs an obscure check with the given password

Description

bool crack_check ( resource $dictionary , string $password )
bool crack_check ( string $password )

Performs an obscure check with the given password on the specified dictionary.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

dictionary

The crack lib dictionary. If not specified, the last opened dictionary is used.

password

The tested password.

Return Values

Returns TRUE if password is strong, or FALSE otherwise.

Crack Functions
crack_closedict
Crack Functions


Closes an open CrackLib dictionary

crack_check
crack_getlastmessage
Crack Functions
PHP Manual

crack_closedict

(PECL crack >= 0.1)

crack_closedict — Closes an open CrackLib dictionary

Description

bool crack_closedict ([ resource $dictionary ] )

crack_closedict() closes the specified dictionary identifier.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

dictionary

The dictionary to close. If not specified, the current directory is closed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • crack_opendict() - Opens a new CrackLib dictionary

crack_check
crack_getlastmessage
Crack Functions


Returns the message from the last obscure check

crack_closedict
crack_opendict
Crack Functions
PHP Manual

crack_getlastmessage

(PECL crack >= 0.1)

crack_getlastmessage — Returns the message from the last obscure check

Description

string crack_getlastmessage ( void )

crack_getlastmessage() returns the message from the last obscure check.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Return Values

The message from the last obscure check or FALSE if there was no obscure checks made so far.

The returned message is one of:

  • it's WAY too short
  • it is too short
  • it does not contain enough DIFFERENT characters
  • it is all whitespace
  • it is too simplistic/systematic
  • it looks like a National Insurance number.
  • it is based on a dictionary word
  • it is based on a (reversed) dictionary word
  • strong password

See Also

  • crack_check() - Performs an obscure check with the given password

crack_closedict
crack_opendict
Crack Functions


Opens a new CrackLib dictionary

crack_getlastmessage
Hash
Crack Functions
PHP Manual

crack_opendict

(PECL crack >= 0.1)

crack_opendict — Opens a new CrackLib dictionary

Description

resource crack_opendict ( string $dictionary )

crack_opendict() opens the specified CrackLib dictionary for use with crack_check().

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Note: Only one dictionary may be open at a time.

Parameters

dictionary

The path to the Cracklib dictionary.

Return Values

Returns a dictionary resource identifier on success or FALSE on failure.

See Also

  • crack_check() - Performs an obscure check with the given password
  • crack_closedict() - Closes an open CrackLib dictionary

crack_getlastmessage
Hash
Crack Functions


Authenticate against a Cyrus IMAP server

Cyrus Functions
cyrus_bind
Cyrus Functions
PHP Manual

cyrus_authenticate

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_authenticate — Authenticate against a Cyrus IMAP server

Description

void cyrus_authenticate ( resource $connection [, string $mechlist [, string $service [, string $user [, int $minssf [, int $maxssf [, string $authname [, string $password ]]]]]]] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

Cyrus Functions
cyrus_bind
Cyrus Functions


Bind callbacks to a Cyrus IMAP connection

cyrus_authenticate
cyrus_close
Cyrus Functions
PHP Manual

cyrus_bind

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_bind — Bind callbacks to a Cyrus IMAP connection

Description

bool cyrus_bind ( resource $connection , array $callbacks )

Binds callbacks to a Cyrus IMAP connection.

Parameters

connection

The connection handle.

callbacks

An array of callbacks.

Return Values

Returns TRUE on success or FALSE on failure.

cyrus_authenticate
cyrus_close
Cyrus Functions


Close connection to a Cyrus IMAP server

cyrus_bind
cyrus_connect
Cyrus Functions
PHP Manual

cyrus_close

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_close — Close connection to a Cyrus IMAP server

Description

bool cyrus_close ( resource $connection )

Closes the connection to a Cyrus IMAP server.

Parameters

connection

The connection handle.

Return Values

Returns TRUE on success or FALSE on failure.

cyrus_bind
cyrus_connect
Cyrus Functions


Connect to a Cyrus IMAP server

cyrus_close
cyrus_query
Cyrus Functions
PHP Manual

cyrus_connect

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_connect — Connect to a Cyrus IMAP server

Description

resource cyrus_connect ([ string $host [, string $port [, int $flags ]]] )

Connects to a Cyrus IMAP server.

Parameters

host

The Cyrus IMAP host name.

port

The port number.

flags

Return Values

Returns a connection handler on success or FALSE on failure.

cyrus_close
cyrus_query
Cyrus Functions


Send a query to a Cyrus IMAP server

cyrus_connect
cyrus_unbind
Cyrus Functions
PHP Manual

cyrus_query

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_query — Send a query to a Cyrus IMAP server

Description

array cyrus_query ( resource $connection , string $query )

Sends a query to a Cyrus IMAP server.

Parameters

connection

The connection handle.

query

The query string.

Return Values

Returns an associative array with the following keys: text, msgno, and keyword.

cyrus_connect
cyrus_unbind
Cyrus Functions


Unbind ...

cyrus_query
IMAP
Cyrus Functions
PHP Manual

cyrus_unbind

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_unbind — Unbind ...

Description

bool cyrus_unbind ( resource $connection , string $trigger_name )
Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

The connection handle.

trigger_name

The trigger name.

Return Values

Returns TRUE on success or FALSE on failure.

cyrus_query
IMAP
Cyrus Functions


Format a local time/date

date_timezone_set
getdate
Date/Time Functions
PHP Manual

date

(PHP 4, PHP 5)

date — Format a local time/date

Description

string date ( string $format [, int $timestamp ] )

Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

Parameters

format

The format of the outputted date string. See the formatting options below. There are also several predefined date constants that may be used instead, so for example DATE_RSS contains the format string 'D, d M Y H:i:s'.

The following characters are recognized in the format parameter string
format character | Description | Example returned values
Day --- ---
d | Day of the month, 2 digits with leading zeros | 01 to 31
D | A textual representation of a day, three letters | Mon through Sun
j | Day of the month without leading zeros | 1 to 31
l (lowercase 'L') | A full textual representation of the day of the week | Sunday through Saturday
N | ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) | 1 (for Monday) through 7 (for Sunday)
S | English ordinal suffix for the day of the month, 2 characters | st, nd, rd or th. Works well with j
w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday)
z | The day of the year (starting from 0) | 0 through 365
Week --- ---
W | ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) | Example: 42 (the 42nd week in the year)
Month --- ---
F | A full textual representation of a month, such as January or March | January through December
m | Numeric representation of a month, with leading zeros | 01 through 12
M | A short textual representation of a month, three letters | Jan through Dec
n | Numeric representation of a month, without leading zeros | 1 through 12
t | Number of days in the given month | 28 through 31
Year --- ---
L | Whether it's a leap year | 1 if it is a leap year, 0 otherwise.
o | ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) | Examples: 1999 or 2003
Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003
y | A two digit representation of a year | Examples: 99 or 03
Time --- ---
a | Lowercase Ante meridiem and Post meridiem | am or pm
A | Uppercase Ante meridiem and Post meridiem | AM or PM
B | Swatch Internet time | 000 through 999
g | 12-hour format of an hour without leading zeros | 1 through 12
G | 24-hour format of an hour without leading zeros | 0 through 23
h | 12-hour format of an hour with leading zeros | 01 through 12
H | 24-hour format of an hour with leading zeros | 00 through 23
i | Minutes with leading zeros | 00 to 59
s | Seconds, with leading zeros | 00 through 59
u | Microseconds (added in PHP 5.2.2) | Example: 654321
Timezone --- ---
e | Timezone identifier (added in PHP 5.1.0) | Examples: UTC, GMT, Atlantic/Azores
I (capital i) | Whether or not the date is in daylight saving time | 1 if Daylight Saving Time, 0 otherwise.
O | Difference to Greenwich time (GMT) in hours | Example: +0200
P | Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) | Example: +02:00
T | Timezone abbreviation | Examples: EST, MDT ...
Z | Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. | -43200 through 50400
Full Date/Time --- ---
c | ISO 8601 date (added in PHP 5) | 2004-02-12T15:19:21+00:00
r | » RFC 2822 formatted date | Example: Thu, 21 Dec 2000 16:01:07 +0200
U | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | See also time()

Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate().

Note: Since this function only accepts integer timestamps the u format character is only useful when using the date_format() function with user based timestamps created with date_create().

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a formatted date string. If a non-numeric value is used for timestamp , FALSE is returned and an E_WARNING level error is emitted.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.1.0 | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.
5.1.1 | There are useful constants of standard date/time formats that can be used to specify the format parameter.

Examples

Example #1 date() examples

<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');

// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* use the constants in the format parameter */
// prints something like: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example #2 Escaping characters in date()

<?php
// prints something like: Wednesday the 15th
echo date("l \\t\h\e jS");
?>

It is possible to use date() and mktime() together to find dates in the future or the past.

Example #3 date() and mktime() example

<?php
$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);
?>

Note: This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example #4 date() Formatting

<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
?>

To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().

Notes

Note: To generate a timestamp from a string representation of the date, you may be able to use strtotime(). Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL's » UNIX_TIMESTAMP function).

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.

See Also

  • gmdate() - Format a GMT/UTC date/time
  • idate() - Format a local time/date as integer
  • getdate() - Get date/time information
  • getlastmod() - Gets time of last page modification
  • mktime() - Get Unix timestamp for a date
  • strftime() - Format a local time/date according to locale settings
  • time() - Return current Unix timestamp
  • Predefined DateTime Constants

date_timezone_set
getdate
Date/Time Functions


Alias of DateTime::add

checkdate
date_create_from_format
Date/Time Functions
PHP Manual

date_add

(PHP 5 >= 5.3.0)

date_add — Alias of DateTime::add

Description

This function is an alias of: DateTime::add

checkdate
date_create_from_format
Date/Time Functions


Returns new DateTime object

date_create_from_format
date_date_set
Date/Time Functions
PHP Manual

date_create

(PHP 5 >= 5.2.0)

date_create — Returns new DateTime object

Description

DateTime date_create ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Parameters

time

String in a format accepted by strtotime().

timezone

Time zone of the time.

Return Values

Returns DateTime object on success or FALSE on failure.

Examples

Example #1 date_create() example

<?php
date_default_timezone_set('Europe/London');

$datetime = date_create('2008-08-03 14:52:10');
echo date_format($datetime, DATE_ATOM);
?>

The above example will output:

2008-08-03T14:52:10+01:00

date_create_from_format
date_date_set
Date/Time Functions


Alias of DateTime::createFromFormat

date_add
date_create
Date/Time Functions
PHP Manual

date_create_from_format

(PHP 5 >= 5.3.0)

date_create_from_format — Alias of DateTime::createFromFormat

Description

This function is an alias of: DateTime::createFromFormat

date_add
date_create
Date/Time Functions


Alias of DateTime::setDate

date_create
date_default_timezone_get
Date/Time Functions
PHP Manual

date_date_set

(PHP 5 >= 5.2.0)

date_date_set — Alias of DateTime::setDate

Description

This function is an alias of: DateTime::setDate

date_create
date_default_timezone_get
Date/Time Functions


Gets the default timezone used by all date/time functions in a script

date_date_set
date_default_timezone_set
Date/Time Functions
PHP Manual

date_default_timezone_get

(PHP 5 >= 5.1.0)

date_default_timezone_get — Gets the default timezone used by all date/time functions in a script

Description

string date_default_timezone_get ( void )

In order of preference, this function returns the default timezone by:

  • Reading the timezone set using the date_default_timezone_set() function (if any)

  • Reading the TZ environment variable (if non empty)

  • Reading the value of the date.timezone ini option (if set)

  • Querying the host operating system (if supported and allowed by the OS)

If none of the above succeed, date_default_timezone_get will return a default timezone of UTC.

Return Values

Returns a string.

Examples

Example #1 Getting the default timezone

<?php
date_default_timezone_set('Europe/London');

if (date_default_timezone_get()) {
    echo 'date_default_timezone_set: ' . date_default_timezone_get() . '<br />';
}

if (ini_get('date.timezone')) {
    echo 'date.timezone: ' . ini_get('date.timezone');
}

?>

The above example will output something similar to:

date_default_timezone_set: Europe/London
date.timezone: Europe/London

Example #2 Getting the abbreviation of a timezone

<?php
date_default_timezone_set('America/Los_Angeles');
echo date_default_timezone_get() . ' => ' . date('e') . ' => ' . date('T');
?>

The above example will output:

America/Los_Angeles => America/Los_Angeles => PST

See Also

  • date_default_timezone_set() - Sets the default timezone used by all date/time functions in a script
  • List of Supported Timezones

date_date_set
date_default_timezone_set
Date/Time Functions


Sets the default timezone used by all date/time functions in a script

date_default_timezone_get
date_diff
Date/Time Functions
PHP Manual

date_default_timezone_set

(PHP 5 >= 5.1.0)

date_default_timezone_set — Sets the default timezone used by all date/time functions in a script

Description

bool date_default_timezone_set ( string $timezone_identifier )

date_default_timezone_set() sets the default timezone used by all date/time functions.

Note: Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_WARNING message if using the system settings or the TZ environment variable.

Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.

Parameters

timezone_identifier

The timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the List of Supported Timezones.

Return Values

This function returns FALSE if the timezone_identifier isn't valid, or TRUE otherwise.

Examples

Example #1 Getting the default timezone

<?php
date_default_timezone_set('America/Los_Angeles');

$script_tz = date_default_timezone_get();

if (strcmp($script_tz, ini_get('date.timezone'))){
    echo 'Script timezone differs from ini-set timezone.';
} else {
    echo 'Script timezone and ini-set timezone match.';
}
?>

Changelog

Version | Description
5.3.0 | Now throws E_WARNING rather then E_STRICT.
5.1.2 | The function started to validate the timezone_identifier parameter.

See Also

  • date_default_timezone_get() - Gets the default timezone used by all date/time functions in a script
  • List of Supported Timezones

date_default_timezone_get
date_diff
Date/Time Functions


Alias of DateTime::diff

date_default_timezone_set
date_format
Date/Time Functions
PHP Manual

date_diff

(PHP 5 >= 5.3.0)

date_diff — Alias of DateTime::diff

Description

This function is an alias of: DateTime::diff

date_default_timezone_set
date_format
Date/Time Functions


Alias of DateTime::format

date_diff
date_get_last_errors
Date/Time Functions
PHP Manual

date_format

(PHP 5 >= 5.2.0)

date_format — Alias of DateTime::format

Description

This function is an alias of: DateTime::format

date_diff
date_get_last_errors
Date/Time Functions


Alias of DateTime::getLastErrors

date_format
date_interval_create_from_date_string
Date/Time Functions
PHP Manual

date_get_last_errors

(PHP 5 >= 5.3.0)

date_get_last_errors — Alias of DateTime::getLastErrors

Description

This function is an alias of: DateTime::getLastErrors

date_format
date_interval_create_from_date_string
Date/Time Functions


Alias of DateInterval::createFromDateString

date_get_last_errors
date_interval_format
Date/Time Functions
PHP Manual

date_interval_create_from_date_string

(PHP 5 >= 5.3.0)

date_interval_create_from_date_string — Alias of DateInterval::createFromDateString

Description

This function is an alias of: DateInterval::createFromDateString

date_get_last_errors
date_interval_format
Date/Time Functions


Alias of DateInterval::format

date_interval_create_from_date_string
date_isodate_set
Date/Time Functions
PHP Manual

date_interval_format

(PHP 5 >= 5.3.0)

date_interval_format — Alias of DateInterval::format

Description

This function is an alias of: DateInterval::format

date_interval_create_from_date_string
date_isodate_set
Date/Time Functions


Alias of DateTime::setISODate

date_interval_format
date_modify
Date/Time Functions
PHP Manual

date_isodate_set

(PHP 5 >= 5.2.0)

date_isodate_set — Alias of DateTime::setISODate

Description

This function is an alias of: DateTime::setISODate

date_interval_format
date_modify
Date/Time Functions


Alias of DateTime::modify

date_isodate_set
date_offset_get
Date/Time Functions
PHP Manual

date_modify

(PHP 5 >= 5.2.0)

date_modify — Alias of DateTime::modify

Description

This function is an alias of: DateTime::modify

date_isodate_set
date_offset_get
Date/Time Functions


Alias of DateTime::getOffset

date_modify
date_parse_from_format
Date/Time Functions
PHP Manual

date_offset_get

(PHP 5 >= 5.2.0)

date_offset_get — Alias of DateTime::getOffset

Description

This function is an alias of: DateTime::getOffset

date_modify
date_parse_from_format
Date/Time Functions


Returns associative array with detailed info about given date

date_parse_from_format
date_sub
Date/Time Functions
PHP Manual

date_parse

(PHP 5 >= 5.2.0)

date_parse — Returns associative array with detailed info about given date

Description

array date_parse ( string $date )

Parameters

date

Date in format accepted by strtotime().

Return Values

Returns array with information about the parsed date on success or FALSE on failure.

Errors/Exceptions

In case the date format has an error, the element 'errors' will contains the error messages.

Examples

Example #1 A date_parse() example

<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>

The above example will output:

Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array()
    [error_count] => 0
    [errors] => Array()
    [is_localtime] =>
)

See Also

  • getdate() - Get date/time information

date_parse_from_format
date_sub
Date/Time Functions


Get info about given date

date_offset_get
date_parse
Date/Time Functions
PHP Manual

date_parse_from_format

(PHP 5 >= 5.3.0)

date_parse_from_format — Get info about given date

Description

array date_parse_from_format ( string $format , string $date )

Returns associative array with detailed info about given date.

Parameters

format

Format accepted by date() with some extras.

date

String representing the date.

Return Values

Returns associative array with detailed info about given date.

Examples

Example #1 date_parse_from_format() example

<?php
$date = "6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP", $date));
?>

The above example will output:

Array
(
    [year] => 2009
    [month] => 1
    [day] => 6
    [hour] => 13
    [minute] => 0
    [second] => 0
    [fraction] =>
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] => 1
    [zone_type] => 1
    [zone] => -60
    [is_dst] =>
)

date_offset_get
date_parse
Date/Time Functions


Alias of DateTime::sub

date_parse
date_sun_info
Date/Time Functions
PHP Manual

date_sub

(PHP 5 >= 5.3.0)

date_sub — Alias of DateTime::sub

Description

This function is an alias of: DateTime::sub

date_parse
date_sun_info
Date/Time Functions


Returns an array with information about sunset/sunrise and twilight begin/end

date_sub
date_sunrise
Date/Time Functions
PHP Manual

date_sun_info

(PHP 5 >= 5.1.2)

date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end

Description

array date_sun_info ( int $time , float $latitude , float $longitude )

Parameters

time

Timestamp.

latitude

Latitude in degrees.

longitude

Longitude in degrees.

Return Values

Returns array on success or FALSE on failure.

Examples

Example #1 A date_sun_info() example

<?php
$sun_info = date_sun_info(strtotime("2006-12-12"), 31.7667, 35.2333);
foreach ($sun_info as $key => $val) {
    echo "$key: " . date("H:i:s", $val) . "\n";
}
?>

The above example will output:

sunrise: 05:52:11
sunset: 15:41:21
transit: 10:46:46
civil_twilight_begin: 05:24:08
civil_twilight_end: 16:09:24
nautical_twilight_begin: 04:52:25
nautical_twilight_end: 16:41:06
astronomical_twilight_begin: 04:21:32
astronomical_twilight_end: 17:12:00

See Also

  • date_sunrise() - Returns time of sunrise for a given day and location
  • date_sunset() - Returns time of sunset for a given day and location

date_sub
date_sunrise
Date/Time Functions


Returns time of sunrise for a given day and location

date_sun_info
date_sunset
Date/Time Functions
PHP Manual

date_sunrise

(PHP 5)

date_sunrise — Returns time of sunrise for a given day and location

Description

mixed date_sunrise ( int $timestamp [, int $format = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunrise_zenith") [, float $gmt_offset = 0 ]]]]] )

date_sunrise() returns the sunrise time for a given day (specified as a timestamp ) and location.

Parameters

timestamp

The timestamp of the day from which the sunrise time is taken.

format

format constants
constant | description | example
SUNFUNCS_RET_STRING | returns the result as string | 16:46
SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132
SUNFUNCS_RET_TIMESTAMP | returns the result as integer (timestamp) | 1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude

longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude

zenith

Default: date.sunrise_zenith

gmtoffset

Specified in hours.

Return Values

Returns the sunrise time in a specified format on success or FALSE on failure.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 date_sunrise() example

<?php

/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

The above example will output something similar to:

Mon Dec 20 2004, sunrise time : 08:54

See Also

  • date_sunset() - Returns time of sunset for a given day and location

date_sun_info
date_sunset
Date/Time Functions


Returns time of sunset for a given day and location

date_sunrise
date_time_set
Date/Time Functions
PHP Manual

date_sunset

(PHP 5)

date_sunset — Returns time of sunset for a given day and location

Description

mixed date_sunset ( int $timestamp [, int $format = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunset_zenith") [, float $gmt_offset = 0 ]]]]] )

date_sunset() returns the sunset time for a given day (specified as a timestamp ) and location.

Parameters

timestamp

The timestamp of the day from which the sunset time is taken.

format

format constants
constant | description | example
SUNFUNCS_RET_STRING | returns the result as string | 16:46
SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132
SUNFUNCS_RET_TIMESTAMP | returns the result as integer (timestamp) | 1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude

longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude

zenith

Default: date.sunset_zenith

gmtoffset

Specified in hours.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Return Values

Returns the sunset time in a specified format on success or FALSE on failure.

Examples

Example #1 date_sunset() example

<?php

/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

The above example will output something similar to:

Mon Dec 20 2004, sunset time : 18:13

See Also

  • date_sunrise() - Returns time of sunrise for a given day and location

date_sunrise
date_time_set
Date/Time Functions


Alias of DateTime::setTime

date_sunset
date_timestamp_get
Date/Time Functions
PHP Manual

date_time_set

(PHP 5 >= 5.2.0)

date_time_set — Alias of DateTime::setTime

Description

This function is an alias of: DateTime::setTime

date_sunset
date_timestamp_get
Date/Time Functions


Alias of DateTime::getTimestamp

date_time_set
date_timestamp_set
Date/Time Functions
PHP Manual

date_timestamp_get

(PHP 5 >= 5.3.0)

date_timestamp_get — Alias of DateTime::getTimestamp

Description

This function is an alias of: DateTime::getTimestamp

date_time_set
date_timestamp_set
Date/Time Functions


Alias of DateTime::setTimestamp

date_timestamp_get
date_timezone_get
Date/Time Functions
PHP Manual

date_timestamp_set

(PHP 5 >= 5.3.0)

date_timestamp_set — Alias of DateTime::setTimestamp

Description

This function is an alias of: DateTime::setTimestamp

date_timestamp_get
date_timezone_get
Date/Time Functions


Alias of DateTime::getTimezone

date_timestamp_set
date_timezone_set
Date/Time Functions
PHP Manual

date_timezone_get

(PHP 5 >= 5.2.0)

date_timezone_get — Alias of DateTime::getTimezone

Description

This function is an alias of: DateTime::getTimezone

date_timestamp_set
date_timezone_set
Date/Time Functions


Alias of DateTime::setTimezone

date_timezone_get
date
Date/Time Functions
PHP Manual

date_timezone_set

(PHP 5 >= 5.2.0)

date_timezone_set — Alias of DateTime::setTimezone

Description

This function is an alias of: DateTime::setTimezone

date_timezone_get
date
Date/Time Functions


Returns or sets the AUTOCOMMIT state for a database connection

IBM DB2 Functions
db2_bind_param
IBM DB2 Functions
PHP Manual

db2_autocommit

(PECL ibm_db2 >= 1.0.0)

db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection

Description

mixed db2_autocommit ( resource $connection [, bool $value ] )

Sets or gets the AUTOCOMMIT behavior of the specified connection resource.

Parameters

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

value

One of the following constants:

DB2_AUTOCOMMIT_OFF

Turns AUTOCOMMIT off.

DB2_AUTOCOMMIT_ON

Turns AUTOCOMMIT on.

Return Values

When db2_autocommit() receives only the connection parameter, it returns the current state of AUTOCOMMIT for the requested connection as an integer value. A value of 0 indicates that AUTOCOMMIT is off, while a value of 1 indicates that AUTOCOMMIT is on.

When db2_autocommit() receives both the connection parameter and autocommit parameter, it attempts to set the AUTOCOMMIT state of the requested connection to the corresponding state. Returns TRUE on success or FALSE on failure.

Examples

Example #1 Retrieving the AUTOCOMMIT value for a connection

In the following example, a connection which has been created with AUTOCOMMIT turned off is tested with the db2_autocommit() function.

<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
$ac = db2_autocommit($conn);
if ($ac == 0) {
    print "$ac -- AUTOCOMMIT is off.";
} else {
    print "$ac -- AUTOCOMMIT is on.";
}
?>

The above example will output:

0 -- AUTOCOMMIT is off.

Example #2 Setting the AUTOCOMMIT value for a connection

In the following example, a connection which was initially created with AUTOCOMMIT turned off has its behavior changed to turn AUTOCOMMIT on.

<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);

// Turn AUTOCOMMIT on
$rc = db2_autocommit($conn, DB2_AUTOCOMMIT_ON);
if ($rc) {
    print "Turning AUTOCOMMIT on succeeded.\n";
}

// Check AUTOCOMMIT state
$ac = db2_autocommit($conn);
if ($ac == 0) {
    print "$ac -- AUTOCOMMIT is off.";
} else {
    print "$ac -- AUTOCOMMIT is on.";
}
?>

The above example will output:

Turning AUTOCOMMIT on succeeded.
1 -- AUTOCOMMIT is on.

See Also

  • db2_connect() - Returns a connection to a database
  • db2_pconnect() - Returns a persistent connection to a database

IBM DB2 Functions
db2_bind_param
IBM DB2 Functions


Binds a PHP variable to an SQL statement parameter

db2_autocommit
db2_client_info
IBM DB2 Functions
PHP Manual

db2_bind_param

(PECL ibm_db2 >= 1.0.0)

db2_bind_param — Binds a PHP variable to an SQL statement parameter

Description

bool db2_bind_param ( resource $stmt , int $parameter-number , string $variable-name [, int $parameter-type [, int $data-type = 0 [, int $precision = -1 [, int $scale = 0 ]]]] )

Binds a PHP variable to an SQL statement parameter in a statement resource returned by db2_prepare(). This function gives you more control over the parameter type, data type, precision, and scale for the parameter than simply passing the variable as part of the optional input array to db2_execute().

Parameters

stmt

A prepared statement returned from db2_prepare().

parameter-number

Specifies the 1-indexed position of the parameter in the prepared statement.

variable-name

A string specifying the name of the PHP variable to bind to the parameter specified by parameter-number .

parameter-type

A constant specifying whether the PHP variable should be bound to the SQL parameter as an input parameter (DB2_PARAM_IN), an output parameter (DB2_PARAM_OUT), or as a parameter that accepts input and returns output (DB2_PARAM_INOUT). To avoid memory overhead, you can also specify DB2_PARAM_FILE to bind the PHP variable to the name of a file that contains large object (BLOB, CLOB, or DBCLOB) data.

data-type

A constant specifying the SQL data type that the PHP variable should be bound as: one of DB2_BINARY, DB2_CHAR, DB2_DOUBLE, or DB2_LONG .

precision

Specifies the precision with which the variable should be bound to the database. This parameter can also be used for retrieving XML output values from stored procedures. A non-negative value specifies the maximum size of the XML data that will be retrieved from the database. If this parameter is not used, a default of 1MB will be assumed for retrieving the XML output value from the stored procedure.

scale

Specifies the scale with which the variable should be bound to the database.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Binding PHP variables to a prepared statement

The SQL statement in the following example uses two input parameters in the WHERE clause. We call db2_bind_param() to bind two PHP variables to the corresponding SQL parameters. Notice that the PHP variables do not have to be declared or assigned before the call to db2_bind_param(); in the example, $lower_limit is assigned a value before the call to db2_bind_param(), but $upper_limit is assigned a value after the call to db2_bind_param(). The variables must be bound and, for parameters that accept input, must have any value assigned, before calling db2_execute().

<?php

$sql = 'SELECT name, breed, weight FROM animals
    WHERE weight > ? AND weight < ?';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);

// We can declare the variable before calling db2_bind_param()
$lower_limit = 1;

db2_bind_param($stmt, 1, "lower_limit", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "upper_limit", DB2_PARAM_IN);

// We can also declare the variable after calling db2_bind_param()
$upper_limit = 15.0;

if (db2_execute($stmt)) {
    while ($row = db2_fetch_array($stmt)) {
        print "{$row[0]}, {$row[1]}, {$row[2]}\n";
    }
}
?>

The above example will output:

Pook, cat, 3.2
Rickety Ride, goat, 9.7
Peaches, dog, 12.3

Example #2 Calling stored procedures with IN and OUT parameters

The stored procedure match_animal in the following example accepts three different parameters:

  1. an input (IN) parameter that accepts the name of the first animal as input

  2. an input-output (INOUT) parameter that accepts the name of the second animal as input and returns the string TRUE if an animal in the database matches that name

  3. an output (OUT) parameter that returns the sum of the weight of the two identified animals

In addition, the stored procedure returns a result set consisting of the animals listed in alphabetic order starting at the animal corresponding to the input value of the first parameter and ending at the animal corresponding to the input value of the second parameter.

<?php

$sql = 'CALL match_animal(?, ?, ?)';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);

$name = "Peaches";
$second_name = "Rickety Ride";
$weight = 0;

db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "second_name", DB2_PARAM_INOUT);
db2_bind_param($stmt, 3, "weight", DB2_PARAM_OUT);

print "Values of bound parameters _before_ CALL:\n";
print "  1: {$name} 2: {$second_name} 3: {$weight}\n\n";

if (db2_execute($stmt)) {
    print "Values of bound parameters _after_ CALL:\n";
    print "  1: {$name} 2: {$second_name} 3: {$weight}\n\n";

    print "Results:\n";
    while ($row = db2_fetch_array($stmt)) {
        print "  {$row[0]}, {$row[1]}, {$row[2]}\n";
    }
}
?>

The above example will output:

Values of bound parameters _before_ CALL:
  1: Peaches 2: Rickety Ride 3: 0

Values of bound parameters _after_ CALL:
  1: Peaches 2: TRUE 3: 22

Results:
  Peaches, dog, 12.3
  Pook, cat, 3.2
  Rickety Ride, goat, 9.7

Example #3 Inserting a binary large object (BLOB) directly from a file

The data for large objects are typically stored in files, such as XML documents or audio files. Rather than reading an entire file into a PHP variable, and then binding that PHP variable into an SQL statement, you can avoid some memory overhead by binding the file directly to the input parameter of your SQL statement. The following example demonstrates how to bind a file directly into a BLOB column.

<?php
$stmt = db2_prepare($conn, "INSERT INTO animal_pictures(picture) VALUES (?)");

$picture = "/opt/albums/spook/grooming.jpg";
$rc = db2_bind_param($stmt, 1, "picture", DB2_PARAM_FILE);
$rc = db2_execute($stmt);
?>

See Also

  • db2_execute() - Executes a prepared SQL statement
  • db2_prepare() - Prepares an SQL statement to be executed

db2_autocommit
db2_client_info
IBM DB2 Functions


Returns an object with properties that describe the DB2 database client

db2_bind_param
db2_close
IBM DB2 Functions
PHP Manual

db2_client_info

(PECL ibm_db2 >= 1.1.1)

db2_client_info — Returns an object with properties that describe the DB2 database client

Description

object db2_client_info ( resource $connection )

This function returns an object with read-only properties that return information about the DB2 database client. The following table lists the DB2 client properties:

DB2 client properties
Property name | Return type | Description
APPL_CODEPAGE | int | The application code page.
CONN_CODEPAGE | int | The code page for the current connection.
DATA_SOURCE_NAME | string | The data source name (DSN) used to create the current connection to the database.
DRIVER_NAME | string | The name of the library that implements the DB2 Call Level Interface (CLI) specification.
DRIVER_ODBC_VER | string | The version of ODBC that the DB2 client supports. This returns a string "MM.mm" where MM is the major version and mm is the minor version. The DB2 client always returns "03.51".
DRIVER_VER | string | The version of the client, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1.
ODBC_SQL_CONFORMANCE string

The level of ODBC SQL grammar supported by the client:

MINIMUM

Supports the minimum ODBC SQL grammar.

CORE

Supports the core ODBC SQL grammar.

EXTENDED

Supports extended ODBC SQL grammar.

ODBC_VER | string | The version of ODBC that the ODBC driver manager supports. This returns a string "MM.mm.rrrr" where MM is the major version, mm is the minor version, and rrrr is the release. The DB2 client always returns "03.01.0000".

Parameters

connection

Specifies an active DB2 client connection.

Return Values

Returns an object on a successful call. Returns FALSE on failure.

Examples

Example #1 A db2_client_info() example

To retrieve information about the client, you must pass a valid database connection resource to db2_client_info().

<?php
$conn = db2_connect( 'SAMPLE', 'db2inst1', 'ibmdb2' );
$client = db2_client_info( $conn );

if ($client) {
    echo "DRIVER_NAME: ";           var_dump( $client->DRIVER_NAME );
    echo "DRIVER_VER: ";            var_dump( $client->DRIVER_VER );
    echo "DATA_SOURCE_NAME: ";      var_dump( $client->DATA_SOURCE_NAME );
    echo "DRIVER_ODBC_VER: ";       var_dump( $client->DRIVER_ODBC_VER );
    echo "ODBC_VER: ";              var_dump( $client->ODBC_VER );
    echo "ODBC_SQL_CONFORMANCE: ";  var_dump( $client->ODBC_SQL_CONFORMANCE );
    echo "APPL_CODEPAGE: ";         var_dump( $client->APPL_CODEPAGE );
    echo "CONN_CODEPAGE: ";         var_dump( $client->CONN_CODEPAGE );
}
else {
    echo "Error retrieving client information.
     Perhaps your database connection was invalid.";
}
db2_close($conn);

?>

The above example will output:

DRIVER_NAME: string(8) "libdb2.a"
DRIVER_VER: string(10) "08.02.0001"
DATA_SOURCE_NAME: string(6) "SAMPLE"
DRIVER_ODBC_VER: string(5) "03.51"
ODBC_VER: string(10) "03.01.0000"
ODBC_SQL_CONFORMANCE: string(8) "EXTENDED"
APPL_CODEPAGE: int(819)
CONN_CODEPAGE: int(819)

See Also

  • db2_server_info() - Returns an object with properties that describe the DB2 database server

db2_bind_param
db2_close
IBM DB2 Functions


Closes a database connection

db2_client_info
db2_column_privileges
IBM DB2 Functions
PHP Manual

db2_close

(PECL ibm_db2 >= 1.0.0)

db2_close — Closes a database connection

Description

bool db2_close ( resource $connection )

This function closes a DB2 client connection created with db2_connect() and returns the corresponding resources to the database server.

If you attempt to close a persistent DB2 client connection created with db2_pconnect(), the close request is ignored and the persistent DB2 client connection remains available for the next caller.

Parameters

connection

Specifies an active DB2 client connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a connection

The following example demonstrates a successful attempt to close a connection to an IBM DB2, Cloudscape, or Apache Derby database.

<?php
$conn = db2_connect('SAMPLE', 'db2inst1', 'ibmdb2');
$rc = db2_close($conn);
if ($rc) {
    echo "Connection was successfully closed.";
}
?>

The above example will output:

Connection was successfully closed.

See Also

  • db2_connect() - Returns a connection to a database
  • db2_pclose() - Closes a persistent database connection
  • db2_pconnect() - Returns a persistent connection to a database

db2_client_info
db2_column_privileges
IBM DB2 Functions


Returns a result set listing the columns and associated privileges for a table

db2_close
db2_columns
IBM DB2 Functions
PHP Manual

db2_column_privileges

(PECL ibm_db2 >= 1.0.0)

db2_column_privileges — Returns a result set listing the columns and associated privileges for a table

Description

resource db2_column_privileges ( resource $connection [, string $qualifier [, string $schema [, string $table-name [, string $column-name ]]]] )

Returns a result set listing the columns and associated privileges for a table.

Parameters

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. To match all schemas, pass NULL or an empty string.

table-name

The name of the table or view. To match all tables in the database, pass NULL or an empty string.

column-name

The name of the column. To match all columns in the table, pass NULL or an empty string.

Return Values

Returns a statement resource with a result set containing rows describing the column privileges for columns matching the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema.
TABLE_NAME | Name of the table or view.
COLUMN_NAME | Name of the column.
GRANTOR | Authorization ID of the user who granted the privilege.
GRANTEE | Authorization ID of the user to whom the privilege was granted.
PRIVILEGE | The privilege for the column.
IS_GRANTABLE | Whether the GRANTEE is permitted to grant this privilege to other users.

See Also

  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_close
db2_columns
IBM DB2 Functions


Returns a result set listing the columns and associated metadata for a table

db2_column_privileges
db2_commit
IBM DB2 Functions
PHP Manual

db2_columns

(PECL ibm_db2 >= 1.0.0)

db2_columns — Returns a result set listing the columns and associated metadata for a table

Description

resource db2_columns ( resource $connection [, string $qualifier [, string $schema [, string $table-name [, string $column-name ]]]] )

Returns a result set listing the columns and associated metadata for a table.

Parameters

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. To match all schemas, pass '%'.

table-name

The name of the table or view. To match all tables in the database, pass NULL or an empty string.

column-name

The name of the column. To match all columns in the table, pass NULL or an empty string.

Return Values

Returns a statement resource with a result set containing rows describing the columns matching the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema.
TABLE_NAME | Name of the table or view.
COLUMN_NAME | Name of the column.
DATA_TYPE | The SQL data type for the column represented as an integer value.
TYPE_NAME | A string representing the data type for the column.
COLUMN_SIZE | An integer value representing the size of the column.
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column.
DECIMAL_DIGITS | The scale of the column, or NULL where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable).
NULLABLE | An integer value representing whether the column is nullable or not.
REMARKS | Description of the column.
COLUMN_DEF | Default value for the column.
SQL_DATA_TYPE | An integer value representing the size of the column.
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or NULL for SQL data types to which this does not apply.
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type column, which matches COLUMN_SIZE for single-byte character set data, or NULL for non-character data types.
ORDINAL_POSITION | The 1-indexed position of the column in the table.
IS_NULLABLE | A string value where 'YES' means that the column is nullable and 'NO' means that the column is not nullable.

See Also

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_column_privileges
db2_commit
IBM DB2 Functions


Commits a transaction

db2_columns
db2_conn_error
IBM DB2 Functions
PHP Manual

db2_commit

(PECL ibm_db2 >= 1.0.0)

db2_commit — Commits a transaction

Description

bool db2_commit ( resource $connection )

Commits an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_commit() is not necessary unless AUTOCOMMIT has been turned off for the connection resource.

Note: If the specified connection resource is a persistent connection, all transactions in progress for all applications using that persistent connection will be committed. For this reason, persistent connections are not recommended for use in applications that require transactions.

Parameters

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
  • db2_rollback() - Rolls back a transaction

db2_columns
db2_conn_error
IBM DB2 Functions


Returns a string containing the SQLSTATE returned by the last connection attempt

db2_commit
db2_conn_errormsg
IBM DB2 Functions
PHP Manual

db2_conn_error

(PECL ibm_db2 >= 1.0.0)

db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt

Description

string db2_conn_error ([ resource $connection ] )

db2_conn_error() returns an SQLSTATE value representing the reason the last attempt to connect to a database failed. As db2_connect() returns FALSE in the event of a failed connection attempt, you do not pass any parameters to db2_conn_error() to retrieve the SQLSTATE value.

If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the SQLSTATE value for a specific connection.

To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value ' . You can also call db2_conn_errormsg() to retrieve an explicit error message and the associated SQLCODE value.

Parameters

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Return Values

Returns the SQLSTATE value resulting from a failed connection attempt. Returns an empty string if there is no error associated with the last connection attempt.

Examples

Example #1 Retrieving an SQLSTATE value for a failed connection attempt

The following example demonstrates how to return an SQLSTATE value after deliberately passing invalid parameters to db2_connect().

<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
    print "SQLSTATE value: " . db2_conn_error();
}
?>

The above example will output:

SQLSTATE value: 08001

See Also

  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_connect() - Returns a connection to a database
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

db2_commit
db2_conn_errormsg
IBM DB2 Functions


Returns the last connection error message and SQLCODE value

db2_conn_error
db2_connect
IBM DB2 Functions
PHP Manual

db2_conn_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_conn_errormsg — Returns the last connection error message and SQLCODE value

Description

string db2_conn_errormsg ([ resource $connection ] )

db2_conn_errormsg() returns an error message and SQLCODE value representing the reason the last database connection attempt failed. As db2_connect() returns FALSE in the event of a failed connection attempt, do not pass any parameters to db2_conn_errormsg() to retrieve the associated error message and SQLCODE value.

If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the associated error message and SQLCODE value for a specific connection.

Parameters

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Return Values

Returns a string containing the error message and SQLCODE value resulting from a failed connection attempt. If there is no error associated with the last connection attempt, db2_conn_errormsg() returns an empty string.

Examples

Example #1 Retrieving the error message returned by a failed connection attempt

The following example demonstrates how to return an error message and SQLCODE value after deliberately passing invalid parameters to db2_connect().

<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
    print db2_conn_errormsg();
}
?>

The above example will output:

[IBM][CLI Driver] SQL1013N  The database alias name
or database name "BADNAME" could not be found.  SQLSTATE=42705
 SQLCODE=-1013

See Also

  • db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_connect() - Returns a connection to a database
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

db2_conn_error
db2_connect
IBM DB2 Functions


Returns a connection to a database

db2_conn_errormsg
db2_cursor_type
IBM DB2 Functions
PHP Manual

db2_connect

(PECL ibm_db2 >= 1.0.0)

db2_connect — Returns a connection to a database

Description

resource db2_connect ( string $database , string $username , string $password [, array $options ] )

Creates a new connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.

Parameters

database

For a cataloged connection to a database, database represents the database alias in the DB2 client catalog.

For an uncataloged connection to a database, database represents a complete connection string in the following format:

DATABASE=database
;HOSTNAME=hostname
;PORT=port
;PROTOCOL=TCPIP;UID=username
;PWD=password
;
where the parameters represent the following values:

database

The name of the database.

hostname

The hostname or IP address of the database server.

port

The TCP/IP port on which the database is listening for requests.

username

The username with which you are connecting to the database.

password

The password with which you are connecting to the database.

username

The username with which you are connecting to the database.

For uncataloged connections, you must pass a NULL value or empty string.

password

The password with which you are connecting to the database.

For uncataloged connections, you must pass a NULL value or empty string.

options

An associative array of connection options that affect the behavior of the connection, where valid array keys include:

autocommit

Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.

Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.

DB2_ATTR_CASE

Passing the DB2_CASE_NATURAL value specifies that column names are returned in natural case.

Passing the DB2_CASE_LOWER value specifies that column names are returned in lower case.

Passing the DB2_CASE_UPPER value specifies that column names are returned in upper case.

CURSOR

Passing the DB2_FORWARD_ONLY value specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.

Passing the DB2_SCROLLABLE value specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.

The following new option is available in ibm_db2 version 1.7.0 and later.

trustedcontext

Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns trusted context on for this connection handle. This parameter cannot be set using db2_set_option().

This key works only if the database is cataloged (even if the database is local), or if you specify the full DSN when you create the connection.

To catalog the database, use following commands:

db2 catalog tcpip node loopback remote <SERVERNAME> server <SERVICENAME>
db2 catalog database <LOCALDBNAME> as <REMOTEDBNAME> at node loopback
db2 "update dbm cfg using svcename <SERVICENAME>"
db2set DB2COMM=TCPIP

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later.

i5_lib

A character value that indicates the default library that will be used for resolving unqualified file references. This is not valid if the connection is using system naming mode.

i5_naming

DB2_I5_NAMING_ON value turns on DB2 UDB CLI iSeries system naming mode. Files are qualified using the slash (/) delimiter. Unqualified files are resolved using the library list for the job.

DB2_I5_NAMING_OFF value turns off DB2 UDB CLI default naming mode, which is SQL naming. Files are qualified using the period (.) delimiter. Unqualified files are resolved using either the default library or the current user ID.

i5_commit

The i5_commit attribute should be set before the db2_connect(). If the value is changed after the connection has been established, and the connection is to a remote data source, the change does not take effect until the next successful db2_connect() for the connection handle.

Note: The php.ini setting ibm_db2.i5_allow_commit ==0 or DB2_I5_TXN_NO_COMMIT is the default, but may be overridden with the i5_commit option.

DB2_I5_TXN_NO_COMMIT - Commitment control is not used.

DB2_I5_TXN_READ_UNCOMMITTED - Dirty reads, nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_READ_COMMITTED - Dirty reads are not possible. Nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_REPEATABLE_READ - Dirty reads and nonrepeatable reads are not possible. Phantoms are possible.

DB2_I5_TXN_SERIALIZABLE - Transactions are serializable. Dirty reads, non-repeatable reads, and phantoms are not possible

i5_query_optimize

DB2_FIRST_IO All queries are optimized with the goal of returning the first page of output as fast as possible. This goal works well when the output is controlled by a user who is most likely to cancel the query after viewing the first page of output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause.

DB2_ALL_IO All queries are optimized with the goal of running the entire query to completion in the shortest amount of elapsed time. This is a good option when the output of a query is being written to a file or report, or the interface is queuing the output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. This is the default.

i5_dbcs_alloc

DB2_I5_DBCS_ALLOC_ON value turns on DB2 6X allocation scheme for DBCS translation column size growth.

DB2_I5_DBCS_ALLOC_OFF value turns off DB2 6X allocation scheme for DBCS translation column size growth.

Note: php.ini setting ibm_db2.i5_dbcs_alloc ==0 or DB2_I5_DBCS_ALLOC_OFF is the default, but may be overridden with the i5_dbcs_alloc option.

i5_date_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) date format yyyy-mm-dd is used. This is the default.

DB2_I5_FMT_USA - The United States date format mm/dd/yyyy is used.

DB2_I5_FMT_EUR - The European date format dd.mm.yyyy is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard date format yyyy-mm-dd is used.

DB2_I5_FMT_MDY - The date format mm/dd/yyyy is used.

DB2_I5_FMT_DMY - The date format dd/mm/yyyy is used.

DB2_I5_FMT_YMD - The date format yy/mm/dd is used.

DB2_I5_FMT_JUL - The Julian date format yy/ddd is used.

DB2_I5_FMT_JOB - The job default is used.

i5_date_sep

DB2_I5_SEP_SLASH - A slash ( / ) is used as the date separator. This is the default.

DB2_I5_SEP_DASH - A dash ( - ) is used as the date separator.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the date separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the date separator.

DB2_I5_SEP_BLANK - A blank is used as the date separator.

DB2_I5_SEP_JOB - The job default is used

i5_time_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) time format hh.mm.ss is used. This is the default.

DB2_I5_FMT_USA - The United States time format hh:mmxx is used, where xx is AM or PM.

DB2_I5_FMT_EUR - The European time format hh.mm.ss is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard time format hh:mm:ss is used.

DB2_I5_FMT_HMS - The hh:mm:ss format is used.

i5_time_sep

DB2_I5_SEP_COLON - A colon ( : ) is used as the time separator. This is the default.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the time separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the time separator.

DB2_I5_SEP_BLANK - A blank is used as the time separator.

DB2_I5_SEP_JOB - The job default is used.

i5_decimal_sep

DB2_I5_SEP_PERIOD - A period ( . ) is used as the decimal separator. This is the default.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the decimal separator.

DB2_I5_SEP_JOB - The job default is used.

The following new i5/OS option is available in ibm_db2 version 1.8.0 and later.

i5_libl

A character value that indicates the library list that will be used for resolving unqualified file references. Specify the library list elements separated by blanks 'i5_libl'=>"MYLIB YOURLIB ANYLIB".

Note: i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

Return Values

Returns a connection handle resource if the connection attempt is successful. If the connection attempt fails, db2_connect() returns FALSE.

Examples

Example #1 Creating a cataloged connection

Cataloged connections require you to have previously cataloged the target database through the DB2 Command Line Processor (CLP) or DB2 Configuration Assistant.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

$conn = db2_connect($database, $user, $password);

if ($conn) {
    echo "Connection succeeded.";
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

The above example will output:

Connection succeeded.

Example #2 Creating an uncataloged connection

An uncataloged connection enables you to dynamically connect to a database.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$hostname = 'localhost';
$port = 50000;

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
  "HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

if ($conn) {
    echo "Connection succeeded.";
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

The above example will output:

Connection succeeded.

Example #3 Creating a connection with autocommit off by default

Passing an array of options to db2_connect() enables you to modify the default behavior of the connection handle.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);

$conn = db2_connect($database, $user, $password, $options);

if ($conn) {
    echo "Connection succeeded.\n";
    if (db2_autocommit($conn)) {
         echo "Autocommit is on.\n";
    }
    else {
         echo "Autocommit is off.\n";
    }
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

The above example will output:

Connection succeeded.
Autocommit is off.

Example #4 i5/OS best performance

To achieve best performance for your i5/OS ibm_db2 1.5.1 PHP application use the default host, userid, and password for your db2_connect().

<?php
  $library = "ADC";
  $i5 = db2_connect("", "", "", array("i5_lib"=>"qsys2"));
  $result = db2_exec($i5,
       "select * from systables where table_schema = '$library'");
  while ($row = db2_fetch_both($result)) {
     echo $row['TABLE_NAME']."</br>";
  }
  db2_close($i5);
?>

The above example will output:

ANIMALS
NAMES
PICTURES

Example #5 Using trusted context

The following example shows how to enable trusted context, switch users, and get the current user ID.

<?php

$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";

$tc_user = "tcuser";
$tc_pass = "tcpassword";

$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;
  PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);

$tc_conn = db2_connect($dsn, "", "", $options);
if($tc_conn) {
    echo "Explicit trusted connection succeeded.\n";

    if(db2_get_option($tc_conn, "trustedcontext")) {
        $userBefore = db2_get_option($tc_conn, "trusted_user");

        //Do some work as user 1.

        //Switching to trusted user.
        $parameters = array("trusted_user" => $tc_user,
          "trusted_password" => $tcuser_pass);
        $res = db2_set_option ($tc_conn, $parameters, 1);

        $userAfter = db2_get_option($tc_conn, "trusted_user");
        //Do more work as trusted user.

        if($userBefore != $userAfter) {
            echo "User has been switched." . "\n";
        }
    }

    db2_close($tc_conn);
}
else {
    echo "Explicit trusted connection failed.\n";
}
?>

The above example will output:

Explicit trusted connection succeeded.
User has been switched.

See Also

  • db2_close() - Closes a database connection
  • db2_pconnect() - Returns a persistent connection to a database

db2_conn_errormsg
db2_cursor_type
IBM DB2 Functions


Returns the cursor type used by a statement resource

db2_connect
db2_escape_string
IBM DB2 Functions
PHP Manual

db2_cursor_type

(PECL ibm_db2 >= 1.0.0)

db2_cursor_type — Returns the cursor type used by a statement resource

Description

int db2_cursor_type ( resource $stmt )

Returns the cursor type used by a statement resource. Use this to determine if you are working with a forward-only cursor or scrollable cursor.

Parameters

stmt

A valid statement resource.

Return Values

Returns either DB2_FORWARD_ONLY if the statement resource uses a forward-only cursor or DB2_SCROLLABLE if the statement resource uses a scrollable cursor.

See Also

  • db2_prepare() - Prepares an SQL statement to be executed

db2_connect
db2_escape_string
IBM DB2 Functions


Used to escape certain characters

db2_cursor_type
db2_exec
IBM DB2 Functions
PHP Manual

db2_escape_string

(PECL ibm_db2 >= 1.6.0)

db2_escape_string — Used to escape certain characters

Description

string db2_escape_string ( string $string_literal )

Prepends backslashes to special characters in the string argument.

Parameters

string_literal

The string that contains special characters that need to be modified. Characters that are prepended with a backslash are \x00, \n, \r, \, ', " and \x1a.

Return Values

Returns string_literal with the special characters noted above prepended with backslashes.

Examples

Example #1 A db2_escape_string() example

Result of using the db2_escape_string() function

<?php

$conn = db2_connect($database, $user, $password);

if ($conn) {
    $str[0] = "All characters: \x00 , \n , \r , \ , ' , \" , \x1a .";
    $str[1] = "Backslash (\). Single quote ('). Double quote (\")";
    $str[2] = "The NULL character \0 must be quoted as well";
    $str[3] = "Intersting characters: \x1a , \x00 .";
    $str[4] = "Nothing to quote";
    $str[5] = 200676;
    $str[6] = "";

    foreach( $str as $string ) {
        echo "db2_escape_string: " . db2_escape_string($string). "\n";
    }
}
?>

The above example will output:

db2_escape_string: All characters: \0 , \n , \r , \\ , \' , \" , \Z .
db2_escape_string: Backslash (\\). Single quote (\'). Double quote (\")
db2_escape_string: The NULL character \0 must be quoted as well
db2_escape_string: Intersting characters: \Z , \0 .
db2_escape_string: Nothing to quote
db2_escape_string: 200676
db2_escape_string:

See Also

  • db2_prepare() - Prepares an SQL statement to be executed

db2_cursor_type
db2_exec
IBM DB2 Functions


Executes an SQL statement directly

db2_escape_string
db2_execute
IBM DB2 Functions
PHP Manual

db2_exec

(PECL ibm_db2 >= 1.0.0)

db2_exec — Executes an SQL statement directly

Description

resource db2_exec ( resource $connection , string $statement [, array $options ] )

Executes an SQL statement directly.

If you plan to interpolate PHP variables into the SQL statement, understand that this is one of the more common security exposures. Consider calling db2_prepare() to prepare an SQL statement with parameter markers for input values. Then you can call db2_execute() to pass in the input values and avoid SQL injection attacks.

If you plan to repeatedly issue the same SQL statement with different parameters, consider calling db2_prepare() and db2_execute() to enable the database server to reuse its access plan and increase the efficiency of your database access.

Parameters

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

statement

An SQL statement. The statement cannot contain any parameter markers.

options

An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.

For a description of valid statement options, see db2_set_option().

Return Values

Returns a statement resource if the SQL statement was issued successfully, or FALSE if the database failed to execute the SQL statement.

Examples

Example #1 Creating a table with db2_exec()

The following example uses db2_exec() to issue a set of DDL statements in the process of creating a table.

<?php
$conn = db2_connect($database, $user, $password);

// Create the test table
$create = 'CREATE TABLE animals (id INTEGER, breed VARCHAR(32),
    name CHAR(16), weight DECIMAL(7,2))';
$result = db2_exec($conn, $create);
if ($result) {
    print "Successfully created the table.\n";
}

// Populate the test table
$animals = array(
    array(0, 'cat', 'Pook', 3.2),
    array(1, 'dog', 'Peaches', 12.3),
    array(2, 'horse', 'Smarty', 350.0),
    array(3, 'gold fish', 'Bubbles', 0.1),
    array(4, 'budgerigar', 'Gizmo', 0.2),
    array(5, 'goat', 'Rickety Ride', 9.7),
    array(6, 'llama', 'Sweater', 150)
);

foreach ($animals as $animal) {
    $rc = db2_exec($conn, "INSERT INTO animals (id, breed, name, weight)
      VALUES ({$animal[0]}, '{$animal[1]}', '{$animal[2]}', {$animal[3]})");
    if ($rc) {
        print "Insert... ";
    }
}
?>

The above example will output:

Successfully created the table.
Insert... Insert... Insert... Insert... Insert... Insert... Insert...

Example #2 Executing a SELECT statement with a scrollable cursor

The following example demonstrates how to request a scrollable cursor for an SQL statement issued by db2_exec().

<?php
$conn = db2_connect($database, $user, $password);
$sql = "SELECT name FROM animals
    WHERE weight < 10.0
    ORDER BY name";
if ($conn) {
    require_once('prepare.inc');
    $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
    while ($row = db2_fetch_array($stmt)) {
        print "$row[0]\n";
    }
}
?>

The above example will output:

Bubbles
Gizmo
Pook
Rickety Ride

Example #3 Returning XML data as a SQL ResultSet

The following example demonstrates how to work with documents stored in a XML column using the SAMPLE database. Using some pretty simple SQL/XML, this example returns some of the nodes in a XML document in a SQL ResultSet format that most users are familiar with.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = 'SELECT * FROM XMLTABLE(
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
    COLUMNS
    "CID" VARCHAR (50) PATH \'@Cid\',
    "NAME" VARCHAR (50) PATH \'name\',
    "PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
    ) AS T
    WHERE NAME = \'Kathy Smith\'
    ';
$stmt = db2_exec($conn, $query);

while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE\n");
}
db2_close($conn);

?>

The above example will output:

1000     Kathy Smith     416-555-1358
1001     Kathy Smith     905-555-7258

Example #4 Performing a "JOIN" with XML data

The following example works with documents stored in 2 different XML columns in the SAMPLE database. It creates 2 temporary tables from the XML documents from 2 different columns and returns a SQL ResultSet with information regarding shipping status for the customer.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
    SELECT A.CID, A.NAME, A.PHONE, C.PONUM, C.STATUS
    FROM
    XMLTABLE(
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
    COLUMNS
    "CID" BIGINT PATH \'@Cid\',
    "NAME" VARCHAR (50) PATH \'name\',
    "PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
    ) as A,
    PURCHASEORDER AS B,
    XMLTABLE (
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("PURCHASEORDER.PORDER")/PurchaseOrder\'
    COLUMNS
    "PONUM"  BIGINT PATH \'@PoNum\',
    "STATUS" VARCHAR (50) PATH \'@Status\'
    ) as C
    WHERE A.CID = B.CUSTID AND
    B.POID = C.PONUM AND
    A.NAME = \'Kathy Smith\'
';

$stmt = db2_exec($conn, $query);

while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE     $row->PONUM     $row->STATUS\n");
}

db2_close($conn);

?>

The above example will output:

1001     Kathy Smith     905-555-7258     5002     Shipped

Example #5 Returning SQL data as part of a larger XML document

The following example works with a portion of the PRODUCT.DESCRIPTION documents in the SAMPLE database. It creates a XML document containing product description (XML data) and pricing info (SQL data).

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
    declare boundary-space strip;
    declare default element namespace "http://posample.org";
    <promoList> {
    for $prod in $doc/product
    where $prod/description/price < 10.00
    order by $prod/description/price ascending
    return(
        <promoitem> {
        $prod,
        <startdate> {$start} </startdate>,
        <enddate> {$end} </enddate>,
        <promoprice> {$promo} </promoprice>
        } </promoitem>
    )
    } </promoList>
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = \'100-100-01\'
';

$stmt = db2_exec($conn, $query);

while($row = db2_fetch_array($stmt)){
    printf("$row[0]\n");
}
db2_close($conn);

?>

The above example will output:

<promoList xmlns="http://posample.org">
    <promoitem>
    <product pid="100-100-01">
        <description>
            <name>Snow Shovel, Basic 22 inch</name>
            <details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
            <price>9.99</price>
            <weight>1 kg</weight>
        </description>
    </product>
    <startdate>2004-11-19</startdate>
    <enddate>2004-12-19</enddate>
    <promoprice>7.25</promoprice>
    </promoitem>
</promoList>

See Also

  • db2_execute() - Executes a prepared SQL statement
  • db2_prepare() - Prepares an SQL statement to be executed

db2_escape_string
db2_execute
IBM DB2 Functions


Executes a prepared SQL statement

db2_exec
db2_fetch_array
IBM DB2 Functions
PHP Manual

db2_execute

(PECL ibm_db2 >= 1.0.0)

db2_execute — Executes a prepared SQL statement

Description

bool db2_execute ( resource $stmt [, array $parameters ] )

db2_execute() executes an SQL statement that was prepared by db2_prepare().

If the SQL statement returns a result set, for example, a SELECT statement or a CALL to a stored procedure that returns one or more result sets, you can retrieve a row as an array from the stmt resource using db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array(). Alternatively, you can use db2_fetch_row() to move the result set pointer to the next row and fetch a column at a time from that row with db2_result().

Refer to db2_prepare() for a brief discussion of the advantages of using db2_prepare() and db2_execute() rather than db2_exec().

Parameters

stmt

A prepared statement returned from db2_prepare().

parameters

An array of input parameters matching any parameter markers contained in the prepared statement.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Preparing and executing an SQL statement with parameter markers

The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().

<?php
$pet = array(0, 'cat', 'Pook', 3.2);

$insert = 'INSERT INTO animals (id, breed, name, weight)
    VALUES (?, ?, ?, ?)';

$stmt = db2_prepare($conn, $insert);
if ($stmt) {
    $result = db2_execute($stmt, $pet);
    if ($result) {
        print "Successfully added new pet.";
    }
}
?>

The above example will output:

Successfully added new pet.

Example #2 Calling a stored procedure with an OUT parameter

The following example prepares a CALL statement that accepts one parameter marker representing an OUT parameter, binds the PHP variable $my_pets to the parameter using db2_bind_param(), then issues db2_execute() to execute the CALL statement. After the CALL to the stored procedure has been made, the value of $num_pets changes to reflect the value returned by the stored procedure for that OUT parameter.

<?php
$num_pets = 0;
$res = db2_prepare($conn, "CALL count_my_pets(?)");
$rc = db2_bind_param($res, 1, "num_pets", DB2_PARAM_OUT);
$rc = db2_execute($res);
print "I have $num_pets pets!";
?>

The above example will output:

I have 7 pets!

Example #3 Returning XML data as a SQL ResultSet

The following example demonstrates how to work with documents stored in a XML column using the SAMPLE database. Using some pretty simple SQL/XML, this example returns some of the nodes in a XML document in a SQL ResultSet format that most users are familiar with.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = 'SELECT * FROM XMLTABLE(
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
    COLUMNS
    "CID" VARCHAR (50) PATH \'@Cid\',
    "NAME" VARCHAR (50) PATH \'name\',
    "PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
    ) AS T
    WHERE NAME = ?
    ';

$stmt = db2_prepare($conn, $query);

$name = 'Kathy Smith';

if ($stmt) {
    db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
    db2_execute($stmt);

    while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE\n");
    }
}
db2_close($conn);

?>

The above example will output:

1000     Kathy Smith     416-555-1358
1001     Kathy Smith     905-555-7258

Example #4 Performing a "JOIN" with XML data

The following example works with documents stored in 2 different XML columns in the SAMPLE database. It creates 2 temporary tables from the XML documents from 2 different columns and returns a SQL ResultSet with information regarding shipping status for the customer.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT A.CID, A.NAME, A.PHONE, C.PONUM, C.STATUS
FROM
XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" BIGINT PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) as A,
PURCHASEORDER AS B,
XMLTABLE (
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("PURCHASEORDER.PORDER")/PurchaseOrder\'
COLUMNS
"PONUM"  BIGINT PATH \'@PoNum\',
"STATUS" VARCHAR (50) PATH \'@Status\'
) as C
WHERE A.CID = B.CUSTID AND
    B.POID = C.PONUM AND
    A.NAME = ?
';

$stmt = db2_prepare($conn, $query);

$name = 'Kathy Smith';

if ($stmt) {
    db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
    db2_execute($stmt);

    while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE     $row->PONUM     $row->STATUS\n");
    }
}

db2_close($conn);

?>

The above example will output:

1001     Kathy Smith     905-555-7258     5002     Shipped

Example #5 Returning SQL data as part of a larger XML document

The following example works with a portion of the PRODUCT.DESCRIPTION documents in the SAMPLE database. It creates a XML document containing product description (XML data) and pricing info (SQL data).

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
    declare boundary-space strip;
    declare default element namespace "http://posample.org";
    <promoList> {
    for $prod in $doc/product
    where $prod/description/price < 10.00
    order by $prod/description/price ascending
    return(
        <promoitem> {
        $prod,
        <startdate> {$start} </startdate>,
        <enddate> {$end} </enddate>,
        <promoprice> {$promo} </promoprice>
            } </promoitem>
    )
    } </promoList>
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = ?
';

$stmt = db2_prepare($conn, $query);

$pid = "100-100-01";

if ($stmt) {
    db2_bind_param($stmt, 1, "pid", DB2_PARAM_IN);
    db2_execute($stmt);

    while($row = db2_fetch_array($stmt)){
    printf("$row[0]\n");
    }
}

db2_close($conn);

?>

The above example will output:

<promoList xmlns="http://posample.org">
    <promoitem>
    <product pid="100-100-01">
        <description>
            <name>Snow Shovel, Basic 22 inch</name>
            <details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
            <price>9.99</price>
            <weight>1 kg</weight>
        </description>
    </product>
    <startdate>2004-11-19</startdate>
    <enddate>2004-12-19</enddate>
    <promoprice>7.25</promoprice>
    </promoitem>
</promoList>

See Also

  • db2_exec() - Executes an SQL statement directly
  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_result() - Returns a single column from a row in the result set

db2_exec
db2_fetch_array
IBM DB2 Functions


Returns an array, indexed by column position, representing a row in a result set

db2_execute
db2_fetch_assoc
IBM DB2 Functions
PHP Manual

db2_fetch_array

(PECL ibm_db2 >= 1.0.1)

db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set

Description

array db2_fetch_array ( resource $stmt [, int $row_number = -1 ] )

Returns an array, indexed by column position, representing a row in a result set. The columns are 0-indexed.

Parameters

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Return Values

Returns a 0-indexed array with column values indexed by the column position representing the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

Examples

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_array() without a specific row number, it automatically retrieves the next row in the result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_array($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row[0], $row[1], $row[2], $row[3]);
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_array() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_array() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_array($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row[0], $row[1], $row[2], $row[3]);
    $i = $i + 2;
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

See Also

  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

db2_execute
db2_fetch_assoc
IBM DB2 Functions


Returns an array, indexed by column name, representing a row in a result set

db2_fetch_array
db2_fetch_both
IBM DB2 Functions
PHP Manual

db2_fetch_assoc

(PECL ibm_db2 >= 1.0.0)

db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set

Description

array db2_fetch_assoc ( resource $stmt [, int $row_number = -1 ] )

Returns an array, indexed by column name, representing a row in a result set.

Parameters

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Return Values

Returns an associative array with column values indexed by the column name representing the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

Examples

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_assoc() without a specific row number, it automatically retrieves the next row in the result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_assoc($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_assoc() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_assoc() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_assoc($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
    $i = $i + 2;
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

See Also

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

db2_fetch_array
db2_fetch_both
IBM DB2 Functions


Returns an array, indexed by both column name and position, representing a row in a result set

db2_fetch_assoc
db2_fetch_object
IBM DB2 Functions
PHP Manual

db2_fetch_both

(PECL ibm_db2 >= 1.0.0)

db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set

Description

array db2_fetch_both ( resource $stmt [, int $row_number = -1 ] )

Returns an array, indexed by both column name and position, representing a
row in a result set. Note that the row returned by
db2_fetch_both() requires more memory than the
single-indexed arrays returned by db2_fetch_assoc() or
db2_fetch_array().

Parameters

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Return Values

Returns an associative array with column values indexed by both the column name and 0-indexed column number. The array represents the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

Examples

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_both() without a specific row number, it automatically retrieves the next row in the result set. The following example accesses columns in the returned array by both column name and by numeric index.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_both($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row['ID'], $row[0], $row['BREED'], $row[3]);
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_both() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_both() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_both($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row[0], $row['NAME'], $row[2], $row['WEIGHT']);
    $i = $i + 2;
}
?>

The above example will output:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

See Also

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

db2_fetch_assoc
db2_fetch_object
IBM DB2 Functions


Returns an object with properties representing columns in the fetched row

db2_fetch_both
db2_fetch_row
IBM DB2 Functions
PHP Manual

db2_fetch_object

(PECL ibm_db2 >= 1.0.0)

db2_fetch_object — Returns an object with properties representing columns in the fetched row

Description

object db2_fetch_object ( resource $stmt [, int $row_number = -1 ] )

Returns an object in which each property represents a column returned in the row fetched from a result set.

Parameters

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Return Values

Returns an object representing a single row in the result set. The properties of the object map to the names of the columns in the result set.

The IBM DB2, Cloudscape, and Apache Derby database servers typically fold column names to upper-case, so the object properties will reflect that case.

If your SELECT statement calls a scalar function to modify the value of a column, the database servers return the column number as the name of the column in the result set. If you prefer a more descriptive column name and object property, you can use the AS clause to assign a name to the column in the result set.

Returns FALSE if no row was retrieved.

Examples

Example #1 A db2_fetch_object() example

The following example issues a SELECT statement with a scalar function, RTRIM, that removes whitespace from the end of the column. Rather than creating an object with the properties "BREED" and "2", we use the AS clause in the SELECT statement to assign the name "name" to the modified column. The database server folds the column names to upper-case, resulting in an object with the properties "BREED" and "NAME".

<?php
$conn = db2_connect($database, $user, $password);

$sql = "SELECT breed, RTRIM(name) AS name
    FROM animals
    WHERE id = ?";

if ($conn) {
    $stmt = db2_prepare($conn, $sql);
    db2_execute($stmt, array(0));

    while ($pet = db2_fetch_object($stmt)) {
        echo "Come here, {$pet->NAME}, my little {$pet->BREED}!";
    }
    db2_close($conn);
}
?>

The above example will output:

Come here, Pook, my little cat!

See Also

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

db2_fetch_both
db2_fetch_row
IBM DB2 Functions


Sets the result set pointer to the next row or requested row

db2_fetch_object
db2_field_display_size
IBM DB2 Functions
PHP Manual

db2_fetch_row

(PECL ibm_db2 >= 1.0.0)

db2_fetch_row — Sets the result set pointer to the next row or requested row

Description

bool db2_fetch_row ( resource $stmt [, int $row_number ] )

Use db2_fetch_row() to iterate through a result set, or to point to a specific row in a result set if you requested a scrollable cursor.

To retrieve individual fields from the result set, call the db2_result() function.

Rather than calling db2_fetch_row() and db2_result(), most applications will call one of db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array() to advance the result set pointer and return a complete row as an array.

Parameters

stmt

A valid stmt resource.

row_number

With scrollable cursors, you can request a specific row number in the result set. Row numbering is 1-indexed.

Return Values

Returns TRUE if the requested row exists in the result set. Returns FALSE if the requested row does not exist in the result set.

Examples

Example #1 Iterating through a result set

The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().

<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
    $breed = db2_result($stmt, 1);
    print "$name $breed";
}
?>

The above example will output:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

Example #2 i5/OS recommended alternatives to db2_fetch_row/db2_result

On i5/OS it is recommended that you use db2_fetch_both(), db2_fetch_array(), or db2_fetch_object() over db2_fetch_row()/db2_result(). In general db2_fetch_row()/db2_result() have more issues with various column types in EBCIDIC to ASCII translation, including possible truncation in DBCS applications. You may also find the performance of db2_fetch_both(), db2_fetch_array(), and db2_fetch_object() to be superior to db2_fetch_row()/db2_result().

<?php
  $conn = db2_connect("","","");
  $sql = 'SELECT SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, ROUTINE_CREATED, ROUTINE_BODY, IN_PARMS, OUT_PARMS, INOUT_PARMS, PARAMETER_STYLE, EXTERNAL_NAME, EXTERNAL_LANGUAGE FROM QSYS2.SYSROUTINES FETCH FIRST 2 ROWS ONLY';
  $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
  while ($row = db2_fetch_both($stmt)){
    echo "<br>db2_fetch_both {$row['SPECIFIC_NAME']} {$row['ROUTINE_CREATED']} {$row[5]}";
  }
  $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
  while ($row = db2_fetch_array($stmt)){
    echo "<br>db2_fetch_array {$row[1]}  {$row[5]}";
  }
  $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
  while ($row = db2_fetch_object($stmt)){
    echo "<br>db2_fetch_object {$row->SPECIFIC_NAME} {$row->ROUTINE_CREATED}";
  }
  db2_close($conn);
?>

The above example will output:

db2_fetch_both MATCH_ANIMAL 2006-08-25-17.10.23.775000 2006-08-25-17.10.23.775000
db2_fetch_both MULTIRESULTS 2006-10-17-10.11.05.308000 2006-10-17-10.11.05.308000
db2_fetch_array MATCH_ANIMAL 2006-08-25-17.10.23.775000
db2_fetch_array MULTIRESULTS 2006-10-17-10.11.05.308000
db2_fetch_object MATCH_ANIMAL 2006-08-25-17.10.23.775000
db2_fetch_object MULTIRESULTS 2006-10-17-10.11.05.308000

See Also

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_result() - Returns a single column from a row in the result set

db2_fetch_object
db2_field_display_size
IBM DB2 Functions


Returns the maximum number of bytes required to display a column

db2_fetch_row
db2_field_name
IBM DB2 Functions
PHP Manual

db2_field_display_size

(PECL ibm_db2 >= 1.0.0)

db2_field_display_size — Returns the maximum number of bytes required to display a column

Description

int db2_field_display_size ( resource $stmt , mixed $column )

Returns the maximum number of bytes required to display a column in a result set.

Parameters

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Return Values

Returns an integer value with the maximum number of bytes required to display the specified column. If the column does not exist in the result set, db2_field_display_size() returns FALSE.

See Also

  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_fetch_row
db2_field_name
IBM DB2 Functions


Returns the name of the column in the result set

db2_field_display_size
db2_field_num
IBM DB2 Functions
PHP Manual

db2_field_name

(PECL ibm_db2 >= 1.0.0)

db2_field_name — Returns the name of the column in the result set

Description

string db2_field_name ( resource $stmt , mixed $column )

Returns the name of the specified column in the result set.

Parameters

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Return Values

Returns a string containing the name of the specified column. If the specified column does not exist in the result set, db2_field_name() returns FALSE.

See Also

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_field_display_size
db2_field_num
IBM DB2 Functions


Returns the position of the named column in a result set

db2_field_name
db2_field_precision
IBM DB2 Functions
PHP Manual

db2_field_num

(PECL ibm_db2 >= 1.0.0)

db2_field_num — Returns the position of the named column in a result set

Description

int db2_field_num ( resource $stmt , mixed $column )

Returns the position of the named column in a result set.

Parameters

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Return Values

Returns an integer containing the 0-indexed position of the named column in the result set. If the specified column does not exist in the result set, db2_field_num() returns FALSE.

See Also

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_field_name
db2_field_precision
IBM DB2 Functions


Returns the precision of the indicated column in a result set

db2_field_num
db2_field_scale
IBM DB2 Functions
PHP Manual

db2_field_precision

(PECL ibm_db2 >= 1.0.0)

db2_field_precision — Returns the precision of the indicated column in a result set

Description

int db2_field_precision ( resource $stmt , mixed $column )

Returns the precision of the indicated column in a result set.

Parameters

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Return Values

Returns an integer containing the precision of the specified column. If the specified column does not exist in the result set, db2_field_precision() returns FALSE.

See Also

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_field_num
db2_field_scale
IBM DB2 Functions


Returns the scale of the indicated column in a result set

db2_field_precision
db2_field_type
IBM DB2 Functions
PHP Manual

db2_field_scale

(PECL ibm_db2 >= 1.0.0)

db2_field_scale — Returns the scale of the indicated column in a result set

Description

int db2_field_scale ( resource $stmt , mixed $column )

Returns the scale of the indicated column in a result set.

Parameters

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Return Values

Returns an integer containing the scale of the specified column. If the specified column does not exist in the result set, db2_field_scale() returns FALSE.

See Also

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_field_precision
db2_field_type
IBM DB2 Functions


Returns the data type of the indicated column in a result set

db2_field_scale
db2_field_width
IBM DB2 Functions
PHP Manual

db2_field_type

(PECL ibm_db2 >= 1.0.0)

db2_field_type — Returns the data type of the indicated column in a result set

Description

string db2_field_type ( resource $stmt , mixed $column )

Returns the data type of the indicated column in a result set.

Parameters

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Return Values

Returns a string containing the defined data type of the specified column. If the specified column does not exist in the result set, db2_field_type() returns FALSE.

See Also

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_field_scale
db2_field_width
IBM DB2 Functions


Returns the width of the current value of the indicated column in a result set

db2_field_type
db2_foreign_keys
IBM DB2 Functions
PHP Manual

db2_field_width

(PECL ibm_db2 >= 1.0.0)

db2_field_width — Returns the width of the current value of the indicated column in a result set

Description

int db2_field_width ( resource $stmt , mixed $column )

Returns the width of the current value of the indicated column in a result set. This is the maximum width of the column for a fixed-length data type, or the actual width of the column for a variable-length data type.

Parameters

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Return Values

Returns an integer containing the width of the specified character or binary data type column in a result set. If the specified column does not exist in the result set, db2_field_width() returns FALSE.

See Also

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set

db2_field_type
db2_foreign_keys
IBM DB2 Functions


Returns a result set listing the foreign keys for a table

db2_field_width
db2_free_result
IBM DB2 Functions
PHP Manual

db2_foreign_keys

(PECL ibm_db2 >= 1.0.0)

db2_foreign_keys — Returns a result set listing the foreign keys for a table

Description

resource db2_foreign_keys ( resource $connection , string $qualifier , string $schema , string $table-name )

Returns a result set listing the foreign keys for a table.

Parameters

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. If schema is NULL, db2_foreign_keys() matches the schema for the current connection.

table-name

The name of the table.

Return Values

Returns a statement resource with a result set containing rows describing the foreign keys for the specified table. The result set is composed of the following columns:

Column name | Description
PKTABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs.
PKTABLE_SCHEM | Name of the schema for the table containing the primary key.
PKTABLE_NAME | Name of the table containing the primary key.
PKCOLUMN_NAME | Name of the column containing the primary key.
FKTABLE_CAT | Name of the catalog for the table containing the foreign key. The value is NULL if this table does not have catalogs.
FKTABLE_SCHEM | Name of the schema for the table containing the foreign key.
FKTABLE_NAME | Name of the table containing the foreign key.
FKCOLUMN_NAME | Name of the column containing the foreign key.
KEY_SEQ | 1-indexed position of the column in the key.
UPDATE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is UPDATE.
DELETE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is DELETE.
FK_NAME | The name of the foreign key.
PK_NAME | The name of the primary key.
DEFERRABILITY | An integer value representing whether the foreign key deferrability is SQL_INITIALLY_DEFERRED, SQL_INITIALLY_IMMEDIATE, or SQL_NOT_DEFERRABLE.

See Also

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_field_width
db2_free_result
IBM DB2 Functions


Frees resources associated with a result set

db2_foreign_keys
db2_free_stmt
IBM DB2 Functions
PHP Manual

db2_free_result

(PECL ibm_db2 >= 1.0.0)

db2_free_result — Frees resources associated with a result set

Description

bool db2_free_result ( resource $stmt )

Frees the system and database resources that are associated with a result set. These resources are freed implicitly when a script finishes, but you can call db2_free_result() to explicitly free the result set resources before the end of the script.

Parameters

stmt

A valid statement resource.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • db2_free_stmt() - Frees resources associated with the indicated statement resource

db2_foreign_keys
db2_free_stmt
IBM DB2 Functions


Frees resources associated with the indicated statement resource

db2_free_result
db2_get_option
IBM DB2 Functions
PHP Manual

db2_free_stmt

(PECL ibm_db2 >= 1.0.0)

db2_free_stmt — Frees resources associated with the indicated statement resource

Description

bool db2_free_stmt ( resource $stmt )

Frees the system and database resources that are associated with a statement resource. These resources are freed implicitly when a script finishes, but you can call db2_free_stmt() to explicitly free the statement resources before the end of the script.

Parameters

stmt

A valid statement resource.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • db2_free_result() - Frees resources associated with a result set

db2_free_result
db2_get_option
IBM DB2 Functions


Retrieves an option value for a statement resource or a connection resource

db2_free_stmt
db2_last_insert_id
IBM DB2 Functions
PHP Manual

db2_get_option

(PECL ibm_db2 >= 1.6.0)

db2_get_option — Retrieves an option value for a statement resource or a connection resource

Description

string db2_get_option ( resource $resource , string $option )

Retrieves the value of a specified option value for a statement resource or a connection resource.

Parameters

resource

A valid statement resource as returned from db2_prepare() or a valid connection resource as returned from db2_connect() or db2_pconnect().

option

A valid statement or connection options. The following new options are available as of ibm_db2 version 1.6.0. They provide useful tracking information that can be set during execution with db2_get_option().

Note: Prior versions of ibm_db2 do not support these new options.
When the value in each option is being set, some servers might not handle the entire length provided and might truncate the value.
To ensure that the data specified in each option is converted correctly when transmitted to a host system, use only the characters A through Z, 0 through 9, and the underscore (_) or period (.).

userid

SQL_ATTR_INFO_USERID - A pointer to a null-terminated character string used to identify the client user ID sent to the host database server when using DB2 Connect.

Note: DB2 for z/OS and OS/390 servers support up to a length of 16 characters. This user-id is not to be confused with the authentication user-id, it is for identification purposes only and is not used for any authorization.

acctstr

SQL_ATTR_INFO_ACCTSTR - A pointer to a null-terminated character string used to identify the client accounting string sent to the host database server when using DB2 Connect.

Note: DB2 for z/OS and OS/390 servers support up to a length of 200 characters.

applname

SQL_ATTR_INFO_APPLNAME - A pointer to a null-terminated character string used to identify the client application name sent to the host database server when using DB2 Connect.

Note: DB2 for z/OS and OS/390 servers support up to a length of 32 characters.

wrkstnname

SQL_ATTR_INFO_WRKSTNNAME - A pointer to a null-terminated character string used to identify the client workstation name sent to the host database server when using DB2 Connect.

Note: DB2 for z/OS and OS/390 servers support up to a length of 18 characters.

The following table specifies which options are compatible with the available resource types:

Resource-Parameter Matrix
Key | Value | Resource Type
 |  | Connection | Statement | Result Set
userid | SQL_ATTR_INFO_USERID | X | X | -
acctstr | SQL_ATTR_INFO_ACCTSTR | X | X | -
applname | SQL_ATTR_INFO_APPLNAME | X | X | -
wrkstnname | SQL_ATTR_INFO_WRKSTNNAME | X | X | -

Return Values

Returns the current setting of the connection attribute provided on success or FALSE on failure.

Examples

Example #1 Setting and retrieving parameters through a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$user     = 'db2inst1';
$password = 'ibmdb2';

/* Obtain Connection Resource */
$conn = db2_connect($database, $user, $password);

echo "Client attributes passed through connection string:\n";

/* Create the associative options array with valid key-value pairs */
/* Assign the attributes through connection string */
/* Access the options specified */
$options1 = array('userid' => 'db2inst1');
$conn1 = db2_connect($database, $user, $password, $options1);
$val = db2_get_option($conn1, 'userid');
echo $val . "\n";

$options2 = array('acctstr' => 'account');
$conn2 = db2_connect($database, $user, $password, $options2);
$val = db2_get_option($conn2, 'acctstr');
echo $val . "\n";

$options3 = array('applname' => 'myapp');
$conn3 = db2_connect($database, $user, $password, $options3);
$val = db2_get_option($conn3, 'applname');
echo $val . "\n";

$options4 = array('wrkstnname' => 'workstation');
$conn4 = db2_connect($database, $user, $password, $options4);
$val = db2_get_option($conn4, 'wrkstnname');
echo $val . "\n";

echo "Client attributes passed post-connection:\n";

/* Create the associative options array with valid key-value pairs */
/* Assign the attributes after a connection is made */
/* Access the options specified */
$options5 = array('userid' => 'db2inst1');
$conn5 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn5, $options5, 1);
$val = db2_get_option($conn5, 'userid');
echo $val . "\n";

$options6 = array('acctstr' => 'account');
$conn6 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn6, $options6, 1);
$val = db2_get_option($conn6, 'acctstr');
echo $val . "\n";

$options7 = array('applname' => 'myapp');
$conn7 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn7, $options7, 1);
$val = db2_get_option($conn7, 'applname');
echo $val . "\n";

$options8 = array('wrkstnname' => 'workstation');
$conn8 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn8, $options8, 1);
$val = db2_get_option($conn8, 'wrkstnname');
echo $val . "\n";
?>

The above example will output:

Client attributes passed through connection string:
db2inst1
account
myapp
workstation
Client attributes passed post-connection:
db2inst1
account
myapp
workstation

See Also

  • db2_connect() - Returns a connection to a database
  • db2_cursor_type() - Returns the cursor type used by a statement resource
  • db2_exec() - Executes an SQL statement directly
  • db2_set_option() - Set options for connection or statement resources
  • db2_pconnect() - Returns a persistent connection to a database
  • db2_prepare() - Prepares an SQL statement to be executed

db2_free_stmt
db2_last_insert_id
IBM DB2 Functions


Returns the auto generated ID of the last insert query that successfully executed on this connection

db2_get_option
db2_lob_read
IBM DB2 Functions
PHP Manual

db2_last_insert_id

(PECL ibm_db2 >= 1.7.1)

db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection

Description

int db2_last_insert_id ( resource $resource )

Returns the auto generated ID of the last insert query that successfully executed on this connection.

The result of this function is not affected by any of the following:

  • A single row INSERT statement with a VALUES clause for a table without an identity column.

  • A multiple row INSERT statement with a VALUES clause.

  • An INSERT statement with a fullselect.

  • A ROLLBACK TO SAVEPOINT statement.

Parameters

resource

A valid connection resource as returned from db2_connect() or db2_pconnect(). The value of this parameter cannot be a statement resource or result set resource.

Return Values

Returns the auto generated ID of last insert query that successfully executed on this connection.

Examples

Example #1 A db2_last_insert_id() example

The following example shows how to return the auto generated ID of last insert query that successfully executed on this connection.

<?php

$database = "SAMPLE";
$user = "db2inst1";
$password = "ibmdb2";

$conn = db2_connect($database, $user, $password);
if($conn) {
    $createTable = "CREATE TABLE lastInsertID
      (id integer GENERATED BY DEFAULT AS IDENTITY, name varchar(20))";
    $insertTable = "INSERT INTO lastInsertID (name) VALUES ('Temp Name')";

    $stmt = @db2_exec($conn, $createTable);

    /* Checking for single row inserted. */
    $stmt = db2_exec($conn, $insertTable);
    $ret =  db2_last_insert_id($conn);
    if($ret) {
        echo "Last Insert ID is : " . $ret . "\n";
    } else {
        echo "No Last insert ID.\n";
    }

    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

The above example will output:

Last Insert ID is : 1

db2_get_option
db2_lob_read
IBM DB2 Functions


Gets a user defined size of LOB files with each invocation

db2_last_insert_id
db2_next_result
IBM DB2 Functions
PHP Manual

db2_lob_read

(PECL ibm_db2 >= 1.6.0)

db2_lob_read — Gets a user defined size of LOB files with each invocation

Description

string db2_lob_read ( resource $stmt , int $colnum , int $length )

Use db2_lob_read() to iterate through a specified column of a result set and retrieve a user defined size of LOB data.

Parameters

stmt

A valid stmt resource containing LOB data.

colnum

A valid column number in the result set of the stmt resource.

length

The size of the LOB data to be retrieved from the stmt resource.

Return Values

Returns the amount of data the user specifies. Returns FALSE if the data cannot be retrieved.

Examples

Example #1 Iterating through different types of data

<?php

/* Database Connection Parameters */
$db = 'SAMPLE';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Obtain Connection Resource */
$conn = db2_connect($db,$username,$password);

if ($conn) {
    $drop = 'DROP TABLE clob_stream';
    $result = @db2_exec( $conn, $drop );

    $create = 'CREATE TABLE clob_stream (id INTEGER, my_clob CLOB)';
    $result = db2_exec( $conn, $create );

    $variable = "";
    $stmt = db2_prepare($conn, "INSERT INTO clob_stream (id,my_clob) VALUES (1, ?)");
    $variable = "THIS IS A CLOB TEST. THIS IS A CLOB TEST.";
    db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN);
    db2_execute($stmt);

    $sql = "SELECT id,my_clob FROM clob_stream";
    $result = db2_prepare($conn, $sql);
    db2_execute($result);
    db2_fetch_row($result);
    $i = 0;
    /* Read LOB data */
    while ($data = db2_lob_read($result, 2, 6)) {
        echo "Loop $i: $data\n";
        $i = $i + 1;
    }

    $drop = 'DROP TABLE blob_stream';
    $result = @db2_exec( $conn, $drop );

    $create = 'CREATE TABLE blob_stream (id INTEGER, my_blob CLOB)';
    $result = db2_exec( $conn, $create );

    $variable = "";
    $stmt = db2_prepare($conn, "INSERT INTO blob_stream (id,my_blob) VALUES (1, ?)");
    $variable = "THIS IS A BLOB TEST. THIS IS A BLOB TEST.";
    db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN);
    db2_execute($stmt);

    $sql = "SELECT id,my_blob FROM blob_stream";
    $result = db2_prepare($conn, $sql);
    db2_execute($result);
    db2_fetch_row($result);
    $i = 0;
    /* Read LOB data */
    while ($data = db2_lob_read($result, 2, 6)) {
        echo "Loop $i: $data\n";
        $i = $i + 1;
    }
} else {
    echo 'no connection: ' . db2_conn_errormsg();
}

?>

The above example will output:

Loop 0: THIS I
Loop 1: S A CL
Loop 2: OB TES
Loop 3: T. THI
Loop 4: S IS A
Loop 5:  CLOB
Loop 6: TEST.
Loop 0: THIS I
Loop 1: S A BL
Loop 2: OB TES
Loop 3: T. THI
Loop 4: S IS A
Loop 5:  BLOB
Loop 6: TEST.

See Also

  • db2_bind_param() - Binds a PHP variable to an SQL statement parameter
  • db2_exec() - Executes an SQL statement directly
  • db2_execute() - Executes a prepared SQL statement
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_result() - Returns a single column from a row in the result set

db2_last_insert_id
db2_next_result
IBM DB2 Functions


Requests the next result set from a stored procedure

db2_lob_read
db2_num_fields
IBM DB2 Functions
PHP Manual

db2_next_result

(PECL ibm_db2 >= 1.0.0)

db2_next_result — Requests the next result set from a stored procedure

Description

resource db2_next_result ( resource $stmt )

A stored procedure can return zero or more result sets. While you handle the first result set in exactly the same way you would handle the results returned by a simple SELECT statement, to fetch the second and subsequent result sets from a stored procedure you must call the db2_next_result() function and return the result to a uniquely named PHP variable.

Parameters

stmt

A prepared statement returned from db2_exec() or db2_execute().

Return Values

Returns a new statement resource containing the next result set if the stored procedure returned another result set. Returns FALSE if the stored procedure did not return another result set.

Examples

Example #1 Calling a stored procedure that returns multiple result sets

In the following example, we call a stored procedure that returns three result sets. The first result set is fetched directly from the same statement resource on which we invoked the CALL statement, while the second and third result sets are fetched from statement resources returned from our calls to the db2_next_result() function.

<?php
$conn = db2_connect($database, $user, $password);

if ($conn) {
  $stmt = db2_exec($conn, 'CALL multiResults()');

  print "Fetching first result set\n";
  while ($row = db2_fetch_array($stmt)) {
    var_dump($row);
  }

  print "\nFetching second result set\n";
  $res = db2_next_result($stmt);
  if ($res) {
    while ($row = db2_fetch_array($res)) {
      var_dump($row);
    }
  }

  print "\nFetching third result set\n";
  $res2 = db2_next_result($stmt);
  if ($res2) {
    while ($row = db2_fetch_array($res2)) {
      var_dump($row);
    }
  }

  db2_close($conn);
}
?>

The above example will output:

Fetching first result set
array(2) {
  [0]=>
  string(16) "Bubbles         "
  [1]=>
  int(3)
}
array(2) {
  [0]=>
  string(16) "Gizmo           "
  [1]=>
  int(4)
}

Fetching second result set
array(4) {
  [0]=>
  string(16) "Sweater         "
  [1]=>
  int(6)
  [2]=>
  string(5) "llama"
  [3]=>
  string(6) "150.00"
}
array(4) {
  [0]=>
  string(16) "Smarty          "
  [1]=>
  int(2)
  [2]=>
  string(5) "horse"
  [3]=>
  string(6) "350.00"
}

Fetching third result set
array(1) {
  [0]=>
  string(16) "Bubbles         "
}
array(1) {
  [0]=>
  string(16) "Gizmo           "
}

db2_lob_read
db2_num_fields
IBM DB2 Functions


Returns the number of fields contained in a result set

db2_next_result
db2_num_rows
IBM DB2 Functions
PHP Manual

db2_num_fields

(PECL ibm_db2 >= 1.0.0)

db2_num_fields — Returns the number of fields contained in a result set

Description

int db2_num_fields ( resource $stmt )

Returns the number of fields contained in a result set. This is most useful for handling the result sets returned by dynamically generated queries, or for result sets returned by stored procedures, where your application cannot otherwise know how to retrieve and use the results.

Parameters

stmt

A valid statement resource containing a result set.

Return Values

Returns an integer value representing the number of fields in the result set associated with the specified statement resource. Returns FALSE if the statement resource is not a valid input value.

Examples

Example #1 Retrieving the number of fields in a result set

The following example demonstrates how to retrieve the number of fields returned in a result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, $sql);
$columns = db2_num_fields($stmt);

echo "There are {$columns} columns in the result set.";
?>

The above example will output:

There are 4 columns in the result set.

See Also

  • db2_execute() - Executes a prepared SQL statement
  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_next_result
db2_num_rows
IBM DB2 Functions


Returns the number of rows affected by an SQL statement

db2_num_fields
db2_pclose
IBM DB2 Functions
PHP Manual

db2_num_rows

(PECL ibm_db2 >= 1.0.0)

db2_num_rows — Returns the number of rows affected by an SQL statement

Description

int db2_num_rows ( resource $stmt )

Returns the number of rows deleted, inserted, or updated by an SQL statement.

To determine the number of rows that will be returned by a SELECT statement, issue SELECT COUNT(*) with the same predicates as your intended SELECT statement and retrieve the value.

If your application logic checks the number of rows returned by a SELECT statement and branches if the number of rows is 0, consider modifying your application to attempt to return the first row with one of db2_fetch_assoc(), db2_fetch_both(), db2_fetch_array(), or db2_fetch_row(), and branch if the fetch function returns FALSE.

Note: If you issue a SELECT statement using a scrollable cursor, db2_num_rows() returns the number of rows returned by the SELECT statement. However, the overhead associated with scrollable cursors significantly degrades the performance of your application, so if this is the only reason you are considering using scrollable cursors, you should use a forward-only cursor and either call SELECT COUNT(*) or rely on the boolean return value of the fetch functions to achieve the equivalent functionality with much better performance.

Parameters

stmt

A valid stmt resource containing a result set.

Return Values

Returns the number of rows affected by the last SQL statement issued by the specified statement handle.

db2_num_fields
db2_pclose
IBM DB2 Functions


Closes a persistent database connection

db2_num_rows
db2_pconnect
IBM DB2 Functions
PHP Manual

db2_pclose

(PECL ibm_db2 >= 1.8.0)

db2_pclose — Closes a persistent database connection

Description

bool db2_pclose ( resource $resource )

This function closes a DB2 client connection created with db2_pconnect() and returns the corresponding resources to the database server.

Note: This function is only available on i5/OS in response to i5/OS system administration requests.

If you have a persistent DB2 client connection created with db2_pconnect(), you may use this function to close the connection. To avoid substantial connection performance penalties, this function should only be used in rare cases when the persistent connection has become unresponsive or the persistent connection will not be needed for a long period of time.

Parameters

connection

Specifies an active DB2 client connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a persistent connection

The following example demonstrates a successful attempt to close a connection to an IBM DB2 i5/OS database.

<?php
$conn = db2_pconnect('', '', '');
$rc = db2_pclose($conn);
if ($rc) {
    echo "Connection was successfully closed.";
}
?>

The above example will output:

Connection was successfully closed.

See Also

  • db2_close() - Closes a database connection
  • db2_pconnect() - Returns a persistent connection to a database

db2_num_rows
db2_pconnect
IBM DB2 Functions


Returns a persistent connection to a database

db2_pclose
db2_prepare
IBM DB2 Functions
PHP Manual

db2_pconnect

(PECL ibm_db2 >= 1.0.0)

db2_pconnect — Returns a persistent connection to a database

Description

resource db2_pconnect ( string $database , string $username , string $password [, array $options ] )

Returns a persistent connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database. For more information on persistent connections, refer to Persistent Database Connections.

Calling db2_close() on a persistent connection always returns TRUE, but the underlying DB2 client connection remains open and waiting to serve the next matching db2_pconnect() request.

Parameters

database

The database alias in the DB2 client catalog.

username

The username with which you are connecting to the database.

password

The password with which you are connecting to the database.

options

An associative array of connection options that affect the behavior of the connection, where valid array keys include:

autocommit

Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.

Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.

DB2_ATTR_CASE

Passing the DB2_CASE_NATURAL value specifies that column names are returned in natural case.

Passing the DB2_CASE_LOWER value specifies that column names are returned in lower case.

Passing the DB2_CASE_UPPER value specifies that column names are returned in upper case.

CURSOR

Passing the DB2_FORWARD_ONLY value specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.

Passing the DB2_SCROLLABLE value specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.

The following new option is available in ibm_db2 version 1.7.0 and later.

trustedcontext

Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns trusted context on for this connection handle. This parameter cannot be set using db2_set_option().

This key works only if the database is cataloged (even if the database is local), or if you specify the full DSN when you create the connection.

To catalog the database, use following commands:

db2 catalog tcpip node loopback remote <SERVERNAME> server <SERVICENAME>
db2 catalog database <LOCALDBNAME> as <REMOTEDBNAME> at node loopback
db2 "update dbm cfg using svcename <SERVICENAME>"
db2set DB2COMM=TCPIP

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later.

Tip

Conflicting connection attributes used in conjunction with persistent connections can produce indeterminate results on i5/OS. Site policies should be establish for all applications using each persistent connection user profile. The default DB2_AUTOCOMMIT_ON is suggested when using persistent connections.

i5_lib

A character value that indicates the default library that will be used for resolving unqualified file references. This is not valid if the connection is using system naming mode.

i5_naming

DB2_I5_NAMING_ON value turns on DB2 UDB CLI iSeries system naming mode. Files are qualified using the slash (/) delimiter. Unqualified files are resolved using the library list for the job.

DB2_I5_NAMING_OFF value turns off DB2 UDB CLI default naming mode, which is SQL naming. Files are qualified using the period (.) delimiter. Unqualified files are resolved using either the default library or the current user ID.

i5_commit

The i5_commit attribute should be set before the db2_pconnect(). If the value is changed after the connection has been established, and the connection is to a remote data source, the change does not take effect until the next successful db2_pconnect() for the connection handle.

Note: The php.ini setting ibm_db2.i5_allow_commit ==0 or DB2_I5_TXN_NO_COMMIT is the default, but may be overridden with the i5_commit option.

DB2_I5_TXN_NO_COMMIT - Commitment control is not used.

DB2_I5_TXN_READ_UNCOMMITTED - Dirty reads, nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_READ_COMMITTED - Dirty reads are not possible. Nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_REPEATABLE_READ - Dirty reads and nonrepeatable reads are not possible. Phantoms are possible.

DB2_I5_TXN_SERIALIZABLE - Transactions are serializable. Dirty reads, non-repeatable reads, and phantoms are not possible

i5_query_optimize

DB2_FIRST_IO All queries are optimized with the goal of returning the first page of output as fast as possible. This goal works well when the output is controlled by a user who is most likely to cancel the query after viewing the first page of output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause.

DB2_ALL_IO All queries are optimized with the goal of running the entire query to completion in the shortest amount of elapsed time. This is a good option when the output of a query is being written to a file or report, or the interface is queuing the output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. This is the default.

i5_dbcs_alloc

DB2_I5_DBCS_ALLOC_ON value turns on DB2 6X allocation scheme for DBCS translation column size growth.

DB2_I5_DBCS_ALLOC_OFF value turns off DB2 6X allocation scheme for DBCS translation column size growth.

Note: The php.ini setting ibm_db2.i5_dbcs_alloc ==0 or DB2_I5_DBCS_ALLOC_OFF is the default, but may be overridden with the i5_dbcs_alloc option.

i5_date_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) date format yyyy-mm-dd is used. This is the default.

DB2_I5_FMT_USA - The United States date format mm/dd/yyyy is used.

DB2_I5_FMT_EUR - The European date format dd.mm.yyyy is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard date format yyyy-mm-dd is used.

DB2_I5_FMT_MDY - The date format mm/dd/yyyy is used.

DB2_I5_FMT_DMY - The date format dd/mm/yyyy is used.

DB2_I5_FMT_YMD - The date format yy/mm/dd is used.

DB2_I5_FMT_JUL - The Julian date format yy/ddd is used.

DB2_I5_FMT_JOB - The job default is used.

i5_date_sep

DB2_I5_SEP_SLASH - A slash ( / ) is used as the date separator. This is the default.

DB2_I5_SEP_DASH - A dash ( - ) is used as the date separator.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the date separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the date separator.

DB2_I5_SEP_BLANK - A blank is used as the date separator.

DB2_I5_SEP_JOB - The job default is used

i5_time_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) time format hh.mm.ss is used. This is the default.

DB2_I5_FMT_USA - The United States time format hh:mmxx is used, where xx is AM or PM.

DB2_I5_FMT_EUR - The European time format hh.mm.ss is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard time format hh:mm:ss is used.

DB2_I5_FMT_HMS - The hh:mm:ss format is used.

i5_time_sep

DB2_I5_SEP_COLON - A colon ( : ) is used as the time separator. This is the default.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the time separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the time separator.

DB2_I5_SEP_BLANK - A blank is used as the time separator.

DB2_I5_SEP_JOB - The job default is used.

i5_decimal_sep

DB2_I5_SEP_PERIOD - A period ( . ) is used as the decimal separator. This is the default.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the decimal separator.

DB2_I5_SEP_JOB - The job default is used.

The following new i5/OS option is available in ibm_db2 version 1.8.0 and later.

i5_libl

A character value that indicates the library list that will be used for resolving unqualified file references. Specify the library list elements separated by blanks 'i5_libl'=>"MYLIB YOURLIB ANYLIB".

Note: i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

Return Values

Returns a connection handle resource if the connection attempt is successful. db2_pconnect() tries to reuse an existing connection resource that exactly matches the database , username , and password parameters. If the connection attempt fails, db2_pconnect() returns FALSE.

Examples

Example #1 A db2_pconnect() example

In the following example, the first call to db2_pconnect() returns a new persistent connection resource. The second call to db2_pconnect() returns a persistent connection resource that simply reuses the first persistent connection resource.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

$pconn = db2_pconnect($database, $user, $password);

if ($pconn) {
    echo "Persistent connection succeeded.";
}
else {
    echo "Persistent connection failed.";
}

$pconn2 = db2_pconnect($database, $user, $password);
if ($pconn) {
    echo "Second persistent connection succeeded.";
}
else {
    echo "Second persistent connection failed.";
}
?>

The above example will output:

Persistent connection succeeded.
Second persistent connection succeeded.

Example #2 Using trusted context

The following example shows how to enable trusted context, switch users, and get the current user ID.

<?php

$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";

$tc_user = "tcuser";
$tc_pass = "tcpassword";

$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;
  PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);

$tc_conn = db2_pconnect($dsn, "", "", $options);
if($tc_conn) {
    echo "Explicit trusted connection succeeded.\n";

    if(db2_get_option($tc_conn, "trustedcontext")) {
        $userBefore = db2_get_option($tc_conn, "trusted_user");

        //Do some work as user 1.

        //Switching to trusted user.
        $parameters = array("trusted_user" => $tc_user,
          "trusted_password" => $tcuser_pass);
        $res = db2_set_option ($tc_conn, $parameters, 1);

        $userAfter = db2_get_option($tc_conn, "trusted_user");
        //Do more work as trusted user.

        if($userBefore != $userAfter) {
            echo "User has been switched." . "\n";
        }
    }

    db2_close($tc_conn);
}
else {
    echo "Explicit trusted connection failed.\n";
}
?>

The above example will output:

Explicit trusted connection succeeded.
User has been switched.

See Also

  • db2_connect() - Returns a connection to a database

db2_pclose
db2_prepare
IBM DB2 Functions


Prepares an SQL statement to be executed

db2_pconnect
db2_primary_keys
IBM DB2 Functions
PHP Manual

db2_prepare

(PECL ibm_db2 >= 1.0.0)

db2_prepare — Prepares an SQL statement to be executed

Description

resource db2_prepare ( resource $connection , string $statement [, array $options ] )

db2_prepare() creates a prepared SQL statement which can include 0 or more parameter markers (? characters) representing parameters for input, output, or input/output. You can pass parameters to the prepared statement using db2_bind_param(), or for input values only, as an array passed to db2_execute().

There are three main advantages to using prepared statements in your application:

  • Performance: when you prepare a statement, the database server creates an optimized access plan for retrieving data with that statement. Subsequently issuing the prepared statement with db2_execute() enables the statements to reuse that access plan and avoids the overhead of dynamically creating a new access plan for every statement you issue.

  • Security: when you prepare a statement, you can include parameter markers for input values. When you execute a prepared statement with input values for placeholders, the database server checks each input value to ensure that the type matches the column definition or parameter definition.

  • Advanced functionality: Parameter markers not only enable you to pass input values to prepared SQL statements, they also enable you to retrieve OUT and INOUT parameters from stored procedures using db2_bind_param().

Parameters

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

statement

An SQL statement, optionally containing one or more parameter markers..

options

An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.

For a description of valid statement options, see db2_set_option().

Return Values

Returns a statement resource if the SQL statement was successfully parsed and prepared by the database server. Returns FALSE if the database server returned an error. You can determine which error was returned by calling db2_stmt_error() or db2_stmt_errormsg().

Examples

Example #1 Preparing and executing an SQL statement with parameter markers

The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().

<?php
$animals = array(
    array(0, 'cat', 'Pook', 3.2),
    array(1, 'dog', 'Peaches', 12.3),
    array(2, 'horse', 'Smarty', 350.0),
);

$insert = 'INSERT INTO animals (id, breed, name, weight)
    VALUES (?, ?, ?, ?)';
$stmt = db2_prepare($conn, $insert);
if ($stmt) {
    foreach ($animals as $animal) {
        $result = db2_execute($stmt, $animal);
    }
}
?>

See Also

  • db2_bind_param() - Binds a PHP variable to an SQL statement parameter
  • db2_execute() - Executes a prepared SQL statement
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

db2_pconnect
db2_primary_keys
IBM DB2 Functions


Returns a result set listing primary keys for a table

db2_prepare
db2_procedure_columns
IBM DB2 Functions
PHP Manual

db2_primary_keys

(PECL ibm_db2 >= 1.0.0)

db2_primary_keys — Returns a result set listing primary keys for a table

Description

resource db2_primary_keys ( resource $connection , string $qualifier , string $schema , string $table-name )

Returns a result set listing the primary keys for a table.

Parameters

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. If schema is NULL, db2_primary_keys() matches the schema for the current connection.

table-name

The name of the table.

Return Values

Returns a statement resource with a result set containing rows describing the primary keys for the specified table. The result set is composed of the following columns:

Column name | Description
TABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema for the table containing the primary key.
TABLE_NAME | Name of the table containing the primary key.
COLUMN_NAME | Name of the column containing the primary key.
KEY_SEQ | 1-indexed position of the column in the key.
PK_NAME | The name of the primary key.

See Also

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_prepare
db2_procedure_columns
IBM DB2 Functions


Returns a result set listing stored procedure parameters

db2_primary_keys
db2_procedures
IBM DB2 Functions
PHP Manual

db2_procedure_columns

(PECL ibm_db2 >= 1.0.0)

db2_procedure_columns — Returns a result set listing stored procedure parameters

Description

resource db2_procedure_columns ( resource $connection , string $qualifier , string $schema , string $procedure , string $parameter )

Returns a result set listing the parameters for one or more stored procedures.

Parameters

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.

procedure

The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.

parameter

The name of the parameter. This parameter accepts a search pattern containing _ and % as wildcards. If this parameter is NULL, all parameters for the specified stored procedures are returned.

Return Values

Returns a statement resource with a result set containing rows describing the parameters for the stored procedures matching the specified parameters. The rows are composed of the following columns:

Column name | Description
PROCEDURE_CAT | The catalog that contains the procedure. The value is NULL if this table does not have catalogs.
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure.
PROCEDURE_NAME | Name of the procedure.
COLUMN_NAME | Name of the parameter.
COLUMN_TYPE

An integer value representing the type of the parameter:

Return value | Parameter type
1 (SQL_PARAM_INPUT) | Input (IN) parameter.
2 (SQL_PARAM_INPUT_OUTPUT) | Input/output (INOUT) parameter.
3 (SQL_PARAM_OUTPUT) | Output (OUT) parameter.
DATA_TYPE | The SQL data type for the parameter represented as an integer value.
TYPE_NAME | A string representing the data type for the parameter.
COLUMN_SIZE | An integer value representing the size of the parameter.
BUFFER_LENGTH | Maximum number of bytes necessary to store data for this parameter.
DECIMAL_DIGITS | The scale of the parameter, or NULL where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable).
NULLABLE | An integer value representing whether the parameter is nullable or not.
REMARKS | Description of the parameter.
COLUMN_DEF | Default value for the parameter.
SQL_DATA_TYPE | An integer value representing the size of the parameter.
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or NULL for SQL data types to which this does not apply.
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type parameter, which matches COLUMN_SIZE for single-byte character set data, or NULL for non-character data types.
ORDINAL_POSITION | The 1-indexed position of the parameter in the CALL statement.
IS_NULLABLE | A string value where 'YES' means that the parameter accepts or returns NULL values and 'NO' means that the parameter does not accept or return NULL values.

See Also

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_primary_keys
db2_procedures
IBM DB2 Functions


Returns a result set listing the stored procedures registered in a database

db2_procedure_columns
db2_result
IBM DB2 Functions
PHP Manual

db2_procedures

(PECL ibm_db2 >= 1.0.0)

db2_procedures — Returns a result set listing the stored procedures registered in a database

Description

resource db2_procedures ( resource $connection , string $qualifier , string $schema , string $procedure )

Returns a result set listing the stored procedures registered in a database.

Parameters

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.

procedure

The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.

Return Values

Returns a statement resource with a result set containing rows describing the stored procedures matching the specified parameters. The rows are composed of the following columns:

Column name | Description
PROCEDURE_CAT | The catalog that contains the procedure. The value is NULL if this table does not have catalogs.
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure.
PROCEDURE_NAME | Name of the procedure.
NUM_INPUT_PARAMS | Number of input (IN) parameters for the stored procedure.
NUM_OUTPUT_PARAMS | Number of output (OUT) parameters for the stored procedure.
NUM_RESULT_SETS | Number of result sets returned by the stored procedure.
REMARKS | Any comments about the stored procedure.
PROCEDURE_TYPE | Always returns 1, indicating that the stored procedure does not return a return value.

See Also

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_procedure_columns
db2_result
IBM DB2 Functions


Returns a single column from a row in the result set

db2_procedures
db2_rollback
IBM DB2 Functions
PHP Manual

db2_result

(PECL ibm_db2 >= 1.0.0)

db2_result — Returns a single column from a row in the result set

Description

mixed db2_result ( resource $stmt , mixed $column )

Use db2_result() to return the value of a specified column in the current row of a result set. You must call db2_fetch_row() before calling db2_result() to set the location of the result set pointer.

Parameters

stmt

A valid stmt resource.

column

Either an integer mapping to the 0-indexed field in the result set, or a string matching the name of the column.

Return Values

Returns the value of the requested field if the field exists in the result set. Returns NULL if the field does not exist, and issues a warning.

Examples

Example #1 A db2_result() example

The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().

<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
    $breed = db2_result($stmt, 'BREED');
    print "$name $breed";
}
?>

The above example will output:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

See Also

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row

db2_procedures
db2_rollback
IBM DB2 Functions


Rolls back a transaction

db2_result
db2_server_info
IBM DB2 Functions
PHP Manual

db2_rollback

(PECL ibm_db2 >= 1.0.0)

db2_rollback — Rolls back a transaction

Description

bool db2_rollback ( resource $connection )

Rolls back an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_rollback() normally has no effect unless AUTOCOMMIT has been turned off for the connection resource.

Note: If the specified connection resource is a persistent connection, all transactions in progress for all applications using that persistent connection will be rolled back. For this reason, persistent connections are not recommended for use in applications that require transactions.

Parameters

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Rolling back a DELETE statement

In the following example, we count the number of rows in a table, turn off AUTOCOMMIT mode on a database connection, delete all of the rows in the table and return the count of 0 to prove that the rows have been removed. We then issue db2_rollback() and return the updated count of rows in the table to show that the number is the same as before we issued the DELETE statement. The return to the original state of the table demonstrates that the roll back of the transaction succeeded.

<?php
$conn = db2_connect($database, $user, $password);

if ($conn) {
    $stmt = db2_exec($conn, "SELECT count(*) FROM animals");
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";

    // Turn AUTOCOMMIT off
    db2_autocommit($conn, DB2_AUTOCOMMIT_OFF);

    // Delete all rows from ANIMALS
    db2_exec($conn, "DELETE FROM animals");

    $stmt = db2_exec($conn, "SELECT count(*) FROM animals");
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";

    // Roll back the DELETE statement
    db2_rollback( $conn );

    $stmt = db2_exec( $conn, "SELECT count(*) FROM animals" );
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";
    db2_close($conn);
}
?>

The above example will output:

7
0
7

See Also

  • db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
  • db2_commit() - Commits a transaction

db2_result
db2_server_info
IBM DB2 Functions


Returns an object with properties that describe the DB2 database server

db2_rollback
db2_set_option
IBM DB2 Functions
PHP Manual

db2_server_info

(PECL ibm_db2 >= 1.1.1)

db2_server_info — Returns an object with properties that describe the DB2 database server

Description

object db2_server_info ( resource $connection )

This function returns an object with read-only properties that return information about the IBM DB2, Cloudscape, or Apache Derby database server. The following table lists the database server properties:

Database server properties
Property name | Return type | Description
DBMS_NAME | string | The name of the database server to which you are connected. For DB2 servers this is a combination of DB2 followed by the operating system on which the database server is running.
DBMS_VER | string | The version of the database server, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1.
DB_CODEPAGE | int | The code page of the database to which you are connected.
DB_NAME | string | The name of the database to which you are connected.
DFT_ISOLATION string

The default transaction isolation level supported by the server:

UR

Uncommitted read: changes are immediately visible by all concurrent transactions.

CS

Cursor stability: a row read by one transaction can be altered and committed by a second concurrent transaction.

RS

Read stability: a transaction can add or remove rows matching a search condition or a pending transaction.

RR

Repeatable read: data affected by pending transaction is not available to other transactions.

NC

No commit: any changes are visible at the end of a successful operation. Explicit commits and rollbacks are not allowed.

IDENTIFIER_QUOTE_CHAR | string | The character used to delimit an identifier.
INST_NAME | string | The instance on the database server that contains the database.
ISOLATION_OPTION | array | An array of the isolation options supported by the database server. The isolation options are described in the DFT_ISOLATION property.
KEYWORDS | array | An array of the keywords reserved by the database server.
LIKE_ESCAPE_CLAUSE | bool | TRUE if the database server supports the use of % and _ wildcard characters. FALSE if the database server does not support these wildcard characters.
MAX_COL_NAME_LEN | int | Maximum length of a column name supported by the database server, expressed in bytes.
MAX_IDENTIFIER_LEN | int | Maximum length of an SQL identifier supported by the database server, expressed in characters.
MAX_INDEX_SIZE | int | Maximum size of columns combined in an index supported by the database server, expressed in bytes.
MAX_PROC_NAME_LEN | int | Maximum length of a procedure name supported by the database server, expressed in bytes.
MAX_ROW_SIZE | int | Maximum length of a row in a base table supported by the database server, expressed in bytes.
MAX_SCHEMA_NAME_LEN | int | Maximum length of a schema name supported by the database server, expressed in bytes.
MAX_STATEMENT_LEN | int | Maximum length of an SQL statement supported by the database server, expressed in bytes.
MAX_TABLE_NAME_LEN | int | Maximum length of a table name supported by the database server, expressed in bytes.
NON_NULLABLE_COLUMNS | bool | TRUE if the database server supports columns that can be defined as NOT NULL, FALSE if the database server does not support columns defined as NOT NULL.
PROCEDURES | bool | TRUE if the database server supports the use of the CALL statement to call stored procedures, FALSE if the database server does not support the CALL statement.
SPECIAL_CHARS | string | A string containing all of the characters other than a-Z, 0-9, and underscore that can be used in an identifier name.
SQL_CONFORMANCE string

The level of conformance to the ANSI/ISO SQL-92 specification offered by the database server:

ENTRY

Entry-level SQL-92 compliance.

FIPS127

FIPS-127-2 transitional compliance.

FULL

Full level SQL-92 compliance.

INTERMEDIATE

Intermediate level SQL-92 compliance.

Parameters

connection

Specifies an active DB2 client connection.

Return Values

Returns an object on a successful call. Returns FALSE on failure.

Examples

Example #1 A db2_server_info() example

To retrieve information about the server, you must pass a valid database connection resource to db2_server_info().

<?php

$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');

$server = db2_server_info( $conn );

if ($server) {
    echo "DBMS_NAME: ";                 var_dump( $server->DBMS_NAME );
    echo "DBMS_VER: ";                  var_dump( $server->DBMS_VER );
    echo "DB_CODEPAGE: ";               var_dump( $server->DB_CODEPAGE );
    echo "DB_NAME: ";                   var_dump( $server->DB_NAME );
    echo "INST_NAME: ";                 var_dump( $server->INST_NAME );
    echo "SPECIAL_CHARS: ";             var_dump( $server->SPECIAL_CHARS );
    echo "KEYWORDS: ";                  var_dump( sizeof($server->KEYWORDS) );
    echo "DFT_ISOLATION: ";             var_dump( $server->DFT_ISOLATION );
    echo "ISOLATION_OPTION: ";
    $il = '';
    foreach( $server->ISOLATION_OPTION as $opt )
    {
       $il .= $opt." ";
    }
    var_dump( $il );
    echo "SQL_CONFORMANCE: ";           var_dump( $server->SQL_CONFORMANCE );
    echo "PROCEDURES: ";                var_dump( $server->PROCEDURES );
    echo "IDENTIFIER_QUOTE_CHAR: ";     var_dump( $server->IDENTIFIER_QUOTE_CHAR );
    echo "LIKE_ESCAPE_CLAUSE: ";        var_dump( $server->LIKE_ESCAPE_CLAUSE );
    echo "MAX_COL_NAME_LEN: ";          var_dump( $server->MAX_COL_NAME_LEN );
    echo "MAX_ROW_SIZE: ";              var_dump( $server->MAX_ROW_SIZE );
    echo "MAX_IDENTIFIER_LEN: ";        var_dump( $server->MAX_IDENTIFIER_LEN );
    echo "MAX_INDEX_SIZE: ";            var_dump( $server->MAX_INDEX_SIZE );
    echo "MAX_PROC_NAME_LEN: ";         var_dump( $server->MAX_PROC_NAME_LEN );
    echo "MAX_SCHEMA_NAME_LEN: ";       var_dump( $server->MAX_SCHEMA_NAME_LEN );
    echo "MAX_STATEMENT_LEN: ";         var_dump( $server->MAX_STATEMENT_LEN );
    echo "MAX_TABLE_NAME_LEN: ";        var_dump( $server->MAX_TABLE_NAME_LEN );
    echo "NON_NULLABLE_COLUMNS: ";      var_dump( $server->NON_NULLABLE_COLUMNS );

    db2_close($conn);
}
?>

The above example will output:

DBMS_NAME: string(9) "DB2/LINUX"
DBMS_VER: string(10) "08.02.0000"
DB_CODEPAGE: int(1208)
DB_NAME: string(6) "SAMPLE"
INST_NAME: string(8) "db2inst1"
SPECIAL_CHARS: string(2) "@#"
KEYWORDS: int(179)
DFT_ISOLATION: string(2) "CS"
ISOLATION_OPTION: string(12) "UR CS RS RR "
SQL_CONFORMANCE: string(7) "FIPS127"
PROCEDURES: bool(true)
IDENTIFIER_QUOTE_CHAR: string(1) """
LIKE_ESCAPE_CLAUSE: bool(true)
MAX_COL_NAME_LEN: int(30)
MAX_ROW_SIZE: int(32677)
MAX_IDENTIFIER_LEN: int(18)
MAX_INDEX_SIZE: int(1024)
MAX_PROC_NAME_LEN: int(128)
MAX_SCHEMA_NAME_LEN: int(30)
MAX_STATEMENT_LEN: int(2097152)
MAX_TABLE_NAME_LEN: int(128)
NON_NULLABLE_COLUMNS: bool(true)

See Also

  • db2_client_info() - Returns an object with properties that describe the DB2 database client

db2_rollback
db2_set_option
IBM DB2 Functions


Set options for connection or statement resources

db2_server_info
db2_special_columns
IBM DB2 Functions
PHP Manual

db2_set_option

(PECL ibm_db2 >= 1.0.0)

db2_set_option — Set options for connection or statement resources

Description

bool db2_set_option ( resource $resource , array $options , int $type )

Sets options for a statement resource or a connection resource. You cannot set options for result set resources.

Parameters

resource

A valid statement resource as returned from db2_prepare() or a valid connection resource as returned from db2_connect() or db2_pconnect().

options

An associative array containing valid statement or connection options. This parameter can be used to change autocommit values, cursor types (scrollable or forward), and to specify the case of the column names (lower, upper, or natural) that will appear in a result set.

autocommit

Passing DB2_AUTOCOMMIT_ON turns autocommit on for the specified connection resource.

Passing DB2_AUTOCOMMIT_OFF turns autocommit off for the specified connection resource.

cursor

Passing DB2_FORWARD_ONLY specifies a forward-only cursor for a statement resource. This is the default cursor type, and is supported by all database servers.

Passing DB2_SCROLLABLE specifies a scrollable cursor for a statement resource. Scrollable cursors enable result set rows to be accessed in non-sequential order, but are only supported by IBM DB2 Universal Database databases.

binmode

Passing DB2_BINARY specifies that binary data will be returned as is. This is the default mode. This is the equivalent of setting ibm_db2.binmode=1 in php.ini.

Passing DB2_CONVERT specifies that binary data will be converted to hexadecimal encoding, and will be returned as such. This is the equivalent of setting ibm_db2.binmode=2 in php.ini.

Passing DB2_PASSTHRU specifies that binary data will be converted to NULL. This is the equivalent of setting ibm_db2.binmode=3 in php.ini.

db2_attr_case

Passing DB2_CASE_LOWER specifies that column names of the result set are returned in lower case.

Passing DB2_CASE_UPPER specifies that column names of the result set are returned in upper case.

Passing DB2_CASE_NATURAL specifies that column names of the result set are returned in natural case.

deferred_prepare

Passing DB2_DEFERRED_PREPARE_ON turns deferred prepare on for the specified statement resource.

Passing DB2_DEFERRED_PREPARE_OFF turns deferred prepare off for the specified statement resource.

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later. These options apply only when running PHP and ibm_db2 natively on i5 systems.

i5_fetch_only

DB2_I5_FETCH_ON - Cursors are read-only and cannot be used for positioned updates or deletes. This is the default unless SQL_ATTR_FOR_FETCH_ONLY environment has been set to SQL_FALSE.

DB2_I5_FETCH_OFF - Cursors can be used for positioned updates and deletes.

The following new option is available in ibm_db2 version 1.8.0 and later.

rowcount

DB2_ROWCOUNT_PREFETCH_ON - Client can request the full row count prior to fetching, which means that db2_num_rows() returns the number of rows selected even when a ROLLFORWARD_ONLY cursor is used.

DB2_ROWCOUNT_PREFETCH_OFF - Client cannot request the full row count prior to fetching.

The following new options are available in ibm_db2 version 1.7.0 and later.

trusted_user

To switch the user to a trusted user, pass the User ID (String) of the trusted user as the value of this key. This option can be set on a connection resource only. To use this option, trusted context must be enabled on the connection resource.

trusted_password

The password (String) that corresponds to the user specified by the trusted_user key.

The following new options are available in ibm_db2 version 1.6.0 and later. These options provide useful tracking information that can be accessed during execution with db2_get_option().

Note: When the value in each option is being set, some servers might not handle the entire length provided and might truncate the value.
To ensure that the data specified in each option is converted correctly when transmitted to a host system, use only the characters A through Z, 0 through 9, and the underscore (_) or period (.).

userid

SQL_ATTR_INFO_USERID - A pointer to a null-terminated character string used to identify the client user ID sent to the host database server when using DB2 Connect.

Note: DB2 for z/OS and OS/390 servers support up to a length of 16 characters. This user-id is not to be confused with the authentication user-id, it is for identification purposes only and is not used for any authorization.

acctstr

SQL_ATTR_INFO_ACCTSTR - A pointer to a null-terminated character string used to identify the client accounting string sent to the host database server when using DB2 Connect.

Note: DB2 for z/OS and OS/390 servers support up to a length of 200 characters.

applname

SQL_ATTR_INFO_APPLNAME - A pointer to a null-terminated character string used to identify the client application name sent to the host database server when using DB2 Connect.

Note: DB2 for z/OS and OS/390 servers support up to a length of 32 characters.

wrkstnname

SQL_ATTR_INFO_WRKSTNNAME - A pointer to a null-terminated character string used to identify the client workstation name sent to the host database server when using DB2 Connect.

Note: DB2 for z/OS and OS/390 servers support up to a length of 18 characters.

type

An integer value that specifies the type of resource that was passed into the function. The type of resource and this value must correspond.

Passing 1 as the value specifies that a connection resource has been passed into the function.

Passing any integer not equal to 1 as the value specifies that a statement resource has been passed into the function.

The following table specifies which options are compatible with the available resource types:

Resource-Parameter Matrix
Key | Value | Resource Type
 |  | Connection | Statement | Result Set
autocommit | DB2_AUTOCOMMIT_ON | X | - | -
autocommit | DB2_AUTOCOMMIT_OFF | X | - | -
cursor | DB2_SCROLLABLE | - | X | -
cursor | DB2_FORWARD_ONLY | - | X | -
binmode | DB2_BINARY | X | X | -
binmode | DB2_CONVERT | X | X | -
binmode | DB2_PASSTHRU | X | X | -
db2_attr_case | DB2_CASE_LOWER | X | X | -
db2_attr_case | DB2_CASE_UPPER | X | X | -
db2_attr_case | DB2_CASE_NATURAL | X | X | -
deferred_prepare | DB2_DEFERRED_PREPARE_ON | - | X | -
deferred_prepare | DB2_DEFERRED_PREPARE_OFF | - | X | -
i5_fetch_only | DB2_I5_FETCH_ON | - | X | -
i5_fetch_only | DB2_I5_FETCH_OFF | - | X | -
rowcount | DB2_ROWCOUNT_PREFETCH_ON | - | X | -
rowcount | DB2_ROWCOUNT_PREFETCH_OFF | - | X | -
trusted_user | <USER NAME> (String) | X | - | -
trusted_password | <PASSWORD> (String) | X | - | -
userid | SQL_ATTR_INFO_USERID | X | X | -
acctstr | SQL_ATTR_INFO_ACCTSTR | X | X | -
applname | SQL_ATTR_INFO_APPLNAME | X | X | -
wrkstnname | SQL_ATTR_INFO_WRKSTNNAME | X | X | -

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting one parameter with a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_ON);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Options Set Successfully

Example #2 Setting multiple parameters with a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Options Set Successfully

Example #3 Setting multiple parameters with an invalid key

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
             'MY_INVALID_KEY' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Could Not Set Options

Example #4 Setting multiple parameters with an invalid value

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => 'INVALID_VALUE',
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Could Not Set Options

Example #5 Setting multiple parameters with a connection resource and the wrong type

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and the wrong type value */
$result = db2_set_option($conn, $options, 2);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Could Not Set Options

Example #6 Setting multiple parameters with the wrong resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE');

/* Call the function using the wrong resource, and the correct options array, and type values */
$result = db2_set_option($stmt, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

The above example will output:

Could Not Set Options

Example #7 Putting it all together

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('db2_attr_case' => DB2_CASE_LOWER,
                        'cursor' => DB2_SCROLLABLE);

$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE WHERE EMPNO = ? OR EMPNO = ?');

/* Call the function using the correct resource, options array, and type values */
$option_result = db2_set_option($stmt, $options, 2);
$result = db2_execute($stmt, array('000130', '000140'));

/* Get Row 2 before Row 1 since Scrollable Cursor */
print_r(db2_fetch_assoc($stmt, 2));
print '<br /><br />';
print_r(db2_fetch_assoc($stmt, 1));

?>

The above example will output:

Array
(
    [empno] => 000140
    [firstnme] => HEATHER
    [midinit] => A
    [lastname] => NICHOLLS
    [workdept] => C01
    [phoneno] => 1793
    [hiredate] => 1976-12-15
    [job] => ANALYST
    [edlevel] => 18
    [sex] => F
    [birthdate] => 1946-01-19
    [salary] => 28420.00
    [bonus] => 600.00
    [comm] => 2274.00
)

Array
(
    [empno] => 000130
    [firstnme] => DELORES
    [midinit] => M
    [lastname] => QUINTANA
    [workdept] => C01
    [phoneno] => 4578
    [hiredate] => 1971-07-28
    [job] => ANALYST
    [edlevel] => 16
    [sex] => F
    [birthdate] => 1925-09-15
    [salary] => 23800.00
    [bonus] => 500.00
    [comm] => 1904.00
)

Example #8 i5/OS cursors are read-only

<?php
  $conn = db2_connect("", "", "", array("i5_lib"=>"nobody"));
  $stmt = db2_prepare($conn, 'select * from names where first = ?');
  $name = "first2";
  db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
  $options = array("i5_fetch_only"=>DB2_I5_FETCH_ON);
  db2_set_option($stmt,$options,0);
  if (db2_execute($stmt)) {
    while ($row = db2_fetch_array($stmt)) {
      echo "{$row[0]} {$row[1]}";
    }
  }
?>

The above example will output:

first2 last2

See Also

  • db2_connect() - Returns a connection to a database
  • db2_pconnect() - Returns a persistent connection to a database
  • db2_exec() - Executes an SQL statement directly
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_cursor_type() - Returns the cursor type used by a statement resource

db2_server_info
db2_special_columns
IBM DB2 Functions


Returns a result set listing the unique row identifier columns for a table

db2_set_option
db2_statistics
IBM DB2 Functions
PHP Manual

db2_special_columns

(PECL ibm_db2 >= 1.0.0)

db2_special_columns — Returns a result set listing the unique row identifier columns for a table

Description

resource db2_special_columns ( resource $connection , string $qualifier , string $schema , string $table_name , int $scope )

Returns a result set listing the unique row identifier columns for a table.

Parameters

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables.

table_name

The name of the table.

scope

Integer value representing the minimum duration for which the unique row identifier is valid. This can be one of the following values:

Integer value | SQL constant | Description
0 | SQL_SCOPE_CURROW | Row identifier is valid only while the cursor is positioned on the row.
1 | SQL_SCOPE_TRANSACTION | Row identifier is valid for the duration of the transaction.
2 | SQL_SCOPE_SESSION | Row identifier is valid for the duration of the connection.

Return Values

Returns a statement resource with a result set containing rows with unique row identifier information for a table. The rows are composed of the following columns:

Column name | Description
SCOPE

Integer value | SQL constant | Description
0 | SQL_SCOPE_CURROW | Row identifier is valid only while the cursor is positioned on the row.
1 | SQL_SCOPE_TRANSACTION | Row identifier is valid for the duration of the transaction.
2 | SQL_SCOPE_SESSION | Row identifier is valid for the duration of the connection.
COLUMN_NAME | Name of the unique column.
DATA_TYPE | SQL data type for the column.
TYPE_NAME | Character string representation of the SQL data type for the column.
COLUMN_SIZE | An integer value representing the size of the column.
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column.
DECIMAL_DIGITS | The scale of the column, or NULL where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable).
PSEUDO_COLUMN | Always returns 1.

See Also

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_set_option
db2_statistics
IBM DB2 Functions


Returns a result set listing the index and statistics for a table

db2_special_columns
db2_stmt_error
IBM DB2 Functions
PHP Manual

db2_statistics

(PECL ibm_db2 >= 1.0.0)

db2_statistics — Returns a result set listing the index and statistics for a table

Description

resource db2_statistics ( resource $connection , string $qualifier , string $schema , string $table-name , bool $unique )

Returns a result set listing the index and statistics for a table.

Parameters

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema that contains the targeted table. If this parameter is NULL, the statistics and indexes are returned for the schema of the current user.

table_name

The name of the table.

unique

An integer value representing the type of index information to return.

0

Return only the information for unique indexes on the table.

1

Return the information for all indexes on the table.

Return Values

Returns a statement resource with a result set containing rows describing the statistics and indexes for the base tables matching the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
NON_UNIQUE

An integer value representing whether the index prohibits unique values, or whether the row represents statistics on the table itself:

Return value | Parameter type
0 (SQL_FALSE) | The index allows duplicate values.
1 (SQL_TRUE) | The index values must be unique.
NULL | This row is statistics information for the table itself.
INDEX_QUALIFIER | A string value representing the qualifier that would have to be prepended to INDEX_NAME to fully qualify the index.
INDEX_NAME | A string representing the name of the index.
TYPE

An integer value representing the type of information contained in this row of the result set:

Return value | Parameter type
0 (SQL_TABLE_STAT) | The row contains statistics about the table itself.
1 (SQL_INDEX_CLUSTERED) | The row contains information about a clustered index.
2 (SQL_INDEX_HASH) | The row contains information about a hashed index.
3 (SQL_INDEX_OTHER) | The row contains information about a type of index that is neither clustered nor hashed.
ORDINAL_POSITION | The 1-indexed position of the column in the index. NULL if the row contains statistics information about the table itself.
COLUMN_NAME | The name of the column in the index. NULL if the row contains statistics information about the table itself.
ASC_OR_DESC | A if the column is sorted in ascending order, D if the column is sorted in descending order, NULL if the row contains statistics information about the table itself.
CARDINALITY

If the row contains information about an index, this column contains an integer value representing the number of unique values in the index.

If the row contains information about the table itself, this column contains an integer value representing the number of rows in the table.

PAGES

If the row contains information about an index, this column contains an integer value representing the number of pages used to store the index.

If the row contains information about the table itself, this column contains an integer value representing the number of pages used to store the table.

FILTER_CONDITION | Always returns NULL.

See Also

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_special_columns
db2_stmt_error
IBM DB2 Functions


Returns a string containing the SQLSTATE returned by an SQL statement

db2_statistics
db2_stmt_errormsg
IBM DB2 Functions
PHP Manual

db2_stmt_error

(PECL ibm_db2 >= 1.0.0)

db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement

Description

string db2_stmt_error ([ resource $stmt ] )

Returns a string containing the SQLSTATE value returned by an SQL statement.

If you do not pass a statement resource as an argument to db2_stmt_error(), the driver returns the SQLSTATE value associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().

To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value ' . You can also call db2_stmt_errormsg() to retrieve an explicit error message and the associated SQLCODE value.

Parameters

stmt

A valid statement resource.

Return Values

Returns a string containing an SQLSTATE value.

See Also

  • db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

db2_statistics
db2_stmt_errormsg
IBM DB2 Functions


Returns a string containing the last SQL statement error message

db2_stmt_error
db2_table_privileges
IBM DB2 Functions
PHP Manual

db2_stmt_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_stmt_errormsg — Returns a string containing the last SQL statement error message

Description

string db2_stmt_errormsg ([ resource $stmt ] )

Returns a string containing the last SQL statement error message.

If you do not pass a statement resource as an argument to db2_stmt_errormsg(), the driver returns the error message associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().

Parameters

stmt

A valid statement resource.

Return Values

Returns a string containing the error message and SQLCODE value for the last error that occurred issuing an SQL statement.

See Also

  • db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement

db2_stmt_error
db2_table_privileges
IBM DB2 Functions


Returns a result set listing the tables and associated privileges in a database

db2_stmt_errormsg
db2_tables
IBM DB2 Functions
PHP Manual

db2_table_privileges

(PECL ibm_db2 >= 1.0.0)

db2_table_privileges — Returns a result set listing the tables and associated privileges in a database

Description

resource db2_table_privileges ( resource $connection [, string $qualifier [, string $schema [, string $table_name ]]] )

Returns a result set listing the tables and associated privileges in a database.

Parameters

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.

table_name

The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.

Return Values

Returns a statement resource with a result set containing rows describing the privileges for the tables that match the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
GRANTOR | Authorization ID of the user who granted the privilege.
GRANTEE | Authorization ID of the user to whom the privilege was granted.
PRIVILEGE | The privilege that has been granted. This can be one of ALTER, CONTROL, DELETE, INDEX, INSERT, REFERENCES, SELECT, or UPDATE.
IS_GRANTABLE | A string value of "YES" or "NO" indicating whether the grantee can grant the privilege to other users.

See Also

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_stmt_errormsg
db2_tables
IBM DB2 Functions


Returns a result set listing the tables and associated metadata in a database

db2_table_privileges
Ingres
IBM DB2 Functions
PHP Manual

db2_tables

(PECL ibm_db2 >= 1.0.0)

db2_tables — Returns a result set listing the tables and associated metadata in a database

Description

resource db2_tables ( resource $connection [, string $qualifier [, string $schema [, string $table-name [, string $table-type ]]]] )

Returns a result set listing the tables and associated metadata in a database.

Parameters

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.

table-name

The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.

table-type

A list of comma-delimited table type identifiers. To match all table types, pass NULL or an empty string. Valid table type identifiers include: ALIAS, HIERARCHY TABLE, INOPERATIVE VIEW, NICKNAME, MATERIALIZED QUERY TABLE, SYSTEM TABLE, TABLE, TYPED TABLE, TYPED VIEW, and VIEW.

Return Values

Returns a statement resource with a result set containing rows describing the tables that match the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
TABLE_TYPE | Table type identifier for the table.
REMARKS | Description of the table.

See Also

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database

db2_table_privileges
Ingres
IBM DB2 Functions


Close a DBA database

DBA Functions
dba_delete
DBA Functions
PHP Manual

dba_close

(PHP 4, PHP 5)

dba_close — Close a DBA database

Description

void dba_close ( resource $handle )

dba_close() closes the established database and frees all resources of the specified database handle.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

No value is returned.

See Also

  • dba_open() - Open database
  • dba_popen() - Open database persistently

DBA Functions
dba_delete
DBA Functions


Delete DBA entry specified by key

dba_close
dba_exists
DBA Functions
PHP Manual

dba_delete

(PHP 4, PHP 5)

dba_delete — Delete DBA entry specified by key

Description

bool dba_delete ( string $key , resource $handle )

dba_delete() deletes the specified entry from the database.

Parameters

key

The key of the entry which is deleted.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • dba_exists() - Check whether key exists
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry

dba_close
dba_exists
DBA Functions


Check whether key exists

dba_delete
dba_fetch
DBA Functions
PHP Manual

dba_exists

(PHP 4, PHP 5)

dba_exists — Check whether key exists

Description

bool dba_exists ( string $key , resource $handle )

dba_exists() checks whether the specified key exists in the database.

Parameters

key

The key the check is performed for.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE if the key exists, FALSE otherwise.

See Also

  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry

dba_delete
dba_fetch
DBA Functions


Fetch data specified by key

dba_exists
dba_firstkey
DBA Functions
PHP Manual

dba_fetch

(PHP 4, PHP 5)

dba_fetch — Fetch data specified by key

Description

string dba_fetch ( string $key , resource $handle )
string dba_fetch ( string $key , int $skip , resource $handle )

dba_fetch() fetches the data specified by key from the database specified with handle .

Parameters

key

The key the data is specified by.

Note: When working with inifiles this function accepts arrays as keys where index 0 is the group and index 1 is the value name. See: dba_key_split().

skip

The number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns the associated string if the key/data pair is found, FALSE otherwise.

Changelog

Version | Description
4.3 | The skip parameter is available to support cdb's capability of multiple keys having the same name.

See Also

  • dba_exists() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry
  • dba_key_split() - Splits a key in string representation into array representation

dba_exists
dba_firstkey
DBA Functions


Fetch first key

dba_fetch
dba_handlers
DBA Functions
PHP Manual

dba_firstkey

(PHP 4, PHP 5)

dba_firstkey — Fetch first key

Description

string dba_firstkey ( resource $handle )

dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns the key on success or FALSE on failure.

See Also

  • dba_nextkey() - Fetch next key
  • dba_key_split() - Splits a key in string representation into array representation
  • Example 2 in the DBA examples

dba_fetch
dba_handlers
DBA Functions


List all the handlers available

dba_firstkey
dba_insert
DBA Functions
PHP Manual

dba_handlers

(PHP 4 >= 4.3.0, PHP 5)

dba_handlers — List all the handlers available

Description

array dba_handlers ([ bool $full_info = false ] )

dba_handlers() list all the handlers supported by this extension.

Parameters

full_info

Turns on/off full information display in the result.

Return Values

Returns an array of database handlers. If full_info is set to TRUE, the array will be associative with the handlers names as keys, and their version information as value. Otherwise, the result will be an indexed array of handlers names.

Note: When the internal cdb library is used you will see cdb and cdb_make.

Examples

Example #1 dba_handlers() Example

<?php

echo "Available DBA handlers:\n";
foreach (dba_handlers(true) as $handler_name => $handler_version) {
  // clean the versions
  $handler_version = str_replace('$', '', $handler_version);
  echo " - $handler_name: $handler_version\n";
}

?>

The above example will output something similar to:

Available DBA handlers:
 - cdb: 0.75, Revision: 1.3.2.3
 - cdb_make: 0.75, Revision: 1.2.2.4
 - db2: Sleepycat Software: Berkeley DB 2.7.7: (08/20/99)
 - inifile: 1.0, Revision: 1.6.2.3
 - flatfile: 1.0, Revision: 1.5.2.4

dba_firstkey
dba_insert
DBA Functions


Insert entry

dba_handlers
dba_key_split
DBA Functions
PHP Manual

dba_insert

(PHP 4, PHP 5)

dba_insert — Insert entry

Description

bool dba_insert ( string $key , string $value , resource $handle )

dba_insert() inserts the entry described with key and value into the database.

Parameters

key

The key of the entry to be inserted. If this key already exist in the database, this function will fail. Use dba_replace() if you need to replace an existent key.

value

The value to be inserted.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • dba_exists() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_replace() - Replace or insert entry

dba_handlers
dba_key_split
DBA Functions


Splits a key in string representation into array representation

dba_insert
dba_list
DBA Functions
PHP Manual

dba_key_split

(PHP 5)

dba_key_split — Splits a key in string representation into array representation

Description

mixed dba_key_split ( mixed $key )

dba_key_split() splits a key (string representation) into an array representation.

Parameters

key

The key in string representation.

Return Values

Returns an array of the form array(0 => group, 1 => value_name). This function will return FALSE if key is NULL or FALSE.

See Also

  • dba_firstkey() - Fetch first key
  • dba_nextkey() - Fetch next key
  • dba_fetch() - Fetch data specified by key

dba_insert
dba_list
DBA Functions


List all open database files

dba_key_split
dba_nextkey
DBA Functions
PHP Manual

dba_list

(PHP 4 >= 4.3.0, PHP 5)

dba_list — List all open database files

Description

array dba_list ( void )

dba_list() list all open database files.

Return Values

An associative array, in the form resourceid => filename.

dba_key_split
dba_nextkey
DBA Functions


Fetch next key

dba_list
dba_open
DBA Functions
PHP Manual

dba_nextkey

(PHP 4, PHP 5)

dba_nextkey — Fetch next key

Description

string dba_nextkey ( resource $handle )

dba_nextkey() returns the next key of the database and advances the internal key pointer.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns the key on success or FALSE on failure.

See Also

  • dba_firstkey() - Fetch first key
  • dba_key_split() - Splits a key in string representation into array representation
  • Example 2 in the DBA examples

dba_list
dba_open
DBA Functions


Open database

dba_nextkey
dba_optimize
DBA Functions
PHP Manual

dba_open

(PHP 4, PHP 5)

dba_open — Open database

Description

resource dba_open ( string $path , string $mode [, string $handler [, mixed $... ]] )

dba_open() establishes a database instance for path with mode using handler .

Parameters

path

Commonly a regular path in your filesystem.

mode

It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access. The database is created in BTree mode, other modes (like Hash or Queue) are not supported.

Additionally you can set the database lock method with the next char. Use l to lock the database with a .lck file or d to lock the databasefile itself. It is important that all of your applications do this consistently.

If you want to test the access and do not want to wait for the lock you can add t as third character. When you are absolutely sure that you do not require database locking you can do so by using - instead of l or d. When none of d, l or - is used, dba will lock on the database file as it would with d.

Note: There can only be one writer for one database file. When you use dba on a web server and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the following table:

DBA locking
already open | mode = "rl" | mode = "rlt" | mode = "wl" | mode = "wlt" | mode = "rd" | mode = "rdt" | mode = "wd" | mode = "wdt"
not open | ok | ok | ok | ok | ok | ok | ok | ok
mode = "rl" | ok | ok | wait | false | illegal | illegal | illegal | illegal
mode = "wl" | wait | false | wait | false | illegal | illegal | illegal | illegal
mode = "rd" | illegal | illegal | illegal | illegal | ok | ok | wait | false
mode = "wd" | illegal | illegal | illegal | illegal | wait | false | wait | false

  • ok: the second call will be successfull.
  • wait: the second call waits until dba_close() is called for the first.
  • false: the second call returns false.
  • illegal: you must not mix "l" and "d" modifiers for mode parameter.

handler

The name of the handler which shall be used for accessing path . It is passed all optional parameters given to dba_open() and can act on behalf of them.

Return Values

Returns a positive handle on success or FALSE on failure.

Changelog

Version | Description
4.3.0 | It's possible to open database files over network connection. However in cases a socket connection will be used (as with http or ftp) the connection will be locked instead of the resource itself. This is important to know since in such cases locking is simply ignored on the resource and other solutions have to be found.
4.3.0 | Locking and the mode modifiers "l", "d", "-" and "t" were added. In previous PHP versions, you must use semaphores to guard against simultaneous database access for any database handler with the exception of GDBM. See System V semaphore support.
before 4.3.5 | open mode 'c' is broken for several internal handlers and truncates the database instead of appending data to an existent database. Also dbm and ndbm fail on mode 'c' in typical configurations (this cannot be fixed).

See Also

  • dba_popen() - Open database persistently
  • dba_close() - Close a DBA database

dba_nextkey
dba_optimize
DBA Functions


Optimize database

dba_open
dba_popen
DBA Functions
PHP Manual

dba_optimize

(PHP 4, PHP 5)

dba_optimize — Optimize database

Description

bool dba_optimize ( resource $handle )

dba_optimize() optimizes the underlying database.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • dba_sync() - Synchronize database

dba_open
dba_popen
DBA Functions


Open database persistently

dba_optimize
dba_replace
DBA Functions
PHP Manual

dba_popen

(PHP 4, PHP 5)

dba_popen — Open database persistently

Description

resource dba_popen ( string $path , string $mode [, string $handler [, mixed $... ]] )

dba_popen() establishes a persistent database instance for path with mode using handler .

Parameters

path

Commonly a regular path in your filesystem.

mode

It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access.

handler

The name of the handler which shall be used for accessing path . It is passed all optional parameters given to dba_popen() and can act on behalf of them.

Return Values

Returns a positive handle on success or FALSE on failure.

See Also

  • dba_open() - Open database
  • dba_close() - Close a DBA database

dba_optimize
dba_replace
DBA Functions


Replace or insert entry

dba_popen
dba_sync
DBA Functions
PHP Manual

dba_replace

(PHP 4, PHP 5)

dba_replace — Replace or insert entry

Description

bool dba_replace ( string $key , string $value , resource $handle )

dba_replace() replaces or inserts the entry described with key and value into the database specified by handle .

Parameters

key

The key of the entry to be replaced.

value

The value to be replaced.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • dba_exists() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry

dba_popen
dba_sync
DBA Functions


Synchronize database

dba_replace
dbx
DBA Functions
PHP Manual

dba_sync

(PHP 4, PHP 5)

dba_sync — Synchronize database

Description

bool dba_sync ( resource $handle )

dba_sync() synchronizes the database. This will probably trigger a physical write to the disk, if supported.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • dba_optimize() - Optimize database

dba_replace
dbx
DBA Functions


Adds a record to a database

dBase Functions
dbase_close
dBase Functions
PHP Manual

dbase_add_record

(PHP 4, PHP 5)

dbase_add_record — Adds a record to a database

Description

bool dbase_add_record ( int $dbase_identifier , array $record )

Adds the given data to the database.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.

Note: If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Inserting a record in a dBase database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  dbase_add_record($db, array(
      date('Ymd'),
      'Maxim Topolov',
      '23',
      'max@example.com',
      'T'));
  dbase_close($db);
}

?>

See Also

  • dbase_delete_record() - Deletes a record from a database
  • dbase_replace_record() - Replaces a record in a database

dBase Functions
dbase_close
dBase Functions


Closes a database

dbase_add_record
dbase_create
dBase Functions
PHP Manual

dbase_close

(PHP 4, PHP 5)

dbase_close — Closes a database

Description

bool dbase_close ( int $dbase_identifier )

Closes the given database link identifier.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a dBase database file

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  // read some data ..

  dbase_close($db);
}

?>

See Also

  • dbase_open() - Opens a database
  • dbase_create() - Creates a database

dbase_add_record
dbase_create
dBase Functions


Creates a database

dbase_close
dbase_delete_record
dBase Functions
PHP Manual

dbase_create

(PHP 4, PHP 5)

dbase_create — Creates a database

Description

int dbase_create ( string $filename , array $fields )

dbase_create() creates a dBase database with the given definition.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: This function is affected by open_basedir.

Parameters

filename

The name of the database. It can be a relative or absolute path to the file where dBase will store your data.

fields

An array of arrays, each array describing the format of one field of the database. Each field consists of a name, a character indicating the field type, and optionally, a length, and a precision.

Note: The fieldnames are limited in length and must not exceed 10 chars.

Return Values

Returns a database link identifier if the database is successfully created, or FALSE if an error occurred.

Examples

Example #1 Creating a dBase database file

<?php

// database "definition"
$def = array(
  array("date",     "D"),
  array("name",     "C",  50),
  array("age",      "N",   3, 0),
  array("email",    "C", 128),
  array("ismember", "L")
);

// creation
if (!dbase_create('/tmp/test.dbf', $def)) {
  echo "Error, can't create the database\n";
}

?>

See Also

  • dbase_open() - Opens a database
  • dbase_close() - Closes a database

dbase_close
dbase_delete_record
dBase Functions


Deletes a record from a database

dbase_create
dbase_get_header_info
dBase Functions
PHP Manual

dbase_delete_record

(PHP 4, PHP 5)

dbase_delete_record — Deletes a record from a database

Description

bool dbase_delete_record ( int $dbase_identifier , int $record_number )

Marks the given record to be deleted from the database.

Note: To actually remove the record from the database, you must also call dbase_pack().

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • dbase_add_record() - Adds a record to a database
  • dbase_replace_record() - Replaces a record in a database

dbase_create
dbase_get_header_info
dBase Functions


Gets the header info of a database

dbase_delete_record
dbase_get_record_with_names
dBase Functions
PHP Manual

dbase_get_header_info

(PHP 5)

dbase_get_header_info — Gets the header info of a database

Description

array dbase_get_header_info ( int $dbase_identifier )

Returns information on the column structure of the given database link identifier.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

An indexed array with an entry for each column in the database. The array index starts at 0.

Each array element contains an associative array of column information, as described here:

name
The name of the column
type
The human-readable name for the dbase type of the column (i.e. date, boolean, etc.)
length
The number of bytes this column can hold
precision
The number of digits of decimal precision for the column
format
A suggested printf() format specifier for the column
offset
The byte offset of the column from the start of the row

If the database header information cannot be read, FALSE is returned.

Examples

Example #1 Showing header information for a dBase database file

<?php
// Path to dbase file
$db_path = "/tmp/test.dbf";

// Open dbase file
$dbh = dbase_open($db_path, 0)
  or die("Error! Could not open dbase database file '$db_path'.");

// Get column information
$column_info = dbase_get_header_info($dbh);

// Display information
print_r($column_info);
?>

dbase_delete_record
dbase_get_record_with_names
dBase Functions


Gets a record from a database as an indexed array

dbase_get_record_with_names
dbase_numfields
dBase Functions
PHP Manual

dbase_get_record

(PHP 4, PHP 5)

dbase_get_record — Gets a record from a database as an indexed array

Description

array dbase_get_record ( int $dbase_identifier , int $record_number )

Gets a record from a database as an indexed array.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record.

Return Values

An indexed array with the record. This array will also include an associative key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings.
  • Integers that would have caused an overflow (> 32 bits) are returned as strings.

On error, dbase_get_record() will return FALSE.

See Also

  • dbase_get_record_with_names() - Gets a record from a database as an associative array

dbase_get_record_with_names
dbase_numfields
dBase Functions


Gets a record from a database as an associative array

dbase_get_header_info
dbase_get_record
dBase Functions
PHP Manual

dbase_get_record_with_names

(PHP 4, PHP 5)

dbase_get_record_with_names — Gets a record from a database as an associative array

Description

array dbase_get_record_with_names ( int $dbase_identifier , int $record_number )

Gets a record from a dBase database as an associative array.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record.

Return Values

An associative array with the record. This will also include a key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings.
  • Integers that would have caused an overflow (> 32 bits) are returned as strings.

On error, dbase_get_record_with_names() will return FALSE.

Examples

Example #1 Listing all the registered members in the database

<?php
// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      $row = dbase_get_record_with_names($db, $i);
      if ($row['ismember'] == 1) {
          echo "Member #$i: " . trim($row['name']) . "\n";
      }
  }
}
?>

See Also

  • dbase_get_record() - Gets a record from a database as an indexed array

dbase_get_header_info
dbase_get_record
dBase Functions


Gets the number of fields of a database

dbase_get_record
dbase_numrecords
dBase Functions
PHP Manual

dbase_numfields

(PHP 4, PHP 5)

dbase_numfields — Gets the number of fields of a database

Description

int dbase_numfields ( int $dbase_identifier )

Gets the number of fields (columns) in the specified database.

Note: Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

The number of fields in the database, or FALSE if an error occurs.

Examples

Example #1 dbase_numfields() Example

<?php

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i = 0; $i < $nf; $i++) {
  echo $rec[$i], "\n";
}

?>

See Also

  • dbase_numrecords() - Gets the number of records in a database

dbase_get_record
dbase_numrecords
dBase Functions


Gets the number of records in a database

dbase_numfields
dbase_open
dBase Functions
PHP Manual

dbase_numrecords

(PHP 4, PHP 5)

dbase_numrecords — Gets the number of records in a database

Description

int dbase_numrecords ( int $dbase_identifier )

Gets the number of records (rows) in the specified database.

Note: Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

The number of records in the database, or FALSE if an error occurs.

Examples

Example #1 Looping over all the records of the database

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      // do something here, for each record
  }
}

?>

See Also

  • dbase_numfields() - Gets the number of fields of a database

dbase_numfields
dbase_open
dBase Functions


Opens a database

dbase_numrecords
dbase_pack
dBase Functions
PHP Manual

dbase_open

(PHP 4, PHP 5)

dbase_open — Opens a database

Description

int dbase_open ( string $filename , int $mode )

dbase_open() opens a dBase database with the given access mode.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: This function is affected by open_basedir.

Parameters

filename

The name of the database. It can be a relative or absolute path to the file where dBase will store your data.

mode

An integer which correspond to those for the open() system call (Typically 0 means read-only, 1 means write-only, and 2 means read and write).

Note: You can't open a dBase file in write-only mode as the function will fail to read the headers information and thus you can't use 1 as mode .

Examples

Example #1 Opening a dBase database file

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  // read some data ..

  dbase_close($db);
}

?>

Return Values

Returns a database link identifier if the database is successfully opened, or FALSE if an error occurred.

See Also

  • dbase_create() - Creates a database
  • dbase_close() - Closes a database

dbase_numrecords
dbase_pack
dBase Functions


Packs a database

dbase_open
dbase_replace_record
dBase Functions
PHP Manual

dbase_pack

(PHP 4, PHP 5)

dbase_pack — Packs a database

Description

bool dbase_pack ( int $dbase_identifier )

Packs the specified database by permanently deleting all records marked for deletion using dbase_delete_record().

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Emptying a dBase database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      dbase_delete_record($db, $i);
  }
  // expunge the database
  dbase_pack($db);
}

?>

See Also

  • dbase_delete_record() - Deletes a record from a database

dbase_open
dbase_replace_record
dBase Functions


Replaces a record in a database

dbase_pack
DB++
dBase Functions
PHP Manual

dbase_replace_record

(PHP 4, PHP 5)

dbase_replace_record — Replaces a record in a database

Description

bool dbase_replace_record ( int $dbase_identifier , array $record , int $record_number )

Replaces the given record in the database with the given data.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_replace_record() will fail.

Note: If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

record_number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Updating a record in the database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  // gets the old row
  $row = dbase_get_record_with_names($db, 1);

  // remove the 'deleted' entry
  unset($row['deleted']);

  // Update the date field with the current timestamp
  $row['date'] = date('Ymd');

  // Replace the record
  dbase_replace_record($db, $row, 1);
  dbase_close($db);
}

?>

See Also

  • dbase_add_record() - Adds a record to a database
  • dbase_delete_record() - Deletes a record from a database

dbase_pack
DB++
dBase Functions


Add a tuple to a relation

DB++ Functions
dbplus_aql
DB++ Functions
PHP Manual

dbplus_add

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_add — Add a tuple to a relation

Description

int dbplus_add ( resource $relation , array $tuple )

Adds a tuple to a relation .

Parameters

relation

tuple

An array of attribute/value pairs to be inserted into the given relation .

After successful execution this array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

Return Values

The function will return DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_errcode() - Get error string for given errorcode or last error

DB++ Functions
dbplus_aql
DB++ Functions


Perform AQL query

dbplus_add
dbplus_chdir
DB++ Functions
PHP Manual

dbplus_aql

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_aql — Perform AQL query

Description

resource dbplus_aql ( string $query [, string $server [, string $dbpath ]] )

Executes an AQL query on the given server and dbpath .

Parameters

query

The AQL query to be executed. Further information on the AQL A... Query Language is provided in the original db++ manual.

server

dbpath

Return Values

Returns a relation handle on success. The result data may be fetched from this relation by calling dbplus_next() and dbplus_curr(). Other relation access functions will not work on a result relation.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_add
dbplus_chdir
DB++ Functions


Get/Set database virtual current directory

dbplus_aql
dbplus_close
DB++ Functions
PHP Manual

dbplus_chdir

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_chdir — Get/Set database virtual current directory

Description

string dbplus_chdir ([ string $newdir ] )

Changes the virtual current directory where relation files will be looked for by dbplus_open().

Parameters

newdir

The new directory for relation files. You can omit this parameter to query the current working directory.

Return Values

Returns the absolute path of the current directory.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_aql
dbplus_close
DB++ Functions


Close a relation

dbplus_chdir
dbplus_curr
DB++ Functions
PHP Manual

dbplus_close

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_close — Close a relation

Description

mixed dbplus_close ( resource $relation )

Closes a relation previously opened by dbplus_open().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_chdir
dbplus_curr
DB++ Functions


Get current tuple from relation

dbplus_close
dbplus_errcode
DB++ Functions
PHP Manual

dbplus_curr

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_curr — Get current tuple from relation

Description

int dbplus_curr ( resource $relation , array &$tuple )

Reads the data for the current tuple for the given relation .

Parameters

relation

A relation opened by dbplus_open().

tuple

The data will be passed back in this parameter, as an associative array.

Return Values

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation
  • dbplus_errcode() - Get error string for given errorcode or last error

dbplus_close
dbplus_errcode
DB++ Functions


Get error string for given errorcode or last error

dbplus_curr
dbplus_errno
DB++ Functions
PHP Manual

dbplus_errcode

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_errcode — Get error string for given errorcode or last error

Description

string dbplus_errcode ([ int $errno ] )

Returns a clear error string for the given error code.

Parameters

errno

The error code. If not provided, the result code of the last db++ operation is assumed.

Return Values

Returns the error message.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_curr
dbplus_errno
DB++ Functions


Get error code for last operation

dbplus_errcode
dbplus_find
DB++ Functions
PHP Manual

dbplus_errno

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_errno — Get error code for last operation

Description

int dbplus_errno ( void )

Returns the error code returned by the last db++ operation.

Return Values

Returns the error code, as an integer.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_errcode() - Get error string for given errorcode or last error

dbplus_errcode
dbplus_find
DB++ Functions


Set a constraint on a relation

dbplus_errno
dbplus_first
DB++ Functions
PHP Manual

dbplus_find

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_find — Set a constraint on a relation

Description

int dbplus_find ( resource $relation , array $constraints , mixed $tuple )

Places a constraint on the given relation .

Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.

Parameters

relation

A relation opened by dbplus_open().

constraints

Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.

The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.

tuple

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_unselect() - Remove a constraint from relation

dbplus_errno
dbplus_first
DB++ Functions


Get first tuple from relation

dbplus_find
dbplus_flush
DB++ Functions
PHP Manual

dbplus_first

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_first — Get first tuple from relation

Description

int dbplus_first ( resource $relation , array &$tuple )

Reads the data for the first tuple for the given relation , makes it the current tuple and pass it back as an associative array in tuple .

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation
  • dbplus_errcode() - Get error string for given errorcode or last error

dbplus_find
dbplus_flush
DB++ Functions


Flush all changes made on a relation

dbplus_first
dbplus_freealllocks
DB++ Functions
PHP Manual

dbplus_flush

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_flush — Flush all changes made on a relation

Description

int dbplus_flush ( resource $relation )

Writes all changes applied to relation since the last flush to disk.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_errcode() - Get error string for given errorcode or last error

dbplus_first
dbplus_freealllocks
DB++ Functions


Free all locks held by this client

dbplus_flush
dbplus_freelock
DB++ Functions
PHP Manual

dbplus_freealllocks

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freealllocks — Free all locks held by this client

Description

int dbplus_freealllocks ( void )

Frees all tuple locks held by this client.

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation

dbplus_flush
dbplus_freelock
DB++ Functions


Release write lock on tuple

dbplus_freealllocks
dbplus_freerlocks
DB++ Functions
PHP Manual

dbplus_freelock

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freelock — Release write lock on tuple

Description

int dbplus_freelock ( resource $relation , string $tuple )

Releases a write lock on the given tuple previously obtained by dbplus_getlock().

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation
  • dbplus_freealllocks() - Free all locks held by this client

dbplus_freealllocks
dbplus_freerlocks
DB++ Functions


Free all tuple locks on given relation

dbplus_freelock
dbplus_getlock
DB++ Functions
PHP Manual

dbplus_freerlocks

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freerlocks — Free all tuple locks on given relation

Description

int dbplus_freerlocks ( resource $relation )

Frees all tuple locks held on the given relation .

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freealllocks() - Free all locks held by this client

dbplus_freelock
dbplus_getlock
DB++ Functions


Get a write lock on a tuple

dbplus_freerlocks
dbplus_getunique
DB++ Functions
PHP Manual

dbplus_getlock

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_getlock — Get a write lock on a tuple

Description

int dbplus_getlock ( resource $relation , string $tuple )

Requests a write lock on the specified tuple .

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation
  • dbplus_freealllocks() - Free all locks held by this client

dbplus_freerlocks
dbplus_getunique
DB++ Functions


Get an id number unique to a relation

dbplus_getlock
dbplus_info
DB++ Functions
PHP Manual

dbplus_getunique

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_getunique — Get an id number unique to a relation

Description

int dbplus_getunique ( resource $relation , int $uniqueid )

Obtains a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid .

Parameters

relation

A relation opened by dbplus_open().

uniqueid

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_getlock
dbplus_info
DB++ Functions


Get information about a relation

dbplus_getunique
dbplus_last
DB++ Functions
PHP Manual

dbplus_info

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_info — Get information about a relation

Description

int dbplus_info ( resource $relation , string $key , array &$result )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

key

result

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_getunique
dbplus_last
DB++ Functions


Get last tuple from relation

dbplus_info
dbplus_lockrel
DB++ Functions
PHP Manual

dbplus_last

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_last — Get last tuple from relation

Description

int dbplus_last ( resource $relation , array &$tuple )

Reads the data for the last tuple for the given relation , makes it the current tuple and pass it back as an associative array in tuple .

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation

dbplus_info
dbplus_lockrel
DB++ Functions


Request write lock on relation

dbplus_last
dbplus_next
DB++ Functions
PHP Manual

dbplus_lockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_lockrel — Request write lock on relation

Description

int dbplus_lockrel ( resource $relation )

Requests a write lock on the given relation .

Other clients may still query the relation, but can't alter it while it is locked.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_last
dbplus_next
DB++ Functions


Get next tuple from relation

dbplus_lockrel
dbplus_open
DB++ Functions
PHP Manual

dbplus_next

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_next — Get next tuple from relation

Description

int dbplus_next ( resource $relation , array &$tuple )

Reads the data for the next tuple for the given relation , makes it the current tuple and will pass it back as an associative array in tuple .

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_last() - Get last tuple from relation

dbplus_lockrel
dbplus_open
DB++ Functions


Open relation file

dbplus_next
dbplus_prev
DB++ Functions
PHP Manual

dbplus_open

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_open — Open relation file

Description

resource dbplus_open ( string $name )

Opens the given relation file.

Parameters

name

Can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

Return Values

On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_next
dbplus_prev
DB++ Functions


Get previous tuple from relation

dbplus_open
dbplus_rchperm
DB++ Functions
PHP Manual

dbplus_prev

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_prev — Get previous tuple from relation

Description

int dbplus_prev ( resource $relation , array &$tuple )

Reads the data for the previous tuple for the given relation , makes it the current tuple and will pass it back as an associative array in tuple .

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation

dbplus_open
dbplus_rchperm
DB++ Functions


Change relation permissions

dbplus_prev
dbplus_rcreate
DB++ Functions
PHP Manual

dbplus_rchperm

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rchperm — Change relation permissions

Description

int dbplus_rchperm ( resource $relation , int $mask , string $user , string $group )

Changes access permissions as specified by mask , user and group . The values for these are operating system specific.

Parameters

relation

A relation opened by dbplus_open().

mask

user

group

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_prev
dbplus_rcreate
DB++ Functions


Creates a new DB++ relation

dbplus_rchperm
dbplus_rcrtexact
DB++ Functions
PHP Manual

dbplus_rcreate

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcreate — Creates a new DB++ relation

Description

resource dbplus_rcreate ( string $name , mixed $domlist [, bool $overwrite ] )

Creates a new relation. Any existing relation sharing the same name will be overwritten if the relation is currently not in use and overwrite is set to TRUE.

Parameters

name

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

This parameter should contain the domain specification for the new relation within an array of domain description strings. A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.

Note: This function will also accept a string with space delimited domain description strings, but it is recommended to use an array

overwrite

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_rchperm
dbplus_rcrtexact
DB++ Functions


Creates an exact but empty copy of a relation including indices

dbplus_rcreate
dbplus_rcrtlike
DB++ Functions
PHP Manual

dbplus_rcrtexact

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices

Description

mixed dbplus_rcrtexact ( string $name , resource $relation [, bool $overwrite ] )

dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name .

Parameters

name

relation

The copied relation, opened by dbplus_open().

overwrite

An existing relation by the same name will only be overwritten if this parameter is set to TRUE and no other process is currently using the relation.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_rcreate
dbplus_rcrtlike
DB++ Functions


Creates an empty copy of a relation with default indices

dbplus_rcrtexact
dbplus_resolve
DB++ Functions
PHP Manual

dbplus_rcrtlike

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcrtlike — Creates an empty copy of a relation with default indices

Description

mixed dbplus_rcrtlike ( string $name , resource $relation [, int $overwrite ] )

dbplus_rcrtexact() will create an empty copy of the given relation under a new name , but with default indices.

Parameters

name

relation

The copied relation, opened by dbplus_open().

overwrite

An existing relation by the same name will only be overwritten if this parameter is set to TRUE and no other process is currently using the relation.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_rcrtexact
dbplus_resolve
DB++ Functions


Resolve host information for relation

dbplus_rcrtlike
dbplus_restorepos
DB++ Functions
PHP Manual

dbplus_resolve

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_resolve — Resolve host information for relation

Description

array dbplus_resolve ( string $relation_name )

dbplus_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host.

Parameters

relation_name

The relation name.

Return Values

Returns an array containing these values under the keys sid, host and host_path or FALSE on error.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_tcl() - Execute TCL code on server side

dbplus_rcrtlike
dbplus_restorepos
DB++ Functions


Restore position

dbplus_resolve
dbplus_rkeys
DB++ Functions
PHP Manual

dbplus_restorepos

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_restorepos — Restore position

Description

int dbplus_restorepos ( resource $relation , array $tuple )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_resolve
dbplus_rkeys
DB++ Functions


Specify new primary key for a relation

dbplus_restorepos
dbplus_ropen
DB++ Functions
PHP Manual

dbplus_rkeys

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rkeys — Specify new primary key for a relation

Description

mixed dbplus_rkeys ( resource $relation , mixed $domlist )

dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist .

Parameters

relation

A relation opened by dbplus_open().

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_restorepos
dbplus_ropen
DB++ Functions


Open relation file local

dbplus_rkeys
dbplus_rquery
DB++ Functions
PHP Manual

dbplus_ropen

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_ropen — Open relation file local

Description

resource dbplus_ropen ( string $name )

dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_curr() and dbplus_next() may be applied to the returned relation.

Parameters

name

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_rkeys
dbplus_rquery
DB++ Functions


Perform local (raw) AQL query

dbplus_ropen
dbplus_rrename
DB++ Functions
PHP Manual

dbplus_rquery

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rquery — Perform local (raw) AQL query

Description

resource dbplus_rquery ( string $query [, string $dbpath ] )

dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.

Parameters

query

dbpath

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_ropen
dbplus_rrename
DB++ Functions


Rename a relation

dbplus_rquery
dbplus_rsecindex
DB++ Functions
PHP Manual

dbplus_rrename

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rrename — Rename a relation

Description

int dbplus_rrename ( resource $relation , string $name )

dbplus_rrename() will change the name of relation to name .

Parameters

relation

A relation opened by dbplus_open().

name

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_rquery
dbplus_rsecindex
DB++ Functions


Create a new secondary index for a relation

dbplus_rrename
dbplus_runlink
DB++ Functions
PHP Manual

dbplus_rsecindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rsecindex — Create a new secondary index for a relation

Description

mixed dbplus_rsecindex ( resource $relation , mixed $domlist , int $type )

dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

Parameters

relation

A relation opened by dbplus_open().

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

type

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_rrename
dbplus_runlink
DB++ Functions


Remove relation from filesystem

dbplus_rsecindex
dbplus_rzap
DB++ Functions
PHP Manual

dbplus_runlink

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_runlink — Remove relation from filesystem

Description

int dbplus_runlink ( resource $relation )

dbplus_runlink() will close and remove the relation .

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_rsecindex
dbplus_rzap
DB++ Functions


Remove all tuples from relation

dbplus_runlink
dbplus_savepos
DB++ Functions
PHP Manual

dbplus_rzap

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rzap — Remove all tuples from relation

Description

int dbplus_rzap ( resource $relation )

dbplus_rzap() will remove all tuples from relation .

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_runlink
dbplus_savepos
DB++ Functions


Save position

dbplus_rzap
dbplus_setindex
DB++ Functions
PHP Manual

dbplus_savepos

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_savepos — Save position

Description

int dbplus_savepos ( resource $relation )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_rzap
dbplus_setindex
DB++ Functions


Set index

dbplus_savepos
dbplus_setindexbynumber
DB++ Functions
PHP Manual

dbplus_setindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_setindex — Set index

Description

int dbplus_setindex ( resource $relation , string $idx_name )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

idx_name

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_savepos
dbplus_setindexbynumber
DB++ Functions


Set index by number

dbplus_setindex
dbplus_sql
DB++ Functions
PHP Manual

dbplus_setindexbynumber

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_setindexbynumber — Set index by number

Description

int dbplus_setindexbynumber ( resource $relation , int $idx_number )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

idx_number

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_setindex
dbplus_sql
DB++ Functions


Perform SQL query

dbplus_setindexbynumber
dbplus_tcl
DB++ Functions
PHP Manual

dbplus_sql

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_sql — Perform SQL query

Description

resource dbplus_sql ( string $query [, string $server [, string $dbpath ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

query

server

dbpath

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_setindexbynumber
dbplus_tcl
DB++ Functions


Execute TCL code on server side

dbplus_sql
dbplus_tremove
DB++ Functions
PHP Manual

dbplus_tcl

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_tcl — Execute TCL code on server side

Description

string dbplus_tcl ( int $sid , string $script )

A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.

dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.

Parameters

sid

script

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_resolve() - Resolve host information for relation

dbplus_sql
dbplus_tremove
DB++ Functions


Remove tuple and return new current tuple

dbplus_tcl
dbplus_undo
DB++ Functions
PHP Manual

dbplus_tremove

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_tremove — Remove tuple and return new current tuple

Description

int dbplus_tremove ( resource $relation , array $tuple [, array &$current ] )

dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current , if given, will contain the data of the new current tuple after calling dbplus_tremove().

Parameters

relation

A relation opened by dbplus_open().

tuple

current

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_tcl
dbplus_undo
DB++ Functions


Undo

dbplus_tremove
dbplus_undoprepare
DB++ Functions
PHP Manual

dbplus_undo

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_undo — Undo

Description

int dbplus_undo ( resource $relation )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_tremove
dbplus_undoprepare
DB++ Functions


Prepare undo

dbplus_undo
dbplus_unlockrel
DB++ Functions
PHP Manual

dbplus_undoprepare

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_undoprepare — Prepare undo

Description

int dbplus_undoprepare ( resource $relation )
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_undo
dbplus_unlockrel
DB++ Functions


Give up write lock on relation

dbplus_undoprepare
dbplus_unselect
DB++ Functions
PHP Manual

dbplus_unlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_unlockrel — Give up write lock on relation

Description

int dbplus_unlockrel ( resource $relation )

Release a write lock previously obtained by dbplus_lockrel().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_undoprepare
dbplus_unselect
DB++ Functions


Remove a constraint from relation

dbplus_unlockrel
dbplus_update
DB++ Functions
PHP Manual

dbplus_unselect

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_unselect — Remove a constraint from relation

Description

int dbplus_unselect ( resource $relation )

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation .

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_unlockrel
dbplus_update
DB++ Functions


Update specified tuple in relation

dbplus_unselect
dbplus_xlockrel
DB++ Functions
PHP Manual

dbplus_update

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_update — Update specified tuple in relation

Description

int dbplus_update ( resource $relation , array $old , array $new )

dbplus_update() replaces the old tuple with the data from the new one, only if the old completely matches a tuple within relation .

Parameters

relation

A relation opened by dbplus_open().

old

The old tuple.

new

The new tuple.

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_unselect
dbplus_xlockrel
DB++ Functions


Request exclusive lock on relation

dbplus_update
dbplus_xunlockrel
DB++ Functions
PHP Manual

dbplus_xlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_xlockrel — Request exclusive lock on relation

Description

int dbplus_xlockrel ( resource $relation )

Request an exclusive lock on relation preventing even read access from other clients.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • dbplus_xunlockrel() - Free exclusive lock on relation

dbplus_update
dbplus_xunlockrel
DB++ Functions


Free exclusive lock on relation

dbplus_xlockrel
FrontBase
DB++ Functions
PHP Manual

dbplus_xunlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_xunlockrel — Free exclusive lock on relation

Description

int dbplus_xunlockrel ( resource $relation )

Releases an exclusive lock previously obtained by dbplus_xlockrel().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

dbplus_xlockrel
FrontBase
DB++ Functions


Close an open connection/database

dbx Functions
dbx_compare
dbx Functions
PHP Manual

dbx_close

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_close — Close an open connection/database

Description

int dbx_close ( object $link_identifier )

Parameters

link_identifier

The DBX link object to close.

Return Values

Returns 1 on success and 0 on errors.

Examples

Example #1 dbx_close() example

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Notes

Note: Always refer to the module-specific documentation as well.

See Also

  • dbx_connect() - Open a connection/database

dbx Functions
dbx_compare
dbx Functions


Compare two rows for sorting purposes

dbx_close
dbx_connect
dbx Functions
PHP Manual

dbx_compare

(PHP 4 >= 4.1.0, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_compare — Compare two rows for sorting purposes

Description

int dbx_compare ( array $row_a , array $row_b , string $column_key [, int $flags = DBX_CMP_ASC | DBX_CMP_NATIVE ] )

dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.

Parameters

row_a

First row

row_b

Second row

column_key

The compared column

flags

The flags can be set to specify comparison direction:

  • DBX_CMP_ASC - ascending order
  • DBX_CMP_DESC - descending order

and the preferred comparison type:

  • DBX_CMP_NATIVE - no type conversion
  • DBX_CMP_TEXT - compare items as strings
  • DBX_CMP_NUMBER - compare items numerically

One of the direction and one of the type constant can be combined with bitwise OR operator (|).

Return Values

Returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC.

Examples

Example #1 dbx_compare() example

<?php
function user_re_order($a, $b)
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM table ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // date in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

See Also

  • dbx_sort() - Sort a result from a dbx_query by a custom sort function

dbx_close
dbx_connect
dbx Functions


Open a connection/database

dbx_compare
dbx_error
dbx Functions
PHP Manual

dbx_connect

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_connect — Open a connection/database

Description

object dbx_connect ( mixed $module , string $host , string $database , string $username , string $password [, int $persistent ] )

Opens a connection to a database.

Parameters

module

The module parameter can be either a string or a constant, though the latter form is preferred. The possible values are given below, but keep in mind that they only work if the module is actually loaded.

  • DBX_MYSQL or "mysql"
  • DBX_ODBC or "odbc"
  • DBX_PGSQL or "pgsql"
  • DBX_MSSQL or "mssql"
  • DBX_FBSQL or "fbsql"
  • DBX_SYBASECT or "sybase_ct"
  • DBX_OCI8 or "oci8"
  • DBX_SQLITE or "sqlite"

host

The SQL server host

database

The database name

username

The username

password

The password

persistent

The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.

The host , database , username and password parameters are expected, but not always used depending on the connect functions for the abstracted module.

Return Values

Returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned.

The returned object has three properties:

database
It is the name of the currently selected database.
handle

It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close($link->handle); // dbx_close($link) would be better here
?>

module
It is used internally by dbx only, and is actually the module number mentioned above.

Changelog

Version | Description
5.0.0 | Introduced DBX_SQLITE.
4.3.0 | Introduced DBX_OCI8.
4.2.0 | Introduced DBX_SYBASECT.
4.1.0 | Introduced DBX_FBSQL.

Examples

Example #1 dbx_connect() example

<?php
$link = dbx_connect(DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Notes

Note: Always refer to the module-specific documentation as well.

See Also

  • dbx_close() - Close an open connection/database

dbx_compare
dbx_error
dbx Functions


Report the error message of the latest function call in the module

dbx_connect
dbx_escape_string
dbx Functions
PHP Manual

dbx_error

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_error — Report the error message of the latest function call in the module

Description

string dbx_error ( object $link_identifier )

dbx_error() returns the last error message.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

Return Values

Returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.

Examples

Example #1 dbx_error() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "select id from non_existing_table");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

Notes

Note: Always refer to the module-specific documentation as well.
The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.
The error message for Oracle (oci8) is not implemented yet.

dbx_connect
dbx_escape_string
dbx Functions


Escape a string so it can safely be used in an sql-statement

dbx_error
dbx_fetch_row
dbx Functions
PHP Manual

dbx_escape_string

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_escape_string — Escape a string so it can safely be used in an sql-statement

Description

string dbx_escape_string ( object $link_identifier , string $text )

Escape the given string so that it can safely be used in an sql-statement.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

text

The string to escape.

Return Values

Returns the text, escaped where necessary (such as quotes, backslashes etc). On error, NULL is returned.

Examples

Example #1 dbx_escape_string() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$text = dbx_escape_string($link, "It\'s quoted and backslashed (\\).");
$result = dbx_query($link, "insert into tbl (txt) values ('" . $text . "')");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

See Also

  • dbx_query() - Send a query and fetch all results (if any)

dbx_error
dbx_fetch_row
dbx Functions


Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

dbx_escape_string
dbx_query
dbx Functions
PHP Manual

dbx_fetch_row

(PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_fetch_row — Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

Description

mixed dbx_fetch_row ( object $result_identifier )

dbx_fetch_row() fetches rows from a result identifier that had the DBX_RESULT_UNBUFFERED flag set.

When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row() will fail as all rows have already been fetched into the results data property.

As a side effect, the rows property of the query-result object is incremented for each successful call to dbx_fetch_row().

Parameters

result_identifier

A result set returned by dbx_query().

Return Values

Returns an object on success that contains the same information as any row would have in the dbx_query() result data property, including columns accessible by index or fieldname when the flags for dbx_query() were set that way.

Upon failure, returns 0 (e.g. when no more rows are available).

Examples

Example #1 How to handle the returned value

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

See Also

  • dbx_query() - Send a query and fetch all results (if any)

dbx_escape_string
dbx_query
dbx Functions


Send a query and fetch all results (if any)

dbx_fetch_row
dbx_sort
dbx Functions
PHP Manual

dbx_query

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_query — Send a query and fetch all results (if any)

Description

mixed dbx_query ( object $link_identifier , string $sql_statement [, int $flags ] )

Sends a query and fetch all results.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

sql_statement

SQL statement.

Data inside the query should be properly escaped.

flags

The flags parameter is used to control the amount of information that is returned. It may be any combination of the following constants with the bitwise OR operator (|). The DBX_COLNAMES_* flags override the dbx.colnames_case setting from php.ini.

DBX_RESULT_INDEX
It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0. If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.
DBX_RESULT_INFO
It provides info about columns, such as field names and field types.
DBX_RESULT_ASSOC
It effects that the field values can be accessed with the respective column names used as keys to the returned object's data property. Associated results are actually references to the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.
DBX_RESULT_UNBUFFERED
This flag will not create the data property, and the rows property will initially be 0. Use this flag for large datasets, and use dbx_fetch_row() to retrieve the results row by row. The dbx_fetch_row() function will return rows that are conformant to the flags set with this query. Incidentally, it will also update the rows each time it is called.
DBX_COLNAMES_UNCHANGED
The case of the returned column names will not be changed.
DBX_COLNAMES_UPPERCASE
The case of the returned column names will be changed to uppercase.
DBX_COLNAMES_LOWERCASE
The case of the returned column names will be changed to lowercase.

Note that DBX_RESULT_INDEX is always used, regardless of the actual value of flags parameter. This means that only the following combinations are effective:

  • DBX_RESULT_INDEX
  • DBX_RESULT_INDEX | DBX_RESULT_INFO
  • DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - this is the default, if flags is not specified.

Return Values

dbx_query() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set (i.e. a SELECT query, even if the result set is empty).

The returned object has four or five properties depending on flags :

handle

It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).

<?php
$result = dbx_query($link, "SELECT id FROM table");
mysql_field_len($result->handle, 0);
?>

cols and rows

These contain the number of columns (or fields) and rows (or records) respectively.

<?php
$result = dbx_query($link, 'SELECT id FROM table');
echo $result->rows; // number of records
echo $result->cols; // number of fields
?>

info (optional)
It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.

Example #1 lists each field's name and type

<?php
$result = dbx_query($link, 'SELECT id FROM table',
                     DBX_RESULT_INDEX | DBX_RESULT_INFO);

for ($i = 0; $i < $result->cols; $i++ ) {
    echo $result->info['name'][$i] . "\n";
    echo $result->info['type'][$i] . "\n";
}
?>
data
This property contains the actual resulting data, possibly associated with column names as well depending on flags . If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].

Example #2 outputs the content of data property into HTML table

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

echo "<table>\n";
foreach ($result->data as $row) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

Example #3 How to handle UNBUFFERED queries

<?php

$result = dbx_query ($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Changelog

Version | Description
5.0.0 | Introduced DBX_RESULT_UNBUFFERED.
4.3.0 | Introduced DBX_COLNAMES_UNCHANGED, DBX_COLNAMES_UPPERCASE, and DBX_COLNAMES_LOWERCASE.

Examples

Example #4 How to handle the returned value

<?php
$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

if (is_object($result) ) {
    // ... do some stuff here, see detailed examples below ...
    // first, print out field names and types
    // then, draw a table filled with the returned field values
} else {
    exit("Query failed");
}

dbx_close($link);
?>

Notes

Note: Always refer to the module-specific documentation as well.
Column names for queries on an Oracle database are returned in lowercase.

See Also

  • dbx_escape_string() - Escape a string so it can safely be used in an sql-statement
  • dbx_fetch_row() - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
  • dbx_connect() - Open a connection/database

dbx_fetch_row
dbx_sort
dbx Functions


Sort a result from a dbx_query by a custom sort function

dbx_query
ODBC
dbx Functions
PHP Manual

dbx_sort

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_sort — Sort a result from a dbx_query by a custom sort function

Description

bool dbx_sort ( object $result , string $user_compare_function )

Sort a result from a dbx_query() call with a custom sort function.

Parameters

result

A result set returned by dbx_query().

user_compare_function

The user-defined comparison function. It must accept two arguments and return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 dbx_sort() example

<?php
function user_re_order($a, $b)
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // data in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

Notes

Note: It is always better to use ORDER BY SQL clause instead of dbx_sort() if possible.

See Also

  • dbx_compare() - Compare two rows for sorting purposes

dbx_query
ODBC
dbx Functions


Overrides the domain for a single lookup

bindtextdomain
dcngettext
Gettext Functions
PHP Manual

dcgettext

(PHP 4, PHP 5)

dcgettext — Overrides the domain for a single lookup

Description

string dcgettext ( string $domain , string $message , int $category )

This function allows you to override the current domain for a single message lookup.

Parameters

domain

The domain

message

The message

category

The category

Return Values

A string on success.

See Also

  • gettext() - Lookup a message in the current domain

bindtextdomain
dcngettext
Gettext Functions


Plural version of dcgettext

dcgettext
dgettext
Gettext Functions
PHP Manual

dcngettext

(PHP 4 >= 4.2.0, PHP 5)

dcngettext — Plural version of dcgettext

Description

string dcngettext ( string $domain , string $msgid1 , string $msgid2 , int $n , int $category )

This function allows you to override the current domain for a single plural message lookup.

Parameters

domain

The domain

msgid1

msgid2

n

category

Return Values

A string on success.

See Also

  • ngettext() - Plural version of gettext

dcgettext
dgettext
Gettext Functions


Generates a backtrace

Error Handling Functions
debug_print_backtrace
Error Handling Functions
PHP Manual

debug_backtrace

(PHP 4 >= 4.3.0, PHP 5)

debug_backtrace — Generates a backtrace

Description

array debug_backtrace ([ bool $provide_object = true ] )

debug_backtrace() generates a PHP backtrace.

Parameters

provide_object

Whether or not to populate the "object" index.

Return Values

Returns an associative array. The possible returned elements are as follows:

Possible returned elements from debug_backtrace()
Name | Type | Description
function | string | The current function name. See also __FUNCTION__.
line | integer | The current line number. See also __LINE__.
file | string | The current file name. See also __FILE__.
class | string | The current class name. See also __CLASS__
object | object | The current object.
type | string | The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned.
args | array | If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s).

Changelog

Version | Description
5.2.5 | Added the optional parameter provide_object .
5.1.1 | Added the current object as a possible return element.

Examples

Example #1 debug_backtrace() example

<?php
// filename: /tmp/a.php

function a_test($str)
{
    echo "\nHi: $str";
    var_dump(debug_backtrace());
}

a_test('friend');
?>

<?php
// filename: /tmp/b.php
include_once '/tmp/a.php';
?>

Results similar to the following when executing /tmp/b.php:

Hi: friend
array(2) {
[0]=>
array(4) {
    ["file"] => string(10) "/tmp/a.php"
    ["line"] => int(10)
    ["function"] => string(6) "a_test"
    ["args"]=>
    array(1) {
      [0] => &string(6) "friend"
    }
}
[1]=>
array(4) {
    ["file"] => string(10) "/tmp/b.php"
    ["line"] => int(2)
    ["args"] =>
    array(1) {
      [0] => string(10) "/tmp/a.php"
    }
    ["function"] => string(12) "include_once"
  }
}

See Also

  • trigger_error() - Generates a user-level error/warning/notice message
  • debug_print_backtrace() - Prints a backtrace

Error Handling Functions
debug_print_backtrace
Error Handling Functions


Prints a backtrace

debug_backtrace
error_get_last
Error Handling Functions
PHP Manual

debug_print_backtrace

(PHP 5)

debug_print_backtrace — Prints a backtrace

Description

void debug_print_backtrace ( void )

debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 debug_print_backtrace() example

<?php
// include.php file

function a() {
    b();
}

function b() {
    c();
}

function c(){
    debug_print_backtrace();
}

a();

?>
<?php
// test.php file
// this is the file you should run

include 'include.php';
?>

The above example will output something similar to:

#0  eval() called at [/tmp/include.php:5]
#1  a() called at [/tmp/include.php:17]
#2  include(/tmp/include.php) called at [/tmp/test.php:3]

#0  c() called at [/tmp/include.php:10]
#1  b() called at [/tmp/include.php:6]
#2  a() called at [/tmp/include.php:17]
#3  include(/tmp/include.php) called at [/tmp/test.php:3]

See Also

  • debug_backtrace() - Generates a backtrace

debug_backtrace
error_get_last
Error Handling Functions


Decimal to binary

cosh
dechex
Math Functions
PHP Manual

decbin

(PHP 4, PHP 5)

decbin — Decimal to binary

Description

string decbin ( int $number )

Returns a string containing a binary representation of the given number argument.

Parameters

number

Decimal value to convert

Range of inputs on 32-bit machines
positive number | negative number | return value
0 | 0
1 | 1
2 | 10
... normal progression ...
2147483646 | 1111111111111111111111111111110
2147483647 (largest signed integer) | 1111111111111111111111111111111 (31 1's)
2147483648 | -2147483648 | 10000000000000000000000000000000
... normal progression ...
4294967294 | -2 | 11111111111111111111111111111110
4294967295 (largest unsigned integer) | -1 | 11111111111111111111111111111111 (32 1's)
Range of inputs on 64-bit machines
positive number | negative number | return value
0 | 0
1 | 1
2 | 10
... normal progression ...
9223372036854775806 | 111111111111111111111111111111111111111111111111111111111111110
9223372036854775807 (largest signed integer) | 111111111111111111111111111111111111111111111111111111111111111 (31 1's)
-9223372036854775808 | 1000000000000000000000000000000000000000000000000000000000000000
... normal progression ...
-2 | 1111111111111111111111111111111111111111111111111111111111111110
-1 | 1111111111111111111111111111111111111111111111111111111111111111 (64 1's)

Return Values

Binary string representation of number

Examples

Example #1 decbin() example

<?php
echo decbin(12) . "\n";
echo decbin(26);
?>

The above example will output:

1100
11010

See Also

  • bindec() - Binary to decimal
  • decoct() - Decimal to octal
  • dechex() - Decimal to hexadecimal
  • base_convert() - Convert a number between arbitrary bases
  • printf() - Output a formatted string, using %b, %032b or %064b as the format
  • sprintf(), using %b, %032b or %064b as the format

cosh
dechex
Math Functions


Decimal to hexadecimal

decbin
decoct
Math Functions
PHP Manual

dechex

(PHP 4, PHP 5)

dechex — Decimal to hexadecimal

Description

string dechex ( int $number )

Returns a string containing a hexadecimal representation of the given number argument. The largest number that can be converted is 4294967295 in decimal resulting to "ffffffff".

Parameters

number

Decimal value to convert

Return Values

Hexadecimal string representation of number

Examples

Example #1 dechex() example

<?php
echo dechex(10) . "\n";
echo dechex(47);
?>

The above example will output:

a
2f

See Also

  • hexdec() - Hexadecimal to decimal
  • decbin() - Decimal to binary
  • decoct() - Decimal to octal
  • base_convert() - Convert a number between arbitrary bases

decbin
decoct
Math Functions


Decimal to octal

dechex
deg2rad
Math Functions
PHP Manual

decoct

(PHP 4, PHP 5)

decoct — Decimal to octal

Description

string decoct ( int $number )

Returns a string containing an octal representation of the given number argument. The largest number that can be converted is 4294967295 in decimal resulting to "37777777777".

Parameters

number

Decimal value to convert

Return Values

Octal string representation of number

Examples

Example #1 decoct() example

<?php
echo decoct(15) . "\n";
echo decoct(264);
?>

The above example will output:

17
410

See Also

  • octdec() - Octal to decimal
  • decbin() - Decimal to binary
  • dechex() - Decimal to hexadecimal
  • base_convert() - Convert a number between arbitrary bases

dechex
deg2rad
Math Functions


Defines a named constant

constant
defined
Misc. Functions
PHP Manual

define

(PHP 4, PHP 5)

define — Defines a named constant

Description

bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )

Defines a named constant at runtime.

Parameters

name

The name of the constant.

value

The value of the constant; only scalar and null values are allowed. Scalar values are integer, float, string or boolean values. It is possible to define resource constants, however it is not recommended and may cause unpredictable behavior.

case_insensitive

If set to TRUE, the constant will be defined case-insensitive. The default behavior is case-sensitive; i.e. CONSTANT and Constant represent different values.

Note: Case-insensitive constants are stored as lower-case.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Defining Constants

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

define("GREETING", "Hello you.", true);
echo GREETING; // outputs "Hello you."
echo Greeting; // outputs "Hello you."

?>

See Also

  • defined() - Checks whether a given named constant exists
  • constant() - Returns the value of a constant
  • The section on Constants

constant
defined
Misc. Functions


Checks whether a given named constant exists

define
die
Misc. Functions
PHP Manual

defined

(PHP 4, PHP 5)

defined — Checks whether a given named constant exists

Description

bool defined ( string $name )

Checks whether the given constant exists and is defined.

Note: If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().

Parameters

name

The constant name.

Return Values

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

Examples

Example #1 Checking Constants

<?php
/* Note the use of quotes, this is important.  This example is checking
 * if the string 'TEST' is the name of a constant named TEST */
if (defined('TEST')) {
    echo TEST;
}
?>

See Also

  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • get_defined_constants() - Returns an associative array with the names of all the constants and their values
  • function_exists() - Return TRUE if the given function has been defined
  • The section on Constants

define
die
Misc. Functions


Converts the number in degrees to the radian equivalent

decoct
exp
Math Functions
PHP Manual

deg2rad

(PHP 4, PHP 5)

deg2rad — Converts the number in degrees to the radian equivalent

Description

float deg2rad ( float $number )

This function converts number from degrees to the radian equivalent.

Parameters

number

Angular value in degrees

Return Values

The radian equivalent of number

Examples

Example #1 deg2rad() example

<?php

echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)

?>

See Also

  • rad2deg() - Converts the radian number to the equivalent number in degrees

decoct
exp
Math Functions


See unlink or unset

copy
dirname
Filesystem Functions
PHP Manual

delete

delete — See unlink() or unset()

Description

void delete ( void )

This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.

Return Values

No value is returned.

See Also

  • unlink() - Deletes a file
  • unset() - Unset a given variable

copy
dirname
Filesystem Functions


Override the current domain

dcngettext
dngettext
Gettext Functions
PHP Manual

dgettext

(PHP 4, PHP 5)

dgettext — Override the current domain

Description

string dgettext ( string $domain , string $message )

The dgettext() function allows you to override the current domain for a single message lookup.

Parameters

domain

The domain

message

The message

Return Values

A string on success.

See Also

  • gettext() - Lookup a message in the current domain

dcngettext
dngettext
Gettext Functions


Equivalent to exit

defined
eval
Misc. Functions
PHP Manual

die

(PHP 4, PHP 5)

die — Equivalent to exit()

Description

This language construct is equivalent to exit().

defined
eval
Misc. Functions


Closes the file descriptor given by fd

Direct IO Functions
dio_fcntl
Direct IO Functions
PHP Manual

dio_close

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_close — Closes the file descriptor given by fd

Description

void dio_close ( resource $fd )

The function dio_close() closes the file descriptor fd .

Parameters

fd

The file descriptor returned by dio_open().

Return Values

No value is returned.

Examples

Example #1 Closing an open file descriptor

<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_close($fd);
?>

See Also

  • dio_open() - Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

Direct IO Functions
dio_fcntl
Direct IO Functions


Performs a c library fcntl on fd

dio_close
dio_open
Direct IO Functions
PHP Manual

dio_fcntl

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_fcntl — Performs a c library fcntl on fd

Description

mixed dio_fcntl ( resource $fd , int $cmd [, mixed $args ] )

The dio_fcntl() function performs the operation specified by cmd on the file descriptor fd . Some commands require additional arguments args to be supplied.

Parameters

fd

The file descriptor returned by dio_open().

cmd

Can be one of the following operations:

  • F_SETLK - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.

  • F_SETLKW - like F_SETLK, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.

  • F_GETLK - dio_fcntl() returns an associative array (as described above) if someone else prevents lock. If there is no obstruction key "type" will set to F_UNLCK.

  • F_DUPFD - finds the lowest numbered available file descriptor greater than or equal to args and returns them.

  • F_SETFL - Sets the file descriptors flags to the value specified by args , which can be O_APPEND, O_NONBLOCK or O_ASYNC. To use O_ASYNC you will need to use the PCNTL extension.

args

args is an associative array, when cmd is F_SETLK or F_SETLLW, with the following keys:

  • "start" - offset where lock begins

  • "length" - size of locked area. zero means to end of file

  • "wenth" - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR

  • "type" - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)

Return Values

Returns the result of the C call.

Examples

Example #1 Setting and clearing a lock

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

if (dio_fcntl($fd, F_SETLK, Array("type"=>F_WRLCK)) == -1) {
   // the file descriptor appears locked
   echo "The lock can not be cleared. It is held by someone else.";
} else {
   echo "Lock succesfully set/cleared";
}

dio_close($fd);
?>

Notes

Note: This function is not implemented on Windows platforms.

dio_close
dio_open
Direct IO Functions


Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

dio_fcntl
dio_read
Direct IO Functions
PHP Manual

dio_open

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

Description

resource dio_open ( string $filename , int $flags [, int $mode = 0 ] )

dio_open() opens a file and returns a new file descriptor for it.

Parameters

filename

The pathname of the file to open.

flags

The flags parameter is a bitwise-ORed value comprising flags from the following list. This value must include one of O_RDONLY, O_WRONLY, or O_RDWR. Additionally, it may include any combination of the other flags from this list.

  • O_RDONLY - opens the file for read access.

  • O_WRONLY - opens the file for write access.

  • O_RDWR - opens the file for both reading and writing.

  • O_CREAT - creates the file, if it doesn't already exist.

  • O_EXCL - if both O_CREAT and O_EXCL are set and the file already exists, causes dio_open() to fail.

  • O_TRUNC - if the file exists and is opened for write access, the file will be truncated to zero length.

  • O_APPEND - write operations write data at the end of the file.

  • O_NONBLOCK - sets non blocking mode.

  • O_NOCTTY - prevent the OS from assigning the opened file as the process's controlling terminal when opening a TTY device file.

mode

If flags contains O_CREAT, mode will set the permissions of the file (creation permissions). Mode is required for correct operation when O_CREAT is specified in mode and is ignored otherwise.

The actual permissions assigned to the created file will be affected by the process's umask setting as per usual.

Return Values

A file descriptor or FALSE on error.

Examples

Example #1 Opening a file descriptor

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_close($fd);
?>

See Also

  • dio_close() - Closes the file descriptor given by fd

dio_fcntl
dio_read
Direct IO Functions


Reads bytes from a file descriptor

dio_open
dio_seek
Direct IO Functions
PHP Manual

dio_read

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_read — Reads bytes from a file descriptor

Description

string dio_read ( resource $fd [, int $len = 1024 ] )

The function dio_read() reads and returns len bytes from file with descriptor fd .

Parameters

fd

The file descriptor returned by dio_open().

len

The number of bytes to read. If not specified, dio_read() reads 1K sized block.

Return Values

The bytes read from fd .

See Also

  • dio_write() - Writes data to fd with optional truncation at length

dio_open
dio_seek
Direct IO Functions


Seeks to pos on fd from whence

dio_read
dio_stat
Direct IO Functions
PHP Manual

dio_seek

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_seek — Seeks to pos on fd from whence

Description

int dio_seek ( resource $fd , int $pos [, int $whence = SEEK_SET ] )

The function dio_seek() is used to change the file position of the given file descriptor.

Parameters

fd

The file descriptor returned by dio_open().

pos

The new position.

whence

Specifies how the position pos should be interpreted:

  • SEEK_SET (default) - specifies that pos is specified from the beginning of the file.

  • SEEK_CUR - Specifies that pos is a count of characters from the current file position. This count may be positive or negative.

  • SEEK_END - Specifies that pos is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position.

Return Values

Examples

Example #1 Positioning in a file

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_seek($fd, 10, SEEK_SET);
// position is now at 10 characters from the start of the file

dio_seek($fd, -2, SEEK_CUR);
// position is now at 8 characters from the start of the file

dio_seek($fd, -5, SEEK_END);
// position is now at 5 characters from the end of the file

dio_seek($fd, 10, SEEK_END);
// position is now at 10 characters past the end of the file.
// The 10 characters between the end of the file and the current
// position are filled with zeros.

dio_close($fd);
?>

dio_read
dio_stat
Direct IO Functions


Gets stat information about the file descriptor fd

dio_seek
dio_tcsetattr
Direct IO Functions
PHP Manual

dio_stat

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_stat — Gets stat information about the file descriptor fd

Description

array dio_stat ( resource $fd )

dio_stat() returns information about the given file descriptor.

Parameters

fd

The file descriptor returned by dio_open().

Return Values

Returns an associative array with the following keys:

  • "device" - device

  • "inode" - inode

  • "mode" - mode

  • "nlink" - number of hard links

  • "uid" - user id

  • "gid" - group id

  • "device_type" - device type (if inode device)

  • "size" - total size in bytes

  • "blocksize" - blocksize

  • "blocks" - number of blocks allocated

  • "atime" - time of last access

  • "mtime" - time of last modification

  • "ctime" - time of last change

On error dio_stat() returns NULL.

dio_seek
dio_tcsetattr
Direct IO Functions


Sets terminal attributes and baud rate for a serial port

dio_stat
dio_truncate
Direct IO Functions
PHP Manual

dio_tcsetattr

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.5)

dio_tcsetattr — Sets terminal attributes and baud rate for a serial port

Description

bool dio_tcsetattr ( resource $fd , array $options )

dio_tcsetattr() sets the terminal attributes and baud rate of the open fd .

Parameters

fd

The file descriptor returned by dio_open().

options

The currently available options are:

  • 'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800, 1200,600,300,200,150,134,110,75 or 50, default value is 9600.

  • 'bits' - data bits - can be 8,7,6 or 5. Default value is 8.

  • 'stop' - stop bits - can be 1 or 2. Default value is 1.

  • 'parity' - can be 0,1 or 2. Default value is 0.

Return Values

No value is returned.

Examples

Example #1 Setting the baud rate on a serial port

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_fcntl($fd, F_SETFL, O_SYNC);

dio_tcsetattr($fd, array(
  'baud' => 9600,
  'bits' => 8,
  'stop'  => 1,
  'parity' => 0
));

while (1) {

  $data = dio_read($fd, 256);

  if ($data) {
      echo $data;
  }
}

?>

Notes

Note: This function is not implemented on Windows platforms.

dio_stat
dio_truncate
Direct IO Functions


Truncates file descriptor fd to offset bytes

dio_tcsetattr
dio_write
Direct IO Functions
PHP Manual

dio_truncate

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_truncate — Truncates file descriptor fd to offset bytes

Description

bool dio_truncate ( resource $fd , int $offset )

dio_truncate() truncates a file to at most offset bytes in size.

If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes.

Parameters

fd

The file descriptor returned by dio_open().

offset

The offset in bytes.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is not implemented on Windows platforms.

dio_tcsetattr
dio_write
Direct IO Functions


Writes data to fd with optional truncation at length

dio_truncate
Directories
Direct IO Functions
PHP Manual

dio_write

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_write — Writes data to fd with optional truncation at length

Description

int dio_write ( resource $fd , string $data [, int $len = 0 ] )

dio_write() writes up to len bytes from data to file fd .

Parameters

fd

The file descriptor returned by dio_open().

data

The written data.

len

The length of data to write in bytes. If not specified, the function writes all the data to the specified file.

Return Values

Returns the number of bytes written to fd .

See Also

  • dio_read() - Reads bytes from a file descriptor

dio_truncate
Directories
Direct IO Functions


Returns directory name component of path

delete
disk_free_space
Filesystem Functions
PHP Manual

dirname

(PHP 4, PHP 5)

dirname — Returns directory name component of path

Description

string dirname ( string $path )

Given a string containing a path to a file, this function will return the name of the directory.

Parameters

path

A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

Return Values

Returns the name of the directory. If there are no slashes in path , a dot ('.') is returned, indicating the current directory. Otherwise, the returned string is path with any trailing /component removed.

Changelog

Version | Description
5.0.0 | dirname() is now binary safe
4.0.3 | dirname() was fixed to be POSIX-compliant.

Examples

Example #1 dirname() example

<?php
$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"
?>

Notes

Note: Since PHP 4.3.0, you will often get a slash or a dot back from dirname() in situations where the older functionality would have given you the empty string.

Check the following change example:

<?php

//before PHP 4.3.0
dirname('c:/'); // returned '.'

//after PHP 4.3.0
dirname('c:/x'); // returns 'c:\'
dirname('c:/Temp/x'); // returns 'c:/Temp'
dirname('/x'); // returns '\'

?>

See Also

  • basename() - Returns filename component of path
  • pathinfo() - Returns information about a file path
  • realpath() - Returns canonicalized absolute pathname

delete
disk_free_space
Filesystem Functions


Returns available space in directory

dirname
disk_total_space
Filesystem Functions
PHP Manual

disk_free_space

(PHP 4 >= 4.1.0, PHP 5)

disk_free_space — Returns available space in directory

Description

float disk_free_space ( string $directory )

Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.

Parameters

directory

A directory of the filesystem or disk partition.

Note: Given a file name instead of a directory, the behaviour of the function is unspecified and may differ between operating systems and PHP versions.

Return Values

Returns the number of available bytes as a float or FALSE on failure.

Examples

Example #1 disk_free_space() example

<?php
// $df contains the number of bytes available on "/"
$df = disk_free_space("/");

// On Windows:
disk_free_space("C:");
disk_free_space("D:");
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

See Also

  • disk_total_space() - Returns the total size of a directory

dirname
disk_total_space
Filesystem Functions


Returns the total size of a directory

disk_free_space
diskfreespace
Filesystem Functions
PHP Manual

disk_total_space

(PHP 4 >= 4.1.0, PHP 5)

disk_total_space — Returns the total size of a directory

Description

float disk_total_space ( string $directory )

Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition.

Parameters

directory

A directory of the filesystem or disk partition.

Return Values

Returns the total number of bytes as a float or FALSE on failure.

Examples

Example #1 disk_total_space() example

<?php
// $df contains the total number of bytes available on "/"
$df = disk_total_space("/");

// On Windows:
disk_total_space("C:");
disk_total_space("D:");
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

See Also

  • disk_free_space() - Returns available space in directory

disk_free_space
diskfreespace
Filesystem Functions


Alias of disk_free_space

disk_total_space
fclose
Filesystem Functions
PHP Manual

diskfreespace

(PHP 4, PHP 5)

diskfreespace — Alias of disk_free_space()

Description

This function is an alias of: disk_free_space().

disk_total_space
fclose
Filesystem Functions


Loads a PHP extension at runtime

assert
extension_loaded
PHP Options/Info Functions
PHP Manual

dl

(PHP 4, PHP 5)

dl — Loads a PHP extension at runtime

Description

int dl ( string $library )

Loads the PHP extension given by the parameter library .

Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).

Warning

This function has been removed from some SAPI's in PHP 5.3.

Parameters

library

This parameter is only the filename of the extension to load which also depends on your platform. For example, the sockets extension (if compiled as a shared module, not the default!) would be called sockets.so on Unix platforms whereas it is called php_sockets.dll on the Windows platform.

The directory where the extension is loaded from depends on your platform:

Windows - If not explicitly set in the php.ini, the extension is loaded from C:\php4\extensions\ (PHP4) or C:\php5\ (PHP5) by default.

Unix - If not explicitly set in the php.ini, the default extension directory depends on

  • whether PHP has been built with --enable-debug or not
  • whether PHP has been built with (experimental) ZTS (Zend Thread Safety) support or not
  • the current internal ZEND_MODULE_API_NO (Zend internal module API number, which is basically the date on which a major module API change happened, e.g. 20010901)

Taking into account the above, the directory then defaults to <install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO, e.g. /usr/local/php/lib/php/extensions/debug-non-zts-20010901 or /usr/local/php/lib/php/extensions/no-debug-zts-20010901.

Return Values

Returns TRUE on success or FALSE on failure. If the functionality of loading modules is not available or has been disabled (either by setting enable_dl off or by enabling safe mode in php.ini) an E_ERROR is emitted and execution is stopped. If dl() fails because the specified library couldn't be loaded, in addition to FALSE an E_WARNING message is emitted.

Examples

Example #1 dl() examples

<?php
// Example loading an extension based on OS
if (!extension_loaded('sqlite')) {
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        dl('php_sqlite.dll');
    } else {
        dl('sqlite.so');
    }
}

// Or, the PHP_SHLIB_SUFFIX constant is available as of PHP 4.3.0
if (!extension_loaded('sqlite')) {
    $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
    dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?>

Changelog

Version | Description
5.3.0 | dl() is now disabled in some SAPI's due to stability issues. The only SAPI's that allow dl() are: CLI, CGI and Embed. Use the Extension Loading Directives instead.

Notes

Note: dl() is not supported when PHP is built with ZTS support. Use the Extension Loading Directives instead.

Note: dl() is case sensitive on Unix platforms.

Note: This function is disabled when PHP is running in safe mode.

See Also

  • Extension Loading Directives
  • extension_loaded() - Find out whether an extension is loaded

assert
extension_loaded
PHP Options/Info Functions


Plural version of dgettext

dgettext
gettext
Gettext Functions
PHP Manual

dngettext

(PHP 4 >= 4.2.0, PHP 5)

dngettext — Plural version of dgettext

Description

string dngettext ( string $domain , string $msgid1 , string $msgid2 , int $n )

The dngettext() function allows you to override the current domain for a single plural message lookup.

Parameters

domain

The domain

msgid1

msgid2

n

Return Values

A string on success.

See Also

  • ngettext() - Plural version of gettext

dgettext
gettext
Gettext Functions


Get Unix timestamp for midnight on Easter of a given year

cal_to_jd
easter_days
Calendar Functions
PHP Manual

easter_date

(PHP 4, PHP 5)

easter_date — Get Unix timestamp for midnight on Easter of a given year

Description

int easter_date ([ int $year ] )

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

Warning

This function will generate a warning if the year is outside of the range for Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)

Parameters

year

The year as a number between 1970 an 2037

Return Values

The easter date as a unix timestamp.

Changelog

Version | Description
Since 4.3.0 | The year parameter is optional and defaults to the current year according to the local time if omitted.

Examples

Example #1 easter_date() example

<?php

echo date("M-d-Y", easter_date(1999));        // Apr-04-1999
echo date("M-d-Y", easter_date(2000));        // Apr-23-2000
echo date("M-d-Y", easter_date(2001));        // Apr-15-2001

?>

See Also

  • easter_days() - Get number of days after March 21 on which Easter falls for a given year for calculating Easter before 1970 or after 2037

cal_to_jd
easter_days
Calendar Functions


Get number of days after March 21 on which Easter falls for a given year

easter_date
FrenchToJD
Calendar Functions
PHP Manual

easter_days

(PHP 4, PHP 5)

easter_days — Get number of days after March 21 on which Easter falls for a given year

Description

int easter_days ([ int $year [, int $method = CAL_EASTER_DEFAULT ]] )

Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)

Parameters

year

The year as a positive number

method

Allows to calculate easter dates based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

Return Values

The number of days after March 21st that the Easter Sunday is in the given year .

Changelog

Version | Description
Since 4.3.0 | The year parameter is optional and defaults to the current year according to the local time if omitted.
Since 4.3.0 | The method parameter was introduced.

Examples

Example #1 easter_days() example

<?php

echo easter_days(1999);        // 14, i.e. April 4
echo easter_days(1492);        // 32, i.e. April 22
echo easter_days(1913);        //  2, i.e. March 23

?>

See Also

  • easter_date() - Get Unix timestamp for midnight on Easter of a given year

easter_date
FrenchToJD
Calendar Functions


Enumerates the Enchant providers

Enchant Functions
enchant_broker_dict_exists
Enchant Functions
PHP Manual

enchant_broker_describe

(PECL enchant >= 0.1.0)

enchant_broker_describe — Enumerates the Enchant providers

Description

array enchant_broker_describe ( resource $broker )

Enumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo().

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 List the backends provided by the given broker

<?php
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);

?>

The above example will output something similar to:

Current broker provides the following backend(s):
Array
(
    [0] => Array
        (
            [name] => aspell
            [desc] => Aspell Provider
            [file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [1] => Array
        (
            [name] => hspell
            [desc] => Hspell Provider
            [file] => /usr/lib/enchant/libenchant_hspell.so
        )

    [2] => Array
        (
            [name] => ispell
            [desc] => Ispell Provider
            [file] => /usr/lib/enchant/libenchant_ispell.so
        )

    [3] => Array
        (
            [name] => myspell
            [desc] => Myspell Provider
            [file] => /usr/lib/enchant/libenchant_myspell.so
        )

)

Enchant Functions
enchant_broker_dict_exists
Enchant Functions


Whether a dictionary exists or not. Using non-empty tag

enchant_broker_describe
enchant_broker_free_dict
Enchant Functions
PHP Manual

enchant_broker_dict_exists

(PECL enchant >= 0.1.0 )

enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag

Description

bool enchant_broker_dict_exists ( resource $broker , string $tag )

Tells if a dictionary exists or not, using a non-empty tags

Parameters

broker

Broker resource

tag

non-empty tag in the LOCALE format, ex: us_US, ch_DE, etc.

Return Values

Returns TRUE when the tag exist or FALSE when not.

Examples

Example #1 A enchant_broker_dict_exists() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
    echo $tag . " dictionary found.\n";
}
?>

See Also

  • enchant_broker_describe() - Enumerates the Enchant providers

enchant_broker_describe
enchant_broker_free_dict
Enchant Functions


Free the broker resource and its dictionnaries

enchant_broker_free_dict
enchant_broker_get_error
Enchant Functions
PHP Manual

enchant_broker_free

(PECL enchant >= 0.1.0 )

enchant_broker_free — Free the broker resource and its dictionnaries

Description

bool enchant_broker_free ( resource $broker )

Free a broker resource with all its dictionaries.

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • enchant_broker_init() - create a new broker object capable of requesting

enchant_broker_free_dict
enchant_broker_get_error
Enchant Functions


Free a dictionary resource

enchant_broker_dict_exists
enchant_broker_free
Enchant Functions
PHP Manual

enchant_broker_free_dict

(PECL enchant >= 0.1.0 )

enchant_broker_free_dict — Free a dictionary resource

Description

bool enchant_broker_free_dict ( resource $dict )

Free a dictionary resource.

Parameters

dict

Dictionary resource.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • enchant_broker_request_dict() - create a new dictionary using a tag
  • enchant_broker_request_pwl_dict() - creates a dictionary using a PWL file

enchant_broker_dict_exists
enchant_broker_free
Enchant Functions


Returns the last error of the broker

enchant_broker_free
enchant_broker_init
Enchant Functions
PHP Manual

enchant_broker_get_error

(PECL enchant >= 0.1.0 )

enchant_broker_get_error — Returns the last error of the broker

Description

string enchant_broker_get_error ( resource $broker )

Returns the last error which occurred in this broker.

Parameters

broker

Broker resource.

Return Values

Return the msg string if an error was found or FALSE

enchant_broker_free
enchant_broker_init
Enchant Functions


create a new broker object capable of requesting

enchant_broker_get_error
enchant_broker_list_dicts
Enchant Functions
PHP Manual

enchant_broker_init

(PECL enchant >= 0.1.0 )

enchant_broker_init — create a new broker object capable of requesting

Description

resource enchant_broker_init ( void )

Parameters

Return Values

Returns a broker resource on success or FALSE.

See Also

  • enchant_broker_free() - Free the broker resource and its dictionnaries

enchant_broker_get_error
enchant_broker_list_dicts
Enchant Functions


Returns a list of available dictionaries

enchant_broker_init
enchant_broker_request_dict
Enchant Functions
PHP Manual

enchant_broker_list_dicts

(PECL enchant >= 1.0.1)

enchant_broker_list_dicts — Returns a list of available dictionaries

Description

mixed enchant_broker_list_dicts ( resource $broker )

Returns a list of available dictionaries with their details.

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 List all available dictionaries for one broker

<?php
$r = enchant_broker_init();
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [lang_tag] => de
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [1] => Array
        (
            [lang_tag] => de_DE
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [3] => Array
        (
            [lang_tag] => en
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [4] => Array
        (
            [lang_tag] => en_GB
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [5] => Array
        (
            [lang_tag] => en_US
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [6] => Array
        (
            [lang_tag] => hi_IN
            [provider_name] => myspell
            [provider_desc] => Myspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_myspell.so
        )

)

See Also

  • enchant_broker_describe() - Enumerates the Enchant providers

enchant_broker_init
enchant_broker_request_dict
Enchant Functions


create a new dictionary using a tag

enchant_broker_list_dicts
enchant_broker_request_pwl_dict
Enchant Functions
PHP Manual

enchant_broker_request_dict

(PECL enchant >= 0.1.0 )

enchant_broker_request_dict — create a new dictionary using a tag

Description

resource enchant_broker_request_dict ( resource $broker , string $tag )

create a new dictionary using tag, the non-empty language tag you wish to request a dictionary for ("en_US", "de_DE", ...)

Parameters

broker

Broker resource

tag

A tag describing the locale, for example en_US, de_DE

Return Values

Returns a dictionary resource on success or FALSE on failure.

Examples

Example #1 A enchant_broker_request_dict() example

Check if a dictionary exists using enchant_broker_dict_exists() and request it.

<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
    $dict = enchant_broker_request_dict($r, $tag);
}
?>

See Also

  • enchant_dict_describe() - Describes an individual dictionary
  • enchant_broker_dict_exists() - Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict() - Free a dictionary resource

enchant_broker_list_dicts
enchant_broker_request_pwl_dict
Enchant Functions


creates a dictionary using a PWL file

enchant_broker_request_dict
enchant_broker_set_ordering
Enchant Functions
PHP Manual

enchant_broker_request_pwl_dict

(PECL enchant >= 0.1.0 )

enchant_broker_request_pwl_dict — creates a dictionary using a PWL file

Description

resource enchant_broker_request_pwl_dict ( resource $broker , string $filename )

Creates a dictionary using a PWL file. A PWL file is personal word file one word per line.

Parameters

broker

Broker resource

filename

Path to the PWL file.

Return Values

Returns a dictionary resource on success or FALSE on failure.

See Also

  • enchant_dict_describe() - Describes an individual dictionary
  • enchant_broker_dict_exists() - Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict() - Free a dictionary resource

enchant_broker_request_dict
enchant_broker_set_ordering
Enchant Functions


Declares a preference of dictionaries to use for the language

enchant_broker_request_pwl_dict
enchant_dict_add_to_personal
Enchant Functions
PHP Manual

enchant_broker_set_ordering

(PECL enchant >= 0.1.0 )

enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language

Description

bool enchant_broker_set_ordering ( resource $broker , string $tag , string $ordering )

Declares a preference of dictionaries to use for the language described/referred to by 'tag'. The ordering is a comma delimited list of provider names. As a special exception, the "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.

Parameters

broker

Broker resource

tag

Language tag. The special "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.

ordering

Comma delimited list of provider names

Return Values

Returns TRUE on success or FALSE on failure.

enchant_broker_request_pwl_dict
enchant_dict_add_to_personal
Enchant Functions


add a word to personal word list

enchant_broker_set_ordering
enchant_dict_add_to_session
Enchant Functions
PHP Manual

enchant_dict_add_to_personal

(PECL enchant >= 0.1.0 )

enchant_dict_add_to_personal — add a word to personal word list

Description

void enchant_dict_add_to_personal ( resource $dict , string $word )

Add a word to personal word list of the given dictionary.

Parameters

dict

Dictionary resource

word

The word to add

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • enchant_broker_request_pwl_dict() - creates a dictionary using a PWL file
  • enchant_broker_request_dict() - create a new dictionary using a tag

enchant_broker_set_ordering
enchant_dict_add_to_session
Enchant Functions


add 'word' to this spell-checking session

enchant_dict_add_to_personal
enchant_dict_check
Enchant Functions
PHP Manual

enchant_dict_add_to_session

(PECL enchant >= 0.1.0 )

enchant_dict_add_to_session — add 'word' to this spell-checking session

Description

void enchant_dict_add_to_session ( resource $dict , string $word )

Add a word to the given dictionary. It will be added only for the active spell-checking session.

Parameters

dict

Dictionary resource

word

The word to add

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • enchant_broker_request_dict() - create a new dictionary using a tag

enchant_dict_add_to_personal
enchant_dict_check
Enchant Functions


Check whether a word is correctly spelled or not

enchant_dict_add_to_session
enchant_dict_describe
Enchant Functions
PHP Manual

enchant_dict_check

(PECL enchant >= 0.1.0 )

enchant_dict_check — Check whether a word is correctly spelled or not

Description

bool enchant_dict_check ( resource $dict , string $word )

If the word is correctly spelled return TRUE, otherwise return FALSE

Parameters

dict

Dictionary resource

word

The word to check

Return Values

Returns TRUE if the word is spelled correctly, FALSE if not.

enchant_dict_add_to_session
enchant_dict_describe
Enchant Functions


Describes an individual dictionary

enchant_dict_check
enchant_dict_get_error
Enchant Functions
PHP Manual

enchant_dict_describe

(PECL enchant >= 0.1.0 )

enchant_dict_describe — Describes an individual dictionary

Description

mixed enchant_dict_describe ( resource $dict )

Returns the details of the dictionary.

Parameters

dict

Dictinaray resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A enchant_dict_describe() example

Check if a dictionary exists using enchant_broker_dict_exists() and show the detail of it.

<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
    $dict = enchant_broker_request_dict($r, $tag);
    $dict_details = enchant_dict_describe($dict);
    print_r($dict_details);
}
?>

The above example will output something similar to:

Array
(
    [lang] => en_US
    [name] => aspell
    [desc] => Aspell Provider
    [file] => /usr/lib/enchant/libenchant_aspell.so
)

enchant_dict_check
enchant_dict_get_error
Enchant Functions


Returns the last error of the current spelling-session

enchant_dict_describe
enchant_dict_is_in_session
Enchant Functions
PHP Manual

enchant_dict_get_error

(PECL enchant >= 0.1.0 )

enchant_dict_get_error — Returns the last error of the current spelling-session

Description

string enchant_dict_get_error ( resource $dict )

Returns the last error of the current spelling-session

Parameters

dict

Dictinaray resource

Return Values

Returns the error message as string or FALSE if no error occurred.

enchant_dict_describe
enchant_dict_is_in_session
Enchant Functions


whether or not 'word' exists in this spelling-session

enchant_dict_get_error
enchant_dict_quick_check
Enchant Functions
PHP Manual

enchant_dict_is_in_session

(PECL enchant >= 0.1.0 )

enchant_dict_is_in_session — whether or not 'word' exists in this spelling-session

Description

bool enchant_dict_is_in_session ( resource $dict , string $word )

Tells whether or not a word already exists in the current session.

Parameters

dict

Dictionary resource

word

The word to lookup

Return Values

Returns TRUE if the word exists or FALSE

See Also

  • enchant_dict_add_to_session() - add 'word' to this spell-checking session

enchant_dict_get_error
enchant_dict_quick_check
Enchant Functions


Check the word is correctly spelled and provide suggestions

enchant_dict_is_in_session
enchant_dict_store_replacement
Enchant Functions
PHP Manual

enchant_dict_quick_check

(PECL enchant:0.2.0-1.0.1)

enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions

Description

bool enchant_dict_quick_check ( resource $dict , string $word [, array &$suggestions ] )

If the word is correctly spelled return TRUE, otherwise return FALSE, if suggestions variable is provided, fill it with spelling alternatives.

Parameters

dict

Dictionary resource

word

The word to check

suggestions

If the word is not correctly spelled, this variable will contain an array of suggestions.

Return Values

Returns TRUE if the word is correctly spelled or FALSE

Examples

Example #1 A enchant_dict_quick_check() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();

if (enchant_broker_dict_exists($r,$tag)) {
    $d = enchant_broker_request_dict($r, $tag);
    enchant_dict_quick_check($d, 'soong', $suggs);
    print_r($suggs);
}
?>

The above example will output something similar to:

Array
(
    [0] => song
    [1] => snog
    [2] => soon
    [3] => Sang
    [4] => Sung
    [5] => sang
    [6] => sung
    [7] => sponge
    [8] => spongy
    [9] => snag
    [10] => snug
    [11] => sonic
    [12] => sing
    [13] => songs
    [14] => Son
    [15] => Sonja
    [16] => Synge
    [17] => son
    [18] => Sejong
    [19] => sarong
    [20] => sooner
    [21] => Sony
    [22] => sown
    [23] => scone
    [24] => song's
)

See Also

  • enchant_dict_check() - Check whether a word is correctly spelled or not
  • enchant_dict_suggest() - Will return a list of values if any of those pre-conditions are not met

enchant_dict_is_in_session
enchant_dict_store_replacement
Enchant Functions


Add a correction for a word

enchant_dict_quick_check
enchant_dict_suggest
Enchant Functions
PHP Manual

enchant_dict_store_replacement

(PECL enchant >= 0.1.0 )

enchant_dict_store_replacement — Add a correction for a word

Description

void enchant_dict_store_replacement ( resource $dict , string $mis , string $cor )

Add a correction for 'mis' using 'cor'. Notes that you replaced @mis with @cor, so it's possibly more likely that future occurrences of @mis will be replaced with @cor. So it might bump @cor up in the suggestion list.

Parameters

dict

Dictionary resource

mis

The work to fix

cor

The correct word

Return Values

Returns TRUE on success or FALSE on failure.

enchant_dict_quick_check
enchant_dict_suggest
Enchant Functions


Will return a list of values if any of those pre-conditions are not met

enchant_dict_store_replacement
FriBiDi
Enchant Functions
PHP Manual

enchant_dict_suggest

(PECL enchant >= 0.1.0 )

enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met

Description

array enchant_dict_suggest ( resource $dict , string $word )

Parameters

dict

Dictionary resource

word

Word to use for the suggestions.

Return Values

Will returns an array of suggestions if the word is bad spelled.

Examples

Example #1 A enchant_dict_suggest() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
    $d = enchant_broker_request_dict($r, $tag);

    $wordcorrect = enchant_dict_check($d, "soong");
    if (!$wordcorrect) {
        $suggs = enchant_dict_suggest($d, "soong");
        echo "Suggestions for 'soong':";
        print_r($suggs);
    }
    enchant_broker_free_dict($d);
}
enchant_broker_free($r);
?>

See Also

  • enchant_dict_check() - Check whether a word is correctly spelled or not
  • enchant_dict_quick_check() - Check the word is correctly spelled and provide suggestions

enchant_dict_store_replacement
FriBiDi
Enchant Functions


Get the last occurred error

debug_print_backtrace
error_log
Error Handling Functions
PHP Manual

error_get_last

(PHP 5 >= 5.2.0)

error_get_last — Get the last occurred error

Description

array error_get_last ( void )

Gets information about the last error that occurred.

Return Values

Returns an associative array describing the last error with keys "type", "message", "file" and "line". Returns NULL if there hasn't been an error yet.

Examples

Example #1 An error_get_last() example

<?php
echo $a;
print_r(error_get_last());
?>

The above example will output something similar to:

Array
(
    [type] => 8
    [message] => Undefined variable: a
    [file] => C:\WWW\index.php
    [line] => 2
)

See Also

  • Error constants
  • Variable $php_errormsg
  • Directive display_errors
  • Directive html_errors
  • Directive xmlrpc_errors

debug_print_backtrace
error_log
Error Handling Functions


Send an error message somewhere

error_get_last
error_reporting
Error Handling Functions
PHP Manual

error_log

(PHP 4, PHP 5)

error_log — Send an error message somewhere

Description

bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] )

Sends an error message to the web server's error log, a TCP port or to a file.

Parameters

message

The error message that should be logged.

message_type

Says where the error should go. The possible message types are as follows:

error_log() log types
0 | message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.
1 | message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used.
2 | No longer an option.
3 | message is appended to the file destination . A newline is not automatically added to the end of the message string.
4 | message is sent directly to the SAPI logging handler.

destination

The destination. Its meaning depends on the message_type parameter as described above.

extra_headers

The extra headers. It's used when the message_type parameter is set to 1. This message type uses the same internal function as mail() does.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.2.7 | The possible value of 4 was added to message_type .

Examples

Example #1 error_log() examples

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
    error_log("Big trouble, we're all out of FOOs!", 1,
               "operator@example.com");
}

// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

error_get_last
error_reporting
Error Handling Functions


Sets which PHP errors are reported

error_log
restore_error_handler
Error Handling Functions
PHP Manual

error_reporting

(PHP 4, PHP 5)

error_reporting — Sets which PHP errors are reported

Description

int error_reporting ([ int $level ] )

The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script. If the optional level is not set, error_reporting() will just return the current error reporting level.

Parameters

level

The new error_reporting level. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected.

The available error level constants and the actual meanings of these error levels are described in the predefined constants.

Return Values

Returns the old error_reporting level or the current level if no level parameter is given.

Changelog

Version | Description
5.0.0 | E_STRICT introduced (not part of E_ALL).
5.2.0 | E_RECOVERABLE_ERROR introduced.
5.3.0 | E_DEPRECATED and E_USER_DEPRECATED introduced.
6.0.0 | E_STRICT became part of E_ALL.

Examples

Example #1 error_reporting() examples

<?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

?>

Notes

Warning

Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).

Tip

Passing in the value -1 will show every possible error, even when new levels and constants are added in future PHP versions. The E_ALL constant also behaves this way as of PHP 6.

See Also

  • The display_errors directive
  • The html_errors directive
  • The xmlrpc_errors directive
  • ini_set() - Sets the value of a configuration option

error_log
restore_error_handler
Error Handling Functions


Escape a string to be used as a shell argument

Program execution Functions
escapeshellcmd
Program execution Functions
PHP Manual

escapeshellarg

(PHP 4 >= 4.0.3, PHP 5)

escapeshellarg — Escape a string to be used as a shell argument

Description

string escapeshellarg ( string $arg )

escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. The shell functions include exec(), system() and the backtick operator.

Parameters

arg

The argument that will be escaped.

Return Values

The escaped string.

Examples

Example #1 escapeshellarg() example

<?php
system('ls '.escapeshellarg($dir));
?>

See Also

  • escapeshellcmd() - Escape shell metacharacters
  • exec() - Execute an external program
  • popen() - Opens process file pointer
  • system() - Execute an external program and display the output
  • backtick operator

Program execution Functions
escapeshellcmd
Program execution Functions


Escape shell metacharacters

escapeshellarg
exec
Program execution Functions
PHP Manual

escapeshellcmd

(PHP 4, PHP 5)

escapeshellcmd — Escape shell metacharacters

Description

string escapeshellcmd ( string $command )

escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator.

Following characters are preceded by a backslash: #&;`|*?~<>^()[]{}$\, \x0A and \xFF. ' and " are escaped only if they are not paired. In Windows, all these characters plus % are replaced by a space instead.

Parameters

command

The command that will be escaped.

Return Values

The escaped string.

Examples

Example #1 escapeshellcmd() example

<?php
$e = escapeshellcmd($userinput);

// here we don't care if $e has spaces
system("echo $e");
$f = escapeshellcmd($filename);

// and here we do, so we use quotes
system("touch \"/tmp/$f\"; ls -l \"/tmp/$f\"");
?>

See Also

  • escapeshellarg() - Escape a string to be used as a shell argument
  • exec() - Execute an external program
  • popen() - Opens process file pointer
  • system() - Execute an external program and display the output
  • backtick operator

escapeshellarg
exec
Program execution Functions


Evaluate a string as PHP code

die
exit
Misc. Functions
PHP Manual

eval

(PHP 4, PHP 5)

eval — Evaluate a string as PHP code

Description

mixed eval ( string $code_str )

Evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.

There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str . To mix HTML output and PHP code you can use a closing PHP tag to leave PHP mode.

Also remember that variables given values under eval() will retain these values in the main script afterwards.

Parameters

code_str

The code string to be evaluated. code_str does not have to contain PHP Opening tags.

A return statement will immediately terminate the evaluation of the string .

Return Values

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally. It is not possible to catch a parse error in eval() using set_error_handler().

Examples

Example #1 eval() example - simple text merge

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>

The above example will output:

This is a $string with my $name in it.
This is a cup with my coffee in it.

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions

Tip

As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).

Note: In case of a fatal error in the evaluated code, the whole script exits.

See Also

  • call_user_func() - Call a user function given by the first parameter

die
exit
Misc. Functions


Destroy event base

event_add
event_base_loop
Libevent Functions
PHP Manual

event_base_free

(PECL libevent >= 0.0.1)

event_base_free — Destroy event base

Description

void event_base_free ( resource $event_base )

Destroys the specified event_base and frees all the resources associated. Note that it's not possible to destroy an event base with events attached to it.

Parameters

event_base

Valid event base resource.

event_add
event_base_loop
Libevent Functions


Handle events

event_base_free
event_base_loopbreak
Libevent Functions
PHP Manual

event_base_loop

(PECL libevent >= 0.0.1)

event_base_loop — Handle events

Description

int event_base_loop ( resource $event_base [, int $flags = 0 ] )

Starts event loop for the specified event base.

Parameters

event_base

Valid event base resource.

flags

Optional parameter, which can take any combination of EVLOOP_ONCE and EVLOOP_NONBLOCK.

Return Values

event_base_loop() returns 0 on success, -1 on error and 1 if no events were registered.

event_base_free
event_base_loopbreak
Libevent Functions


Abort event loop

event_base_loop
event_base_loopexit
Libevent Functions
PHP Manual

event_base_loopbreak

(PECL libevent >= 0.0.1)

event_base_loopbreak — Abort event loop

Description

bool event_base_loopbreak ( resource $event_base )

Abort the active event loop immediately. The behaviour is similar to break statement.

Parameters

event_base

Valid event base resource.

Return Values

event_base_loopbreak() returns TRUE on success or FALSE on error.

event_base_loop
event_base_loopexit
Libevent Functions


Exit loop after a time

event_base_loopbreak
event_base_new
Libevent Functions
PHP Manual

event_base_loopexit

(PECL libevent >= 0.0.1)

event_base_loopexit — Exit loop after a time

Description

bool event_base_loopexit ( resource $event_base [, int $timeout = -1 ] )

The next event loop iteration after the given timer expires will complete normally, then exit without blocking for events again.

Parameters

event_base

Valid event base resource.

timeout

Optional timeout parameter (in microseconds).

Return Values

event_base_loopexit() returns TRUE on success or FALSE on error.

event_base_loopbreak
event_base_new
Libevent Functions


Create and initialize new event base

event_base_loopexit
event_base_priority_init
Libevent Functions
PHP Manual

event_base_new

(PECL libevent >= 0.0.1)

event_base_new — Create and initialize new event base

Description

resource event_base_new ( void )

Returns new event base, which can be used later in event_base_set(), event_base_loop() and other functions.

Parameters

This function has no parameters.

Return Values

event_base_new() returns valid event base resource on success or FALSE on error.

event_base_loopexit
event_base_priority_init
Libevent Functions


Set the number of event priority levels

event_base_new
event_base_set
Libevent Functions
PHP Manual

event_base_priority_init

(PECL libevent >= 0.0.2)

event_base_priority_init — Set the number of event priority levels

Description

bool event_base_priority_init ( resource $event_base , int $npriorities )

Sets the number of different event priority levels.

By default all events are scheduled with the same priority (npriorities /2). Using event_base_priority_init() you can change the number of event priority levels and then set a desired priority for each event.

Parameters

event_base

Valid event base resource.

npriorities

The number of event priority levels.

Return Values

event_base_priority_init() returns TRUE on success or FALSE on error.

event_base_new
event_base_set
Libevent Functions


Associate event base with an event

event_base_priority_init
event_buffer_base_set
Libevent Functions
PHP Manual

event_base_set

(PECL libevent >= 0.0.1)

event_base_set — Associate event base with an event

Description

bool event_base_set ( resource $event , resource $event_base )

Associates the event_base with the event .

Parameters

event

Valid event resource.

event_base

Valid event base resource.

Return Values

event_base_set() returns TRUE on success or FALSE on error.

event_base_priority_init
event_buffer_base_set
Libevent Functions


Associate buffered event with an event base

event_base_set
event_buffer_disable
Libevent Functions
PHP Manual

event_buffer_base_set

(PECL libevent >= 0.0.1)

event_buffer_base_set — Associate buffered event with an event base

Description

bool event_buffer_base_set ( resource $bevent , resource $event_base )

Assign the specified bevent to the event_base .

Parameters

bevent

Valid buffered event resource.

event_base

Valid event base resource.

Return Values

event_buffer_base_set() returns TRUE on success or FALSE on error.

event_base_set
event_buffer_disable
Libevent Functions


Disable a buffered event

event_buffer_base_set
event_buffer_enable
Libevent Functions
PHP Manual

event_buffer_disable

(PECL libevent >= 0.0.1)

event_buffer_disable — Disable a buffered event

Description

bool event_buffer_disable ( resource $bevent , int $events )

Disables the specified buffered event.

Parameters

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

Return Values

event_buffer_disable() returns TRUE on success or FALSE on error.

event_buffer_base_set
event_buffer_enable
Libevent Functions


Enable a buffered event

event_buffer_disable
event_buffer_fd_set
Libevent Functions
PHP Manual

event_buffer_enable

(PECL libevent >= 0.0.1)

event_buffer_enable — Enable a buffered event

Description

bool event_buffer_enable ( resource $bevent , int $events )

Enables the specified buffered event.

Parameters

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

Return Values

event_buffer_enable() returns TRUE on success or FALSE on error.

event_buffer_disable
event_buffer_fd_set
Libevent Functions


Change a buffered event file descriptor

event_buffer_enable
event_buffer_free
Libevent Functions
PHP Manual

event_buffer_fd_set

(PECL libevent >= 0.0.1)

event_buffer_fd_set — Change a buffered event file descriptor

Description

void event_buffer_fd_set ( resource $bevent , resource $fd )

Changes the file descriptor on which the buffered event operates.

Parameters

bevent

Valid buffered event resource.

fd

Valid PHP stream, must be castable to file descriptor.

event_buffer_enable
event_buffer_free
Libevent Functions


Destroy buffered event

event_buffer_fd_set
event_buffer_new
Libevent Functions
PHP Manual

event_buffer_free

(PECL libevent >= 0.0.1)

event_buffer_free — Destroy buffered event

Description

void event_buffer_free ( resource $bevent )

Destroys the specified buffered event and frees all the resources associated.

Parameters

bevent

Valid buffered event resource.

event_buffer_fd_set
event_buffer_new
Libevent Functions


Create new buffered event

event_buffer_free
event_buffer_priority_set
Libevent Functions
PHP Manual

event_buffer_new

(PECL libevent >= 0.0.1)

event_buffer_new — Create new buffered event

Description

resource event_buffer_new ( resource $stream , mixed $readcb , mixed $writecb , mixed $errorcb [, mixed $arg ] )

Libevent provides an abstraction layer on top of the regular event API. Using buffered event you don't need to deal with the I/O manually, instead it provides input and output buffers that get filled and drained automatically.

Parameters

stream

Valid PHP stream resource. Must be castable to file descriptor.

readcb

Callback to invoke where there is data to read, or NULL if no callback is desired.

writecb

Callback to invoke where the descriptor is ready for writing, or NULL if no callback is desired.

errorcb

Callback to invoke where there is an error on the descriptor, cannot be NULL.

arg

An argument that will be passed to each of the callbacks (optional).

Return Values

event_buffer_new() returns new buffered event resource on success or FALSE on error.

event_buffer_free
event_buffer_priority_set
Libevent Functions


Assign a priority to a buffered event

event_buffer_new
event_buffer_read
Libevent Functions
PHP Manual

event_buffer_priority_set

(PECL libevent >= 0.0.1)

event_buffer_priority_set — Assign a priority to a buffered event

Description

bool event_buffer_priority_set ( resource $bevent , int $priority )

Assign a priority to the bevent .

Parameters

bevent

Valid buffered event resource.

priority

Priority level. Cannot be less than zero and cannot exceed maximum priority level of the event base (see event_base_priority_init()).

Return Values

event_buffer_priority_set() returns TRUE on success or FALSE on error.

event_buffer_new
event_buffer_read
Libevent Functions


Read data from a buffered event

event_buffer_priority_set
event_buffer_timeout_set
Libevent Functions
PHP Manual

event_buffer_read

(PECL libevent >= 0.0.1)

event_buffer_read — Read data from a buffered event

Description

string event_buffer_read ( resource $bevent , int $data_size )

Reads data from the input buffer of the buffered event.

Parameters

bevent

Valid buffered event resource.

data_size

Data size in bytes.

event_buffer_priority_set
event_buffer_timeout_set
Libevent Functions


Set read and write timeouts for a buffered event

event_buffer_read
event_buffer_watermark_set
Libevent Functions
PHP Manual

event_buffer_timeout_set

(PECL libevent >= 0.0.1)

event_buffer_timeout_set — Set read and write timeouts for a buffered event

Description

void event_buffer_timeout_set ( resource $bevent , int $read_timeout , int $write_timeout )

Sets the read and write timeouts for the specified buffered event.

Parameters

bevent

Valid buffered event resource.

read_timeout

Read timeout (in seconds).

write_timeout

Write timeout (in seconds).

event_buffer_read
event_buffer_watermark_set
Libevent Functions


Set the watermarks for read and write events

event_buffer_timeout_set
event_buffer_write
Libevent Functions
PHP Manual

event_buffer_watermark_set

(PECL libevent >= 0.0.1)

event_buffer_watermark_set — Set the watermarks for read and write events

Description

void event_buffer_watermark_set ( resource $bevent , int $events , int $lowmark , int $highmark )

Sets the watermarks for read and write events. Libevent does not invoke read callback unless there is at least lowmark bytes in the input buffer; if the read buffer is beyond the highmark , reading is stopped. On output, the write callback is invoked whenever the buffered data falls below the lowmark .

Parameters

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

lowmark

Low watermark.

highmark

High watermark.

event_buffer_timeout_set
event_buffer_write
Libevent Functions


Write data to a buffered event

event_buffer_watermark_set
event_del
Libevent Functions
PHP Manual

event_buffer_write

(PECL libevent >= 0.0.1)

event_buffer_write — Write data to a buffered event

Description

bool event_buffer_write ( resource $bevent , string $data [, int $data_size = -1 ] )

Writes data to the specified buffered event. The data is appended to the output buffer and written to the descriptor when it becomes available for writing.

Parameters

bevent

Valid buffered event resource.

data

The data to be written.

data_size

Optional size parameter. event_buffer_write() writes all the data by default.

Return Values

event_buffer_write() returns TRUE on success or FALSE on error.

event_buffer_watermark_set
event_del
Libevent Functions


Remove an event from the set of monitored events

event_buffer_write
event_free
Libevent Functions
PHP Manual

event_del

(PECL libevent >= 0.0.1)

event_del — Remove an event from the set of monitored events

Description

bool event_del ( resource $event )

Cancels the event .

Parameters

event

Valid event resource.

Return Values

event_del() returns TRUE on success or FALSE on error.

event_buffer_write
event_free
Libevent Functions


Free event resource

event_del
event_new
Libevent Functions
PHP Manual

event_free

(PECL libevent >= 0.0.1)

event_free — Free event resource

Description

void event_free ( resource $event )

Frees previously created event resource.

Parameters

event

Valid event resource.

event_del
event_new
Libevent Functions


Create new event

event_free
event_set
Libevent Functions
PHP Manual

event_new

(PECL libevent >= 0.0.1)

event_new — Create new event

Description

resource event_new ( void )

Creates and returns a new event resource.

Return Values

event_new() returns a new event resource on success or FALSE on error.

event_free
event_set
Libevent Functions


Prepare an event

event_new
PCNTL
Libevent Functions
PHP Manual

event_set

(PECL libevent >= 0.0.1)

event_set — Prepare an event

Description

bool event_set ( resource $event , resource $fd , int $events , mixed $callback [, mixed $arg ] )

Prepares the event to be used in event_add(). The event is prepared to call the function specified by the callback on the events specified in parameter events , which is a set of the following flags: EV_TIMEOUT, EV_SIGNAL, EV_READ and EV_WRITE.

After initializing the event, use event_base_set() to associate the event with its event base.

In case of matching event, these three arguments are passed to the callback function:

fd

Resource indicating the stream.

events

A flag indicating the event. Can be one of the following: EV_TIMEOUT, EV_SIGNAL, EV_READ or EV_WRITE.

arg

Optional parameter, previously passed to event_set() as arg .

Parameters

event

Valid event resource.

fd

Valid PHP stream resource. The stream must be castable to file descriptor, so you most likely won't be able to use any of filtered streams.

events

A set of flags indicating the desired event, can be EV_READ and/or EV_WRITE. The additional flag EV_PERSIST makes the event to persist until event_del() is called, otherwise the callback is invoked only once.

callback

Callback function to be called when the matching event occurs.

arg

Optional callback parameter.

Return Values

event_set() returns TRUE on success or FALSE on error.

event_new
PCNTL
Libevent Functions


Add an event to the set of monitored events

Libevent Functions
event_base_free
Libevent Functions
PHP Manual

event_add

(PECL libevent >= 0.0.1)

event_add — Add an event to the set of monitored events

Description

bool event_add ( resource $event [, int $timeout = -1 ] )

event_add() schedules the execution of the event when the event specified in event_set() occurs or in at least the time specified by the timeout argument. If timeout was not specified, not timeout is set. The event must be already initalized by event_set() and event_base_set() functions. If the event already has a timeout set, it is replaced by the new one.

Parameters

event

Valid event resource.

timeout

Optional timeout (in microseconds).

Return Values

event_add() returns TRUE on success or FALSE on error.

Libevent Functions
event_base_free
Libevent Functions


Execute an external program

escapeshellcmd
passthru
Program execution Functions
PHP Manual

exec

(PHP 4, PHP 5)

exec — Execute an external program

Description

string exec ( string $command [, array &$output [, int &$return_var ]] )

exec() executes the given command .

Parameters

command

The command that will be executed.

output

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

return_var

If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.

Return Values

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

To get the output of the executed command, be sure to set and use the output parameter.

Examples

Example #1 An exec() example

<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo exec('whoami');
?>

Notes

Warning

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note: If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.

Warning

With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x.

See Also

  • system() - Execute an external program and display the output
  • passthru() - Execute an external program and display raw output
  • escapeshellcmd() - Escape shell metacharacters
  • pcntl_exec() - Executes specified program in current process space
  • backtick operator

escapeshellcmd
passthru
Program execution Functions


Determine the type of an image

Exif Functions
exif_read_data
Exif Functions
PHP Manual

exif_imagetype

(PHP 4 >= 4.3.0, PHP 5)

exif_imagetype — Determine the type of an image

Description

int exif_imagetype ( string $filename )

exif_imagetype() reads the first bytes of an image and checks its signature.

exif_imagetype() can be used to avoid calls to other exif functions with unsupported file types or in conjunction with $_SERVER['HTTP_ACCEPT'] to check whether or not the viewer is able to see a specific image in the browser.

Parameters

filename
The image being checked.

Return Values

When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.

Changelog

Version | Description
4.3.2 | Support for JPC, JP2, JPX, JB2, XBM, and WBMP
4.3.0 | Support for SWC

Predefined Constants

The following constants are defined, and represent possible exif_imagetype() return values:

Imagetype Constants
Value | Constant
1 | IMAGETYPE_GIF
2 | IMAGETYPE_JPEG
3 | IMAGETYPE_PNG
4 | IMAGETYPE_SWF
5 | IMAGETYPE_PSD
6 | IMAGETYPE_BMP
7 | IMAGETYPE_TIFF_II (intel byte order)
8 | IMAGETYPE_TIFF_MM (motorola byte order)
9 | IMAGETYPE_JPC
10 | IMAGETYPE_JP2
11 | IMAGETYPE_JPX
12 | IMAGETYPE_JB2
13 | IMAGETYPE_SWC
14 | IMAGETYPE_IFF
15 | IMAGETYPE_WBMP
16 | IMAGETYPE_XBM

Examples

Example #1 exif_imagetype() example

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
    echo 'The picture is not a gif';
}
?>

See Also

  • getimagesize() - Get the size of an image

Exif Functions
exif_read_data
Exif Functions


Reads the EXIF headers from JPEG or TIFF

exif_imagetype
exif_tagname
Exif Functions
PHP Manual

exif_read_data

(PHP 4 >= 4.2.0, PHP 5)

exif_read_data — Reads the EXIF headers from JPEG or TIFF

Description

array exif_read_data ( string $filename [, string $sections = NULL [, bool $arrays = false [, bool $thumbnail = false ]]] )

exif_read_data() reads the EXIF headers from a JPEG or TIFF image file. This way you can read meta data generated by digital cameras.

EXIF headers tend to be present in JPEG/TIFF images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present.

Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, html is a height/width text string to be used inside normal HTML.

When an Exif header contains a Copyright note, this itself can contain two values. As the solution is inconsistent in the Exif 2.10 standard, the COMPUTED section will return both entries Copyright.Photographer and Copyright.Editor while the IFD0 sections contains the byte array with the NULL character that splits both entries. Or just the first entry if the datatype was wrong (normal behaviour of Exif). The COMPUTED will also contain the entry Copyright which is either the original copyright string, or a comma separated list of the photo and editor copyright.

The tag UserComment has the same problem as the Copyright tag. It can store two values. First the encoding used, and second the value itself. If so the IFD section only contains the encoding or a byte array. The COMPUTED section will store both in the entries UserCommentEncoding and UserComment. The entry UserComment is available in both cases so it should be used in preference to the value in IFD0 section.

exif_read_data() also validates EXIF data tags according to the EXIF specification (» http://exif.org/Exif2-2.PDF, page 20).

Note: Windows ME/XP can both wipe the Exif headers when connecting to a camera. More information available at » http://www.canon.co.jp/Imaging/NOTICE/011214-e.html.

Parameters

filename

The name of the image file being read. This cannot be an URL.

sections

Is a comma separated list of sections that need to be present in file to produce a result array. If none of the requested sections could be found the return value is FALSE.

FILE | FileName, FileSize, FileDateTime, SectionsFound
COMPUTED | html, Width, Height, IsColor, and more if available. Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, html is a height/width text string to be used inside normal HTML.
ANY_TAG | Any information that has a Tag e.g. IFD0, EXIF, ...
IFD0 | All tagged data of IFD0. In normal imagefiles this contains image size and so forth.
THUMBNAIL | A file is supposed to contain a thumbnail if it has a second IFD. All tagged information about the embedded thumbnail is stored in this section.
COMMENT | Comment headers of JPEG images.
EXIF | The EXIF section is a sub section of IFD0. It contains more detailed information about an image. Most of these entries are digital camera related.

arrays

Specifies whether or not each section becomes an array. The sections COMPUTED, THUMBNAIL, and COMMENT always become arrays as they may contain values whose names conflict with other sections.

thumbnail

When set to TRUE the thumbnail itself is read. Otherwise, only the tagged data is read.

Return Values

It returns an associative array where the array indexes are the header names and the array values are the values associated with those headers. If no data can be returned, exif_read_data() will return FALSE.

Changelog

Version | Description
4.3.0 | Can read all embedded IFD data including arrays (returned as such). Also the size of an embedded thumbnail is returned in a THUMBNAIL subarray, and can return thumbnails in TIFF format. Also, there is no longer a maximum length for returned values (not until the memory limit has been reached)
4.3.0 | If PHP has mbstring support, the user comment can automatically change encoding. Also, if the user comment uses Unicode or JIS encoding this encoding will automatically be changed according to the exif ini settings in php.ini
4.3.0 | If the image contains any IFD0 data then COMPUTED contains the entry ByteOrderMotorola which is 0 for little-endian (intel) and 1 for big-endian (motorola) byte order. Also, COMPUTED and UserComment no longer only contain the first copyright entry if the datatype was wrong.

Examples

Example #1 exif_read_data() example

<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";

$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {
    foreach ($section as $name => $val) {
        echo "$key.$name: $val<br />\n";
    }
}
?>

The first call fails because the image has no header information.

The above example will output something similar to:

test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

See Also

  • exif_thumbnail() - Retrieve the embedded thumbnail of a TIFF or JPEG image
  • getimagesize() - Get the size of an image

exif_imagetype
exif_tagname
Exif Functions


Get the header name for an index

exif_read_data
exif_thumbnail
Exif Functions
PHP Manual

exif_tagname

(PHP 4 >= 4.2.0, PHP 5)

exif_tagname — Get the header name for an index

Description

string exif_tagname ( int $index )
Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The image index

Return Values

Returns the header name, or FALSE if index is undefined.

See Also

  • exif_imagetype() - Determine the type of an image

exif_read_data
exif_thumbnail
Exif Functions


Retrieve the embedded thumbnail of a TIFF or JPEG image

exif_tagname
read_exif_data
Exif Functions
PHP Manual

exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5)

exif_thumbnail — Retrieve the embedded thumbnail of a TIFF or JPEG image

Description

string exif_thumbnail ( string $filename [, int &$width [, int &$height [, int &$imagetype ]]] )

exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image.

If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function.

It is possible that exif_thumbnail() cannot create an image but can determine its size. In this case, the return value is FALSE but width and height are set.

Parameters

filename

The name of the image file being read. This image contains an embedded thumbnail.

width

The return width of the returned thumbnail.

height

The returned height of the returned thumbnail.

imagetype

The returned image type of the returned thumbnail. This is either TIFF or JPEG.

Return Values

Returns the embedded thumbnail, or FALSE if the image contains no thumbnail.

Changelog

Version | Description
4.3.0 | The optional parameters width , height , and imagetype all became available.
4.3.0 | May return thumbnails in the TIFF format.

Examples

Example #1 exif_thumbnail() example

<?php
if (array_key_exists('file', $_REQUEST)) {
    $image = exif_thumbnail($_REQUEST['file'], $width, $height, $type);
} else {
    $image = false;
}
if ($image!==false) {
    header('Content-type: ' .image_type_to_mime_type($type));
    echo $image;
    exit;
} else {
    // no thumbnail available, handle the error here
    echo 'No thumbnail available';
}
?>

See Also

  • exif_read_data() - Reads the EXIF headers from JPEG or TIFF
  • image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

exif_tagname
read_exif_data
Exif Functions


Output a message and terminate the current script

eval
get_browser
Misc. Functions
PHP Manual

exit

(PHP 4, PHP 5)

exit — Output a message and terminate the current script

Description

void exit ([ string $status ] )
void exit ( int $status )

Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit() is called.

Parameters

status

If status is a string, this function prints the status just before exiting.

If status is an integer, that value will also be used as the exit status. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.

Note: PHP >= 4.2.0 does NOT print the status if it is an integer.

Return Values

No value is returned.

Examples

Example #1 exit() example

<?php

$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
    or exit("unable to open file ($filename)");

?>

Example #2 exit() status example

<?php

//exit program normally
exit;
exit();
exit(0);

//exit with an error code
exit(1);
exit(0376); //octal

?>

Example #3 Shutdown functions and destructors run regardless

<?php
class Foo
{
    public function __destruct()
    {
        echo 'Destruct: ' . __METHOD__ . '()' . PHP_EOL;
    }
}

function shutdown()
{
    echo 'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL;
}

$foo = new Foo();
register_shutdown_function('shutdown');

exit();
echo 'This will not be output.';
?>

The above example will output:

 Shutdown: shutdown()
 Destruct: Foo::__destruct()

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions

Note: This language construct is equivalent to die().

See Also

  • register_shutdown_function() - Register a function for execution on shutdown

eval
get_browser
Misc. Functions


Calculates the exponent of e

deg2rad
expm1
Math Functions
PHP Manual

exp

(PHP 4, PHP 5)

exp — Calculates the exponent of e

Description

float exp ( float $arg )

Returns e raised to the power of arg .

Note: 'e' is the base of the natural system of logarithms, or approximately 2.718282.

Parameters

arg

The argument to process

Return Values

'e' raised to the power of arg

Examples

Example #1 exp() example

<?php
echo exp(12) . "\n";
echo exp(5.7);
?>

The above example will output:

1.6275E+005
298.87

See Also

  • log() - Natural logarithm
  • pow() - Exponential expression

deg2rad
expm1
Math Functions


Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

Expect Functions
expect_popen
Expect Functions
PHP Manual

expect_expectl

(PECL expect >= 0.1.0)

expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

Description

int expect_expectl ( resource $expect , array $cases [, array &$match ] )

Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen.

If match is provided, then it is filled with the result of search. The matched string can be found in match[0] . The match substrings (according to the parentheses) in the original pattern can be found in match[1] , match[2] , and so on, up to match[9] (the limitation of libexpect).

Parameters

expect

An Expect stream, previously opened with expect_popen().

cases

An array of expect cases. Each expect case is an indexed array, as described in the following table:

Expect Case Array
Index Key | Value Type | Description | Is Mandatory | Default Value
0 | string | pattern, that will be matched against the output from the stream | yes
1 | mixed | value, that will be returned by this function, if the pattern matches | yes
2 | integer | pattern type, one of: EXP_GLOB, EXP_EXACT or EXP_REGEXP | no | EXP_GLOB

Return Values

Returns value associated with the pattern that was matched.

On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER

Changelog

Version | Description
0.2.1 | Prior to version 0.2.1, in match parameter a match string was returned, not an array of match substrings.

Examples

Example #1 expect_expectl() example

<?php
// Copies file from remote host:
ini_set ("expect.timeout", 30);

$stream = fopen ("expect://scp user@remotehost:/var/log/messages /home/user/messages.txt", "r");

$cases = array (
  array (0 => "password:", 1 => PASSWORD),
  array (0 => "yes/no)?", 1 => YESNO)
);

while (true) {
 switch (expect_expectl ($stream, $cases))
 {
  case PASSWORD:
   fwrite ($stream, "password\n");
   break;

  case YESNO:
   fwrite ($stream, "yes\n");
   break;

  case EXP_TIMEOUT:
  case EXP_EOF:
   break 2;

  default:
   die ("Error has occurred!\n");
 }
}

fclose ($stream);
?>

See Also

  • expect_popen() - Execute command via Bourne shell, and open the PTY stream to the process

Expect Functions
expect_popen
Expect Functions


Execute command via Bourne shell, and open the PTY stream to the process

expect_expectl
Libevent
Expect Functions
PHP Manual

expect_popen

(PECL expect >= 0.1.0)

expect_popen — Execute command via Bourne shell, and open the PTY stream to the process

Description

resource expect_popen ( string $command )

Execute command via Bourne shell, and open the PTY stream to the process.

Parameters

command

Command to execute.

Return Values

Returns an open PTY stream to the processes stdio, stdout, and stderr.

On failure this function returns FALSE.

Examples

Example #1 expect_popen() example

<?php
// Login to the PHP.net CVS repository:
$stream = expect_popen ("cvs -d :pserver:anonymous@cvs.php.net:/repository login");
sleep (3);
fwrite ($stream, "phpfi\n");
fclose ($stream);
?>

See Also

  • popen() - Opens process file pointer

expect_expectl
Libevent
Expect Functions


Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

exp
floor
Math Functions
PHP Manual

expm1

(PHP 4 >= 4.1.0, PHP 5)

expm1 — Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

Description

float expm1 ( float $arg )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

expm1() returns the equivalent to 'exp(arg ) - 1' computed in a way that is accurate even if the value of arg is near zero, a case where 'exp (arg ) - 1' would be inaccurate due to subtraction of two numbers that are nearly equal.

Parameters

arg

The argument to process

Return Values

'e' to the power of arg minus one

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • log1p() - Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
  • exp() - Calculates the exponent of e

exp
floor
Math Functions


Find out whether an extension is loaded

dl
gc_collect_cycles
PHP Options/Info Functions
PHP Manual

extension_loaded

(PHP 4, PHP 5)

extension_loaded — Find out whether an extension is loaded

Description

bool extension_loaded ( string $name )

Finds out whether the extension is loaded.

Parameters

name

The extension name.

You can see the names of various extensions by using phpinfo() or if you're using the CGI or CLI version of PHP you can use the -m switch to list all available extensions:

$ php -m
[PHP Modules]
xml
tokenizer
standard
sockets
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

Return Values

Returns TRUE if the extension identified by name is loaded, FALSE otherwise.

Examples

Example #1 extension_loaded() example

<?php
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit;
    }
}
?>

Changelog

Version | Description
5.0.0 | extension_loaded() uses the internal extension name to test whether a certain extension is available or not. Most internal extension names are written in lower case but there may be extensions available which also use uppercase letters. Prior to PHP 5, this function compared the names case sensitively.

See Also

  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • get_extension_funcs() - Returns an array with the names of the functions of a module
  • phpinfo() - Outputs lots of PHP information
  • dl() - Loads a PHP extension at runtime

dl
gc_collect_cycles
PHP Options/Info Functions


Calculate the hash value needed by EZMLM

Mail Functions
mail
Mail Functions
PHP Manual

ezmlm_hash

(PHP 4 >= 4.0.2, PHP 5)

ezmlm_hash — Calculate the hash value needed by EZMLM

Description

int ezmlm_hash ( string $addr )

ezmlm_hash() calculates the hash value needed when keeping EZMLM mailing lists in a MySQL database.

Parameters

addr

The email address that's being hashed.

Return Values

The hash value of addr .

Examples

Example #1 Calculating the hash and subscribing a user

<?php

$user = "joecool@example.com";
$hash = ezmlm_hash($user);
$query = sprintf("INSERT INTO sample VALUES (%s, '%s')", $hash, $user);
$db->query($query); // using PHPLIB db interface

?>

Mail Functions
mail
Mail Functions


Get number of affected rows in previous FrontBase operation

FrontBase Functions
fbsql_autocommit
FrontBase Functions
PHP Manual

fbsql_affected_rows

(PHP 4 >= 4.0.6, PHP 5)

fbsql_affected_rows — Get number of affected rows in previous FrontBase operation

Description

int fbsql_affected_rows ([ resource $link_identifier ] )

fbsql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query associated with link_identifier .

Note: If you are using transactions, you need to call fbsql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the commit.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero.

Note: When using UPDATE, FrontBase will not update columns where the new value is the same as the old value. This creates the possibility that fbsql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

If the last query failed, this function will return -1.

See Also

  • fbsql_num_rows() - Get number of rows in result

FrontBase Functions
fbsql_autocommit
FrontBase Functions


Enable or disable autocommit

fbsql_affected_rows
fbsql_blob_size
FrontBase Functions
PHP Manual

fbsql_autocommit

(PHP 4 >= 4.0.6, PHP 5)

fbsql_autocommit — Enable or disable autocommit

Description

bool fbsql_autocommit ( resource $link_identifier [, bool $OnOff ] )

Returns the current autocommit status.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

OnOff

If this optional parameter is given the auto commit status will be changed.

With OnOff set to TRUE each statement will be committed automatically, if no errors was found.

With OnOff set to FALSE the user must commit or rollback the transaction using either fbsql_commit() or fbsql_rollback().

Return Values

Returns the current autocommit status, as a boolean.

See Also

  • fbsql_commit() - Commits a transaction to the database
  • fbsql_rollback() - Rollback a transaction to the database

fbsql_affected_rows
fbsql_blob_size
FrontBase Functions


Get the size of a BLOB

fbsql_autocommit
fbsql_change_user
FrontBase Functions
PHP Manual

fbsql_blob_size

(PHP 4 >= 4.2.0, PHP 5)

fbsql_blob_size — Get the size of a BLOB

Description

int fbsql_blob_size ( string $blob_handle [, resource $link_identifier ] )

Returns the size of the given BLOB.

Parameters

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the BLOB size as an integer, or FALSE on error.

See Also

  • fbsql_clob_size() - Get the size of a CLOB

fbsql_autocommit
fbsql_change_user
FrontBase Functions


Change logged in user of the active connection

fbsql_blob_size
fbsql_clob_size
FrontBase Functions
PHP Manual

fbsql_change_user

(PHP 4 >= 4.0.6, PHP 5)

fbsql_change_user — Change logged in user of the active connection

Description

bool fbsql_change_user ( string $user , string $password [, string $database [, resource $link_identifier ]] )

fbsql_change_user() changes the logged in user of the specified connection. If the new user and password authorization fails, the current connected user stays active.

Parameters

user

The new user name.

password

The new user password.

database

If specified, this will be the default or current database after the user has been changed.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_blob_size
fbsql_clob_size
FrontBase Functions


Get the size of a CLOB

fbsql_change_user
fbsql_close
FrontBase Functions
PHP Manual

fbsql_clob_size

(PHP 4 >= 4.2.0, PHP 5)

fbsql_clob_size — Get the size of a CLOB

Description

int fbsql_clob_size ( string $clob_handle [, resource $link_identifier ] )

Returns the size of the given CLOB.

Parameters

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the CLOB size as an integer, or FALSE on error.

See Also

  • fbsql_blob_size() - Get the size of a BLOB

fbsql_change_user
fbsql_close
FrontBase Functions


Close FrontBase connection

fbsql_clob_size
fbsql_commit
FrontBase Functions
PHP Manual

fbsql_close

(PHP 4 >= 4.0.6, PHP 5)

fbsql_close — Close FrontBase connection

Description

bool fbsql_close ([ resource $link_identifier ] )

Closes the connection to the FrontBase server that's associated with the specified link identifier.

Using fbsql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 fbsql_close() example

<?php
$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);
?>

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server

fbsql_clob_size
fbsql_commit
FrontBase Functions


Commits a transaction to the database

fbsql_close
fbsql_connect
FrontBase Functions
PHP Manual

fbsql_commit

(PHP 4 >= 4.0.6, PHP 5)

fbsql_commit — Commits a transaction to the database

Description

bool fbsql_commit ([ resource $link_identifier ] )

Ends the current transaction by writing all inserts, updates and deletes to the disk and unlocking all row and table locks held by the transaction. This command is only needed if autocommit is set to false.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_autocommit() - Enable or disable autocommit
  • fbsql_rollback() - Rollback a transaction to the database

fbsql_close
fbsql_connect
FrontBase Functions


Open a connection to a FrontBase Server

fbsql_commit
fbsql_create_blob
FrontBase Functions
PHP Manual

fbsql_connect

(PHP 4 >= 4.0.6, PHP 5)

fbsql_connect — Open a connection to a FrontBase Server

Description

 resource fbsql_connect
  ([ string $hostname = ini_get("fbsql.default_host")
 [, string $username = ini_get("fbsql.default_user")
 [, string $password = ini_get("fbsql.default_password")
]]] )

fbsql_connect() establishes a connection to a FrontBase server.

If a second call is made to fbsql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling fbsql_close().

Parameters

hostname

The server host name.

username

The user name for the connection.

password

The password for the connection.

Return Values

Returns a positive FrontBase link identifier on success, or FALSE on errors.

Examples

Example #1 fbsql_connect() example

<?php

$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);

?>

See Also

  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_close() - Close FrontBase connection

fbsql_commit
fbsql_create_blob
FrontBase Functions


Create a BLOB

fbsql_connect
fbsql_create_clob
FrontBase Functions
PHP Manual

fbsql_create_blob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_create_blob — Create a BLOB

Description

string fbsql_create_blob ( string $blob_data [, resource $link_identifier ] )

Creates a BLOB from the given data.

Parameters

blob_data

The BLOB data.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a resource handle to the newly created BLOB, which can be used with insert and update commands to store the BLOB in the database.

Examples

Example #1 fbsql_create_blob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$filename = "blobfile.bin";
$fp = fopen($filename, "rb");
$blobdata = fread($fp, filesize($filename));
fclose($fp);

$blobHandle = fbsql_create_blob($blobdata, $link);

$sql = "INSERT INTO BLOB_TABLE (BLOB_COLUMN) VALUES ($blobHandle);";
$rs = fbsql_query($sql, $link);
?>

See Also

  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

fbsql_connect
fbsql_create_clob
FrontBase Functions


Create a CLOB

fbsql_create_blob
fbsql_create_db
FrontBase Functions
PHP Manual

fbsql_create_clob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_create_clob — Create a CLOB

Description

string fbsql_create_clob ( string $clob_data [, resource $link_identifier ] )

Creates a CLOB from the given data.

Parameters

clob_data

The CLOB data.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a resource handle to the newly created CLOB, which can be used with insert and update commands to store the CLOB in the database.

Examples

Example #1 fbsql_create_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$filename = "clob_file.txt";
$fp = fopen($filename, "rb");
$clobdata = fread($fp, filesize($filename));
fclose($fp);

$clobHandle = fbsql_create_clob($clobdata, $link);

$sql = "INSERT INTO CLOB_TABLE (CLOB_COLUMN) VALUES ($clobHandle);";
$rs = fbsql_query($sql, $link);
?>

See Also

  • fbsql_create_blob() - Create a BLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

fbsql_create_blob
fbsql_create_db
FrontBase Functions


Create a FrontBase database

fbsql_create_clob
fbsql_data_seek
FrontBase Functions
PHP Manual

fbsql_create_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_create_db — Create a FrontBase database

Description

bool fbsql_create_db ( string $database_name [, resource $link_identifier [, string $database_options ]] )

Attempts to create a new database on the specified server.

Parameters

database_name

The database name, as a string.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

database_options

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 fbsql_create_db() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
if (fbsql_create_db("my_db")) {
    echo "Database created successfully\n";
} else {
    printf("Error creating database: %s\n", fbsql_error());
}
?>

See Also

  • fbsql_drop_db() - Drop (delete) a FrontBase database

fbsql_create_clob
fbsql_data_seek
FrontBase Functions


Move internal result pointer

fbsql_create_db
fbsql_database_password
FrontBase Functions
PHP Manual

fbsql_data_seek

(PHP 4 >= 4.0.6, PHP 5)

fbsql_data_seek — Move internal result pointer

Description

bool fbsql_data_seek ( resource $result , int $row_number )

Moves the internal row pointer of the FrontBase result associated with the specified result identifier to point to the specified row number.

The next call to fbsql_fetch_row() would return that row.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

row_number

The row number. Starts at 0.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 fbsql_data_seek() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");

fbsql_select_db("samp_db")
    or die("Could not select database");

$query = "SELECT last_name, first_name FROM friends;";
$result = fbsql_query($query)
    or die("Query failed");

// fetch rows in reverse order

for ($i = fbsql_num_rows($result) - 1; $i >=0; $i--) {
    if (!fbsql_data_seek($result, $i)) {
        printf("Cannot seek to row %d\n", $i);
        continue;
    }

    if (!($row = fbsql_fetch_object($result)))
        continue;

    echo $row->last_name . $row->first_name . "<br />\n";
}

fbsql_free_result($result);
?>

fbsql_create_db
fbsql_database_password
FrontBase Functions


Get or set the database name used with a connection

fbsql_database_password
fbsql_db_query
FrontBase Functions
PHP Manual

fbsql_database

(PHP 4 >= 4.0.6, PHP 5)

fbsql_database — Get or set the database name used with a connection

Description

string fbsql_database ( resource $link_identifier [, string $database ] )

Get or set the database name used with the connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

database

The database name. If given, the default database of the connexion will be changed to database .

Return Values

Returns the name of the database used with this connection.

fbsql_database_password
fbsql_db_query
FrontBase Functions


Sets or retrieves the password for a FrontBase database

fbsql_data_seek
fbsql_database
FrontBase Functions
PHP Manual

fbsql_database_password

(PHP 4 >= 4.0.6, PHP 5)

fbsql_database_password — Sets or retrieves the password for a FrontBase database

Description

string fbsql_database_password ( resource $link_identifier [, string $database_password ] )

Sets and retrieves the database password used by the connection. If a database is protected by a database password, the user must call this function before calling fbsql_select_db().

If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

This function does not change the database password in the database nor can it be used to retrieve the database password for a database.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

database_password

The database password, as a string. If given, the function sets the database password for the specified link identifier.

Return Values

Returns the database password associated with the link identifier.

Examples

Example #1 fbsql_create_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
fbsql_database_password($link, "secret db password");
fbsql_select_db($database, $link);
?>

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_select_db() - Select a FrontBase database

fbsql_data_seek
fbsql_database
FrontBase Functions


Send a FrontBase query

fbsql_database
fbsql_db_status
FrontBase Functions
PHP Manual

fbsql_db_query

(PHP 4 >= 4.0.6, PHP 5)

fbsql_db_query — Send a FrontBase query

Description

resource fbsql_db_query ( string $database , string $query [, resource $link_identifier ] )

Selects a database and executes a query on it.

Parameters

database

The database to be selected.

query

The SQL query to be executed.

Note: The query string shall always end with a semicolon.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a positive FrontBase result identifier to the query result, or FALSE on error.

See Also

  • fbsql_query() - Send a FrontBase query
  • fbsql_connect() - Open a connection to a FrontBase Server

fbsql_database
fbsql_db_status
FrontBase Functions


Get the status for a given database

fbsql_db_query
fbsql_drop_db
FrontBase Functions
PHP Manual

fbsql_db_status

(PHP 4 >= 4.0.7, PHP 5)

fbsql_db_status — Get the status for a given database

Description

int fbsql_db_status ( string $database_name [, resource $link_identifier ] )

Gets the current status of the specified database.

Parameters

database_name

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns an integer value with the current status. This can be one of the following constants:

  • FALSE - The exec handler for the host was invalid. This error will occur when the link_identifier connects directly to a database by using a port number. FBExec can be available on the server but no connection has been made for it.
  • FBSQL_UNKNOWN - The Status is unknown.
  • FBSQL_STOPPED - The database is not running. Use fbsql_start_db() to start the database.
  • FBSQL_STARTING - The database is starting.
  • FBSQL_RUNNING - The database is running and can be used to perform SQL operations.
  • FBSQL_STOPPING - The database is stopping.
  • FBSQL_NOEXEC - FBExec is not running on the server and it is not possible to get the status of the database.

See Also

  • fbsql_start_db() - Start a database on local or remote server
  • fbsql_stop_db() - Stop a database on local or remote server

fbsql_db_query
fbsql_drop_db
FrontBase Functions


Drop (delete) a FrontBase database

fbsql_db_status
fbsql_errno
FrontBase Functions
PHP Manual

fbsql_drop_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_drop_db — Drop (delete) a FrontBase database

Description

bool fbsql_drop_db ( string $database_name [, resource $link_identifier ] )

fbsql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

Parameters

database_name

The database name, as a string.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_create_db() - Create a FrontBase database

fbsql_db_status
fbsql_errno
FrontBase Functions


Returns the error number from previous operation

fbsql_drop_db
fbsql_error
FrontBase Functions
PHP Manual

fbsql_errno

(PHP 4 >= 4.0.6, PHP 5)

fbsql_errno — Returns the error number from previous operation

Description

int fbsql_errno ([ resource $link_identifier ] )

Returns the numerical value of the error message from previous FrontBase operation.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the error number from the last fbsql function, or 0 (zero) if no error occurred.

Examples

Example #1 fbsql_errno() Example

<?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
?>

See Also

  • fbsql_error() - Returns the error message from previous operation
  • fbsql_warnings() - Enable or disable FrontBase warnings

fbsql_drop_db
fbsql_error
FrontBase Functions


Returns the error message from previous operation

fbsql_errno
fbsql_fetch_array
FrontBase Functions
PHP Manual

fbsql_error

(PHP 4 >= 4.0.6, PHP 5)

fbsql_error — Returns the error message from previous operation

Description

string fbsql_error ([ resource $link_identifier ] )

Returns the error message from previous FrontBase operation.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_error() to retrieve the error text. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the error text from the last fbsql function, or '' (the empty string) if no error occurred.

Examples

Example #1 fbsql_error() Example

<?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
?>

See Also

  • fbsql_errno() - Returns the error number from previous operation
  • fbsql_warnings() - Enable or disable FrontBase warnings

fbsql_errno
fbsql_fetch_array
FrontBase Functions


Fetch a result row as an associative array, a numeric array, or both

fbsql_error
fbsql_fetch_assoc
FrontBase Functions
PHP Manual

fbsql_fetch_array

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Description

array fbsql_fetch_array ( resource $result [, int $result_type ] )

fbsql_fetch_array() is a combination of
fbsql_fetch_row() and
fbsql_fetch_assoc().

An important thing to note is that using fbsql_fetch_array() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

result_type

A constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, or FBSQL_BOTH.

When using FBSQL_BOTH, in addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must the numeric index of the column or make an alias for the column.

select t1.f1 as foo t2.f1 as bar from t1, t2

Examples

Example #1 fbsql_fetch_array() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select user_id, fullname from table");
while ($row = fbsql_fetch_array($result)) {
    echo "user_id: " . $row["user_id"] . "<br />\n";
    echo "user_id: " . $row[0] . "<br />\n";
    echo "fullname: " . $row["fullname"] . "<br />\n";
    echo "fullname: " . $row[1] . "<br />\n";
}
fbsql_free_result($result);
?>

See Also

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_assoc() - Fetch a result row as an associative array
  • fbsql_fetch_object() - Fetch a result row as an object

fbsql_error
fbsql_fetch_assoc
FrontBase Functions


Fetch a result row as an associative array

fbsql_fetch_array
fbsql_fetch_field
FrontBase Functions
PHP Manual

fbsql_fetch_assoc

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_assoc — Fetch a result row as an associative array

Description

array fbsql_fetch_assoc ( resource $result )

Calling fbsql_fetch_assoc() is equivalent to calling fbsql_fetch_array() with FBSQL_ASSOC as second parameter. It only returns an associative array.

This is the way fbsql_fetch_array() originally worked. If you need the numeric indices as well as the associative, use fbsql_fetch_array().

An important thing to note is that using fbsql_fetch_assoc() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use fbsql_fetch_array() and have it return the numeric indices as well.

Examples

Example #1 fbsql_fetch_assoc() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_assoc($result)) {
    echo $row["user_id"];
    echo $row["fullname"];
}
fbsql_free_result($result);
?>

See Also

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_object() - Fetch a result row as an object

fbsql_fetch_array
fbsql_fetch_field
FrontBase Functions


Get column information from a result and return as an object

fbsql_fetch_assoc
fbsql_fetch_lengths
FrontBase Functions
PHP Manual

fbsql_fetch_field

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_field — Get column information from a result and return as an object

Description

object fbsql_fetch_field ( resource $result [, int $field_offset ] )

Used in order to obtain information about fields in a certain query result.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0. If not specified, the next field that wasn't yet retrieved by fbsql_fetch_field() is retrieved.

Return Values

Returns an object containing field information, or FALSE on errors.

The properties of the object are:

  • name - column name
  • table - name of the table the column belongs to
  • max_length - maximum length of the column
  • not_null - 1 if the column cannot be NULL
  • type - the type of the column

Examples

Example #1 fbsql_fetch_field() example

<?php
fbsql_connect($host, $user, $password)
    or die("Could not connect");
$result = fbsql_db_query("database", "select * from table")
    or die("Query failed");
# get column metadata
$i = 0;
while ($i < fbsql_num_fields($result)) {
    echo "Information for column $i:<br />\n";
    $meta = fbsql_fetch_field($result);
    if (!$meta) {
        echo "No information available<br />\n";
    }
    echo "<pre>
max_length:   $meta->max_length
name:         $meta->name
not_null:     $meta->not_null
table:        $meta->table
type:         $meta->type
</pre>";
    $i++;
}
fbsql_free_result($result);
?>

See Also

  • fbsql_field_seek() - Set result pointer to a specified field offset

fbsql_fetch_assoc
fbsql_fetch_lengths
FrontBase Functions


Get the length of each output in a result

fbsql_fetch_field
fbsql_fetch_object
FrontBase Functions
PHP Manual

fbsql_fetch_lengths

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_lengths — Get the length of each output in a result

Description

array fbsql_fetch_lengths ( resource $result )

Stores the lengths of each result column in the last row returned by
fbsql_fetch_row(),
fbsql_fetch_array() and
fbsql_fetch_object() in an array.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an array, starting at offset 0, that corresponds to the lengths of each field in the last row fetched by fbsql_fetch_row(), or FALSE on error.

See Also

  • fbsql_fetch_row() - Get a result row as an enumerated array

fbsql_fetch_field
fbsql_fetch_object
FrontBase Functions


Fetch a result row as an object

fbsql_fetch_lengths
fbsql_fetch_row
FrontBase Functions
PHP Manual

fbsql_fetch_object

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_object — Fetch a result row as an object

Description

object fbsql_fetch_object ( resource $result )

fbsql_fetch_object() is similar to fbsql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to fbsql_fetch_array(), and almost as quick as fbsql_fetch_row() (the difference is insignificant).

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 fbsql_fetch_object() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
fbsql_free_result($result);
?>

See Also

  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_assoc() - Fetch a result row as an associative array

fbsql_fetch_lengths
fbsql_fetch_row
FrontBase Functions


Get a result row as an enumerated array

fbsql_fetch_object
fbsql_field_flags
FrontBase Functions
PHP Manual

fbsql_fetch_row

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_row — Get a result row as an enumerated array

Description

array fbsql_fetch_row ( resource $result )

fbsql_fetch_row() fetches one row of data from the result associated with the specified result identifier.

Subsequent call to fbsql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an array that corresponds to the fetched row where each result column is stored in an offset, starting at offset 0, or FALSE if there are no more rows.

See Also

  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_assoc() - Fetch a result row as an associative array
  • fbsql_fetch_object() - Fetch a result row as an object
  • fbsql_data_seek() - Move internal result pointer
  • fbsql_fetch_lengths() - Get the length of each output in a result
  • fbsql_result() - Get result data

fbsql_fetch_object
fbsql_field_flags
FrontBase Functions


Get the flags associated with the specified field in a result

fbsql_fetch_row
fbsql_field_len
FrontBase Functions
PHP Manual

fbsql_field_flags

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_flags — Get the flags associated with the specified field in a result

Description

string fbsql_field_flags ( resource $result [, int $field_offset ] )

Gets the flags associated with the specified field in a result.

Parameters

result

A result pointer returned by fbsql_list_fields().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the field flags of the specified field as a single word per flag separated by a single space, so that you can split the returned value using explode().

fbsql_fetch_row
fbsql_field_len
FrontBase Functions


Returns the length of the specified field

fbsql_field_flags
fbsql_field_name
FrontBase Functions
PHP Manual

fbsql_field_len

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_len — Returns the length of the specified field

Description

int fbsql_field_len ( resource $result [, int $field_offset ] )

Returns the length of the specified field.

Parameters

result

A result pointer returned by fbsql_list_fields().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the length of the specified field.

fbsql_field_flags
fbsql_field_name
FrontBase Functions


Get the name of the specified field in a result

fbsql_field_len
fbsql_field_seek
FrontBase Functions
PHP Manual

fbsql_field_name

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_name — Get the name of the specified field in a result

Description

string fbsql_field_name ( resource $result [, int $field_index ] )

Returns the name of the specified field index.

Parameters

result

A result pointer returned by fbsql_list_fields().

field_index

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the name as a string, or FALSE if the field doesn't exist.

Examples

Example #1 fbsql_field_name() example

<?php
// The users table consists of three fields:
//   user_id
//   username
//   password.

$res = fbsql_db_query("users", "select * from users", $link);

echo fbsql_field_name($res, 0) . "\n";
echo fbsql_field_name($res, 2);
?>

The above example will output:

user_id
password

See Also

  • fbsql_field_type() - Get the type of the specified field in a result

fbsql_field_len
fbsql_field_seek
FrontBase Functions


Set result pointer to a specified field offset

fbsql_field_name
fbsql_field_table
FrontBase Functions
PHP Manual

fbsql_field_seek

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_seek — Set result pointer to a specified field offset

Description

bool fbsql_field_seek ( resource $result [, int $field_offset ] )

Seeks to the specified field offset. If the next call to fbsql_fetch_field() doesn't include a field offset, the field offset specified in fbsql_field_seek() will be returned.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_fetch_field() - Get column information from a result and return as an object

fbsql_field_name
fbsql_field_table
FrontBase Functions


Get name of the table the specified field is in

fbsql_field_seek
fbsql_field_type
FrontBase Functions
PHP Manual

fbsql_field_table

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_table — Get name of the table the specified field is in

Description

string fbsql_field_table ( resource $result [, int $field_offset ] )

Returns the name of the table that the specified field is in.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the name of the table, as a string.

fbsql_field_seek
fbsql_field_type
FrontBase Functions


Get the type of the specified field in a result

fbsql_field_table
fbsql_free_result
FrontBase Functions
PHP Manual

fbsql_field_type

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_type — Get the type of the specified field in a result

Description

string fbsql_field_type ( resource $result [, int $field_offset ] )

fbsql_field_type() is similar to the fbsql_field_name() function, but the field type is returned instead.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the field type, as a string.

This can be one of int, real, string, blob, and others as detailed in the » FrontBase documentation.

Examples

Example #1 fbsql_field_type() example

<?php

fbsql_connect("localhost", "_SYSTEM", "");
fbsql_select_db("wisconsin");
$result = fbsql_query("SELECT * FROM onek;");
$fields = fbsql_num_fields($result);
$rows   = fbsql_num_rows($result);
$i = 0;
$table = fbsql_field_table($result, $i);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " records <br />";
echo "The table has the following fields <br />";
while ($i < $fields) {
    $type  = fbsql_field_type($result, $i);
    $name  = fbsql_field_name($result, $i);
    $len   = fbsql_field_len($result, $i);
    $flags = fbsql_field_flags($result, $i);
    echo $type . " " . $name . " " . $len . " " . $flags . "<br />";
    $i++;
}
fbsql_close();

?>

See Also

  • fbsql_field_name() - Get the name of the specified field in a result

fbsql_field_table
fbsql_free_result
FrontBase Functions


Free result memory

fbsql_field_type
fbsql_get_autostart_info
FrontBase Functions
PHP Manual

fbsql_free_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_free_result — Free result memory

Description

bool fbsql_free_result ( resource $result )

Frees all memory associated with the given result identifier.

fbsql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_field_type
fbsql_get_autostart_info
FrontBase Functions


fbsql_free_result
fbsql_hostname
FrontBase Functions
PHP Manual

fbsql_get_autostart_info

(PHP 4 >= 4.0.7, PHP 5)

fbsql_get_autostart_info —

Description

array fbsql_get_autostart_info ([ resource $link_identifier ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

fbsql_free_result
fbsql_hostname
FrontBase Functions


Get or set the host name used with a connection

fbsql_get_autostart_info
fbsql_insert_id
FrontBase Functions
PHP Manual

fbsql_hostname

(PHP 4 >= 4.0.6, PHP 5)

fbsql_hostname — Get or set the host name used with a connection

Description

string fbsql_hostname ( resource $link_identifier [, string $host_name ] )

Gets or sets the host name used with a connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

host_name

If provided, this will be the new connection host name.

Return Values

Returns the current host name used for the connection.

See Also

  • fbsql_username() - Get or set the username for the connection
  • fbsql_password() - Get or set the user password used with a connection

fbsql_get_autostart_info
fbsql_insert_id
FrontBase Functions


Get the id generated from the previous INSERT operation

fbsql_hostname
fbsql_list_dbs
FrontBase Functions
PHP Manual

fbsql_insert_id

(PHP 4 >= 4.0.6, PHP 5)

fbsql_insert_id — Get the id generated from the previous INSERT operation

Description

int fbsql_insert_id ([ resource $link_identifier ] )

Gets the id generated from the previous INSERT operation which created a DEFAULT UNIQUE value.

Note: The value of the FrontBase SQL function fbsql_insert_id() always contains the most recently generated DEFAULT UNIQUE value, and is not reset between queries.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the ID generated from the previous INSERT query, or 0 if the previous query does not generate an DEFAULT UNIQUE value.

If you need to save the value for later, be sure to call this function immediately after the query that generates the value.

See Also

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation

fbsql_hostname
fbsql_list_dbs
FrontBase Functions


List databases available on a FrontBase server

fbsql_insert_id
fbsql_list_fields
FrontBase Functions
PHP Manual

fbsql_list_dbs

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_dbs — List databases available on a FrontBase server

Description

resource fbsql_list_dbs ([ resource $link_identifier ] )

Return a result pointer containing the databases available from the current fbsql daemon. Use the fbsql_tablename() to traverse this result pointer.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a result pointer or FALSE on error.

Examples

Example #1 fbsql_list_dbs() example

$link = fbsql_connect('localhost', 'myname', 'secret');
$db_list = fbsql_list_dbs($link);

while ($row = fbsql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}

The above example will output something similar to:

database1
database2
database3
...

Note: The above code would just as easily work with fbsql_fetch_row() or other similar functions.

See Also

  • fbsql_list_fields() - List FrontBase result fields
  • fbsql_list_tables() - List tables in a FrontBase database

fbsql_insert_id
fbsql_list_fields
FrontBase Functions


List FrontBase result fields

fbsql_list_dbs
fbsql_list_tables
FrontBase Functions
PHP Manual

fbsql_list_fields

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_fields — List FrontBase result fields

Description

resource fbsql_list_fields ( string $database_name , string $table_name [, resource $link_identifier ] )

Retrieves information about the given table.

Parameters

database_name

The database name.

table_name

The table name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a result pointer which can be used with the fbsql_field_xxx functions, or FALSE on error.

Errors/Exceptions

A string describing the error will be placed in $phperrmsg, and unless the function was called as @fbsql() then this error string will also be printed out.

Examples

Example #1 fbsql_list_fields() example

<?php
$link = fbsql_connect('localhost', 'myname', 'secret');

$fields = fbsql_list_fields("database1", "table1", $link);
$columns = fbsql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo fbsql_field_name($fields, $i) . "\n";;
}
?>

The above example will output something similar to:

field1
field2
field3
...

See Also

  • fbsql_field_len() - Returns the length of the specified field
  • fbsql_field_name() - Get the name of the specified field in a result
  • fbsql_field_type() - Get the type of the specified field in a result
  • fbsql_field_flags() - Get the flags associated with the specified field in a result

fbsql_list_dbs
fbsql_list_tables
FrontBase Functions


List tables in a FrontBase database

fbsql_list_fields
fbsql_next_result
FrontBase Functions
PHP Manual

fbsql_list_tables

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_tables — List tables in a FrontBase database

Description

resource fbsql_list_tables ( string $database [, resource $link_identifier ] )

Returns a result pointer describing the database .

Parameters

database

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a result pointer which can be used with the fbsql_tablename() function to read the actual table names, or FALSE on error.

See Also

  • fbsql_list_fields() - List FrontBase result fields
  • fbsql_list_dbs() - List databases available on a FrontBase server

fbsql_list_fields
fbsql_next_result
FrontBase Functions


Move the internal result pointer to the next result

fbsql_list_tables
fbsql_num_fields
FrontBase Functions
PHP Manual

fbsql_next_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_next_result — Move the internal result pointer to the next result

Description

bool fbsql_next_result ( resource $result )

When sending more than one SQL statement to the server or executing a stored procedure with multiple results will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the words from the new result set.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns TRUE if an additional result set was available or FALSE otherwise.

Examples

Example #1 fbsql_next_result() example

<?php
$link = fbsql_connect("localhost", "_SYSTEM", "secret");
fbsql_select_db("MyDB", $link);
$SQL = "Select * from table1; select * from table2;";
$rs = fbsql_query($SQL, $link);
do {
    while ($row = fbsql_fetch_row($rs)) {
    }
} while (fbsql_next_result($rs));
fbsql_free_result($rs);
fbsql_close($link);
?>

fbsql_list_tables
fbsql_num_fields
FrontBase Functions


Get number of fields in result

fbsql_next_result
fbsql_num_rows
FrontBase Functions
PHP Manual

fbsql_num_fields

(PHP 4 >= 4.0.6, PHP 5)

fbsql_num_fields — Get number of fields in result

Description

int fbsql_num_fields ( resource $result )

Returns the number of fields in the given result set.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of fields, as an integer.

See Also

  • fbsql_db_query() - Send a FrontBase query
  • fbsql_query() - Send a FrontBase query
  • fbsql_fetch_field() - Get column information from a result and return as an object
  • fbsql_num_rows() - Get number of rows in result

fbsql_next_result
fbsql_num_rows
FrontBase Functions


Get number of rows in result

fbsql_num_fields
fbsql_password
FrontBase Functions
PHP Manual

fbsql_num_rows

(PHP 4 >= 4.0.6, PHP 5)

fbsql_num_rows — Get number of rows in result

Description

int fbsql_num_rows ( resource $result )

Gets the number of rows in the given result set.

This function is only valid for SELECT statements. To retrieve the number of rows returned from a INSERT, UPDATE or DELETE query, use fbsql_affected_rows().

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of rows returned by the last SELECT statement.

Examples

Example #1 fbsql_num_rows() example

<?php

$link = fbsql_connect("localhost", "username", "password");
fbsql_select_db("database", $link);

$result = fbsql_query("SELECT * FROM table1;", $link);
$num_rows = fbsql_num_rows($result);

echo "$num_rows Rows\n";

?>

See Also

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation
  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_select_db() - Select a FrontBase database
  • fbsql_query() - Send a FrontBase query

fbsql_num_fields
fbsql_password
FrontBase Functions


Get or set the user password used with a connection

fbsql_num_rows
fbsql_pconnect
FrontBase Functions
PHP Manual

fbsql_password

(PHP 4 >= 4.0.6, PHP 5)

fbsql_password — Get or set the user password used with a connection

Description

string fbsql_password ( resource $link_identifier [, string $password ] )

Get or set the user password used with a connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

password

If provided, this will be the new connection password.

Return Values

Returns the current password used for the connection.

See Also

  • fbsql_username() - Get or set the username for the connection
  • fbsql_hostname() - Get or set the host name used with a connection

fbsql_num_rows
fbsql_pconnect
FrontBase Functions


Open a persistent connection to a FrontBase Server

fbsql_password
fbsql_query
FrontBase Functions
PHP Manual

fbsql_pconnect

(PHP 4 >= 4.0.6, PHP 5)

fbsql_pconnect — Open a persistent connection to a FrontBase Server

Description

 resource fbsql_pconnect
  ([ string $hostname = ini_get("fbsql.default_host")
 [, string $username = ini_get("fbsql.default_user")
 [, string $password = ini_get("fbsql.default_password")
]]] )

Establishes a persistent connection to a FrontBase server.

To set the server port number, use fbsql_select_db().

fbsql_pconnect() acts very much like fbsql_connect() with two major differences:

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

This type of links is therefore called 'persistent'.

Parameters

hostname

The server host name.

username

The user name for the connection.

password

The password for the connection.

Return Values

Returns a positive FrontBase persistent link identifier on success, or FALSE on error.

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server

fbsql_password
fbsql_query
FrontBase Functions


Send a FrontBase query

fbsql_pconnect
fbsql_read_blob
FrontBase Functions
PHP Manual

fbsql_query

(PHP 4 >= 4.0.6, PHP 5)

fbsql_query — Send a FrontBase query

Description

resource fbsql_query ( string $query [, resource $link_identifier [, int $batch_size ]] )

Sends a query to the currently active database on the server.

If the query succeeds, you can call fbsql_num_rows() to find out how many rows were returned for a SELECT statement or fbsql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

Parameters

query

The SQL query to be executed.

Note: The query string shall always end with a semicolon.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

batch_size

Return Values

fbsql_query() returns TRUE (non-zero) or FALSE to indicate whether or not the query succeeded. A return value of TRUE means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.

For SELECT statements, fbsql_query() returns a new result identifier that you can pass to fbsql_result().

fbsql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.

Examples

The following query is syntactically invalid, so fbsql_query() fails and returns FALSE:

Example #1 fbsql_query() example

<?php
$result = fbsql_query("SELECT * WHERE 1=1")
    or die ("Invalid query");
?>

The following query is semantically invalid if my_col is not a column in the table my_tbl, so fbsql_query() fails and returns FALSE:

Example #2 fbsql_query() example

<?php
$result = fbsql_query ("SELECT my_col FROM my_tbl;")
    or die ("Invalid query");
?>

See Also

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation
  • fbsql_db_query() - Send a FrontBase query
  • fbsql_free_result() - Free result memory
  • fbsql_result() - Get result data
  • fbsql_select_db() - Select a FrontBase database
  • fbsql_connect() - Open a connection to a FrontBase Server

fbsql_pconnect
fbsql_read_blob
FrontBase Functions


Read a BLOB from the database

fbsql_query
fbsql_read_clob
FrontBase Functions
PHP Manual

fbsql_read_blob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_read_blob — Read a BLOB from the database

Description

string fbsql_read_blob ( string $blob_handle [, resource $link_identifier ] )

Reads BLOB data from the database.

If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_blob() to get the actual BLOB data from the database.

Parameters

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a string containing the specified BLOB data.

Examples

Example #1 fbsql_read_blob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$sql = "SELECT BLOB_COLUMN FROM BLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain the blob data for the first row
fbsql_free_result($rs);

$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain a handle to the BLOB data in the first row
$blob_data = fbsql_read_blob($row_data[0]);
fbsql_free_result($rs);

?>

See Also

  • fbsql_create_blob() - Create a BLOB
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

fbsql_query
fbsql_read_clob
FrontBase Functions


Read a CLOB from the database

fbsql_read_blob
fbsql_result
FrontBase Functions
PHP Manual

fbsql_read_clob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_read_clob — Read a CLOB from the database

Description

string fbsql_read_clob ( string $clob_handle [, resource $link_identifier ] )

Reads CLOB data from the database.

If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_clob() to get the actual CLOB data from the database.

Parameters

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a string containing the specified CLOB data.

Examples

Example #1 fbsql_read_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$sql = "SELECT CLOB_COLUMN FROM CLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain the clob data for the first row
fbsql_free_result($rs);

$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain a handle to the CLOB data in the first row
$clob_data = fbsql_read_clob($row_data[0]);
fbsql_free_result($rs);

?>

See Also

  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

fbsql_read_blob
fbsql_result
FrontBase Functions


Get result data

fbsql_read_clob
fbsql_rollback
FrontBase Functions
PHP Manual

fbsql_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_result — Get result data

Description

mixed fbsql_result ( resource $result [, int $row [, mixed $field ]] )

Returns the contents of one cell from a FrontBase result set.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than fbsql_result().

Calls to fbsql_result() should not be mixed with calls to other functions that deal with the result set.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

row

field

Can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname).

If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

Note: Specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Return Values

See Also

Recommended high-performance alternatives:

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_assoc() - Fetch a result row as an associative array
  • fbsql_fetch_object() - Fetch a result row as an object

fbsql_read_clob
fbsql_rollback
FrontBase Functions


Rollback a transaction to the database

fbsql_result
fbsql_rows_fetched
FrontBase Functions
PHP Manual

fbsql_rollback

(PHP 4 >= 4.0.6, PHP 5)

fbsql_rollback — Rollback a transaction to the database

Description

bool fbsql_rollback ([ resource $link_identifier ] )

Ends the current transaction by rolling back all statements issued since last commit.

This command is only needed if autocommit is set to false.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_autocommit() - Enable or disable autocommit
  • fbsql_commit() - Commits a transaction to the database

fbsql_result
fbsql_rows_fetched
FrontBase Functions


Get the number of rows affected by the last statement

fbsql_rollback
fbsql_select_db
FrontBase Functions
PHP Manual

fbsql_rows_fetched

(PHP 5 >= 5.1.0)

fbsql_rows_fetched — Get the number of rows affected by the last statement

Description

int fbsql_rows_fetched ( resource $result )

Gets the number of rows affected by the last statement.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of rows, as an integer.

fbsql_rollback
fbsql_select_db
FrontBase Functions


Select a FrontBase database

fbsql_rows_fetched
fbsql_set_characterset
FrontBase Functions
PHP Manual

fbsql_select_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_select_db — Select a FrontBase database

Description

bool fbsql_select_db ([ string $database_name [, resource $link_identifier ]] )

Sets the current active database on the given link identifier.

The client contacts FBExec to obtain the port number to use for the connection to the database. If the database name is a number the system will use that as a port number and it will not ask FBExec for the port number. The FrontBase server can be stared as FRontBase -FBExec=No -port=<port number> <database name>.

Every subsequent call to fbsql_query() will be made on the active database.

Parameters

database_name

The name of the database to be selected.

If the database is protected with a database password, the you must call fbsql_database_password() before selecting the database.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_database_password() - Sets or retrieves the password for a FrontBase database
  • fbsql_query() - Send a FrontBase query

fbsql_rows_fetched
fbsql_set_characterset
FrontBase Functions


Change input/output character set

fbsql_select_db
fbsql_set_lob_mode
FrontBase Functions
PHP Manual

fbsql_set_characterset

(PHP 5 >= 5.1.0)

fbsql_set_characterset — Change input/output character set

Description

void fbsql_set_characterset ( resource $link_identifier , int $characterset [, int $in_out_both ] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

fbsql_select_db
fbsql_set_lob_mode
FrontBase Functions


Set the LOB retrieve mode for a FrontBase result set

fbsql_set_characterset
fbsql_set_password
FrontBase Functions
PHP Manual

fbsql_set_lob_mode

(PHP 4 >= 4.2.0, PHP 5)

fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set

Description

bool fbsql_set_lob_mode ( resource $result , int $lob_mode )

Sets the mode for retrieving LOB data from the database.

When BLOB and CLOB data is retrieved in FrontBase it can be retrieved direct or indirect. Direct retrieved LOB data will always be fetched no matter the setting of the lob mode. If the LOB data is less than 512 bytes it will always be retrieved directly.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

lob_mode

Can be one of:

  • FBSQL_LOB_DIRECT - LOB data is retrieved directly. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, all CLOB and BLOB columns will be returned as ordinary columns. This is the default value on a new FrontBase result.
  • FBSQL_LOB_HANDLE - LOB data is retrieved as handles to the data. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, LOB data will be returned as a handle to the data if the data is stored indirect or the data if it is stored direct. If a handle is returned it will be a 27 byte string formatted as @'000000000000000000000000'.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_create_blob() - Create a BLOB
  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database

fbsql_set_characterset
fbsql_set_password
FrontBase Functions


Change the password for a given user

fbsql_set_lob_mode
fbsql_set_transaction
FrontBase Functions
PHP Manual

fbsql_set_password

(PHP 5)

fbsql_set_password — Change the password for a given user

Description

bool fbsql_set_password ( resource $link_identifier , string $user , string $password , string $old_password )

Changes the password for the given user .

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

user

The user name.

password

The new password to be set.

old_password

The old password to be replaced.

Return Values

Returns TRUE on success or FALSE on failure.

fbsql_set_lob_mode
fbsql_set_transaction
FrontBase Functions


Set the transaction locking and isolation

fbsql_set_password
fbsql_start_db
FrontBase Functions
PHP Manual

fbsql_set_transaction

(PHP 4 >= 4.2.0, PHP 5)

fbsql_set_transaction — Set the transaction locking and isolation

Description

void fbsql_set_transaction ( resource $link_identifier , int $locking , int $isolation )

Sets the transaction locking and isolation .

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

locking

The type of locking to be set. It can be one of the following constants: FBSQL_LOCK_DEFERRED, FBSQL_LOCK_OPTIMISTIC, or FBSQL_LOCK_PESSIMISTIC.

isolation

The type of isolation to be set. It can be one of the following constants: FBSQL_ISO_READ_UNCOMMITTED, FBSQL_ISO_READ_COMMITTED, FBSQL_ISO_REPEATABLE_READ, FBSQL_ISO_SERIALIZABLE, or FBSQL_ISO_VERSIONED.

Return Values

No value is returned.

fbsql_set_password
fbsql_start_db
FrontBase Functions


Start a database on local or remote server

fbsql_set_transaction
fbsql_stop_db
FrontBase Functions
PHP Manual

fbsql_start_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_start_db — Start a database on local or remote server

Description

bool fbsql_start_db ( string $database_name [, resource $link_identifier [, string $database_options ]] )

Start a database on local or remote server.

Parameters

database_name

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

database_options

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_db_status() - Get the status for a given database
  • fbsql_stop_db() - Stop a database on local or remote server

fbsql_set_transaction
fbsql_stop_db
FrontBase Functions


Stop a database on local or remote server

fbsql_start_db
fbsql_table_name
FrontBase Functions
PHP Manual

fbsql_stop_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_stop_db — Stop a database on local or remote server

Description

bool fbsql_stop_db ( string $database_name [, resource $link_identifier ] )

Stops a database on local or remote server.

Parameters

database_name

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_db_status() - Get the status for a given database
  • fbsql_start_db() - Start a database on local or remote server

fbsql_start_db
fbsql_table_name
FrontBase Functions


Get table name of field

fbsql_stop_db
fbsql_tablename
FrontBase Functions
PHP Manual

fbsql_table_name

(PHP 4 >= 4.2.0, PHP 5)

fbsql_table_name — Get table name of field

Description

string fbsql_table_name ( resource $result , int $index )

fbsql_table_name() gets the name of the current table in the given result set.

The fbsql_num_rows() function may be used to determine the number of tables in the result pointer.

Parameters

result

A result pointer returned by fbsql_list_tables().

index

Integer index for the current table.

Return Values

Returns the name of the table, as a string.

Examples

Example #1 fbsql_table_name() example

<?php
fbsql_connect("localhost", "_SYSTEM", "");
$result = fbsql_list_tables("wisconsin");
$i = 0;
while ($i < fbsql_num_rows($result)) {
    $tb_names[$i] = fbsql_table_name($result, $i);
    echo $tb_names[$i] . "<br />";
    $i++;
}
?>

fbsql_stop_db
fbsql_tablename
FrontBase Functions


Alias of of fbsql_table_name

fbsql_table_name
fbsql_username
FrontBase Functions
PHP Manual

fbsql_tablename

(PHP 4 >= 4.2.0, PHP 5)

fbsql_tablename — Alias of of fbsql_table_name()

Description

This function is an alias of: fbsql_table_name().

fbsql_table_name
fbsql_username
FrontBase Functions


Get or set the username for the connection

fbsql_tablename
fbsql_warnings
FrontBase Functions
PHP Manual

fbsql_username

(PHP 4 >= 4.0.6, PHP 5)

fbsql_username — Get or set the username for the connection

Description

string fbsql_username ( resource $link_identifier [, string $username ] )

Get or set the username used for the connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

username

If provided, this is the new username to set.

Return Values

Returns the current username used with the connection, as a string.

See Also

  • fbsql_password() - Get or set the user password used with a connection
  • fbsql_hostname() - Get or set the host name used with a connection

fbsql_tablename
fbsql_warnings
FrontBase Functions


Enable or disable FrontBase warnings

fbsql_username
filePro
FrontBase Functions
PHP Manual

fbsql_warnings

(PHP 4 >= 4.0.6, PHP 5)

fbsql_warnings — Enable or disable FrontBase warnings

Description

bool fbsql_warnings ([ bool $OnOff ] )

Enables or disables FrontBase warnings.

Parameters

OnOff

Whether to enable warnings or no.

Return Values

Returns TRUE if warnings is turned on, FALSE otherwise.

See Also

  • fbsql_errno() - Returns the error number from previous operation
  • fbsql_error() - Returns the error message from previous operation

fbsql_username
filePro
FrontBase Functions


Closes an open file pointer

diskfreespace
feof
Filesystem Functions
PHP Manual

fclose

(PHP 4, PHP 5)

fclose — Closes an open file pointer

Description

bool fclose ( resource $handle )

The file pointed to by handle is closed.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A simple fclose() example

<?php

$handle = fopen('somefile.txt', 'r');

fclose($handle);

?>

See Also

  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection

diskfreespace
feof
Filesystem Functions


Adds javascript code to the FDF document

FDF Functions
fdf_add_template
FDF Functions
PHP Manual

fdf_add_doc_javascript

(PHP 4 >= 4.3.0, PHP 5)

fdf_add_doc_javascript — Adds javascript code to the FDF document

Description

bool fdf_add_doc_javascript ( resource $fdf_document , string $script_name , string $script_code )

Adds a script to the FDF, which Acrobat then adds to the doc-level scripts of a document, once the FDF is imported into it.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

script_name

The script name.

script_code

The script code. It is strongly suggested to use \r for linebreaks within the script code.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Adding JavaScript code to a FDF

<?php
$fdf = fdf_create();
fdf_add_doc_javascript($fdf, "PlusOne", "function PlusOne(x)\r{\r  return x+1;\r}\r");
fdf_save($fdf);
?>

will create a FDF like this:

%FDF-1.2
%âãÏÓ
1 0 obj
<<
/FDF << /JavaScript << /Doc [ (PlusOne)(function PlusOne\(x\)\r{\r  return x+1;\r}\r)] >> >>
>>
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF

FDF Functions
fdf_add_template
FDF Functions


Adds a template into the FDF document

fdf_add_doc_javascript
fdf_close
FDF Functions
PHP Manual

fdf_add_template

(PHP 4, PHP 5)

fdf_add_template — Adds a template into the FDF document

Description

bool fdf_add_template ( resource $fdf_document , int $newpage , string $filename , string $template , int $rename )
Warning

This function is currently not documented; only its argument list is available.

fdf_add_doc_javascript
fdf_close
FDF Functions


Close an FDF document

fdf_add_template
fdf_create
FDF Functions
PHP Manual

fdf_close

(PHP 4, PHP 5)

fdf_close — Close an FDF document

Description

void fdf_close ( resource $fdf_document )

Closes the FDF document.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

No value is returned.

See Also

  • fdf_open() - Open a FDF document

fdf_add_template
fdf_create
FDF Functions


Create a new FDF document

fdf_close
fdf_enum_values
FDF Functions
PHP Manual

fdf_create

(PHP 4, PHP 5)

fdf_create — Create a new FDF document

Description

resource fdf_create ( void )

Creates a new FDF document.

This function is needed if one would like to populate input fields in a PDF document with data.

Return Values

Returns a FDF document handle, or FALSE on error.

Examples

Example #1 Populating a PDF document

<?php
$outfdf = fdf_create();
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf);
Header("Content-type: application/vnd.fdf");
$fp = fopen("outtest.fdf", "r");
fpassthru($fp);
unlink("outtest.fdf");
?>

See Also

  • fdf_close() - Close an FDF document
  • fdf_save() - Save a FDF document
  • fdf_open() - Open a FDF document

fdf_close
fdf_enum_values
FDF Functions


Call a user defined function for each document value

fdf_create
fdf_errno
FDF Functions
PHP Manual

fdf_enum_values

(PHP 4 >= 4.3.0, PHP 5)

fdf_enum_values — Call a user defined function for each document value

Description

bool fdf_enum_values ( resource $fdf_document , callback $function [, mixed $userdata ] )
Warning

This function is currently not documented; only its argument list is available.

fdf_create
fdf_errno
FDF Functions


Return error code for last fdf operation

fdf_enum_values
fdf_error
FDF Functions
PHP Manual

fdf_errno

(PHP 4 >= 4.3.0, PHP 5)

fdf_errno — Return error code for last fdf operation

Description

int fdf_errno ( void )

Gets the error code set by the last FDF function call.

A textual description of the error may be obtained using with fdf_error().

Return Values

Returns the error code as an integer, or zero if there was no errors.

See Also

  • fdf_error() - Return error description for FDF error code

fdf_enum_values
fdf_error
FDF Functions


Return error description for FDF error code

fdf_errno
fdf_get_ap
FDF Functions
PHP Manual

fdf_error

(PHP 4 >= 4.3.0, PHP 5)

fdf_error — Return error description for FDF error code

Description

string fdf_error ([ int $error_code ] )

Gets a textual description for the FDF error code given in error_code .

Parameters

error_code

An error code obtained with fdf_errno(). If not provided, this function uses the internal error code set by the last operation.

Return Values

Returns the error message as a string, or the string no error if nothing went wrong.

See Also

  • fdf_errno() - Return error code for last fdf operation

fdf_errno
fdf_get_ap
FDF Functions


Get the appearance of a field

fdf_error
fdf_get_attachment
FDF Functions
PHP Manual

fdf_get_ap

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_ap — Get the appearance of a field

Description

bool fdf_get_ap ( resource $fdf_document , string $field , int $face , string $filename )

Gets the appearance of a field (i.e. the value of the /AP key) and stores it in a file.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

field

face

The possible values are FDFNormalAP, FDFRolloverAP and FDFDownAP.

filename

The appearance will be stored in this parameter.

Return Values

Returns TRUE on success or FALSE on failure.

fdf_error
fdf_get_attachment
FDF Functions


Extracts uploaded file embedded in the FDF

fdf_get_ap
fdf_get_encoding
FDF Functions
PHP Manual

fdf_get_attachment

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_attachment — Extracts uploaded file embedded in the FDF

Description

array fdf_get_attachment ( resource $fdf_document , string $fieldname , string $savepath )

Extracts a file uploaded by means of the "file selection" field fieldname and stores it under savepath .

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

savepath

May be the name of a plain file or an existing directory in which the file is to be created under its original name. Any existing file under the same name will be overwritten.

Note: There seems to be no other way to find out the original filename but to store the file using a directory as savepath and check for the basename it was stored under.

Return Values

The returned array contains the following fields:

  • path - path were the file got stored
  • size - size of the stored file in bytes
  • type - mimetype if given in the FDF

Examples

Example #1 Storing an uploaded file

<?php
  $fdf = fdf_open_string($HTTP_FDF_DATA);
  $data = fdf_get_attachment($fdf, "filename", "/tmpdir");
  echo "The uploaded file is stored in $data[path]";
?>

fdf_get_ap
fdf_get_encoding
FDF Functions


Get the value of the /Encoding key

fdf_get_attachment
fdf_get_file
FDF Functions
PHP Manual

fdf_get_encoding

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_encoding — Get the value of the /Encoding key

Description

string fdf_get_encoding ( resource $fdf_document )

Gets the value of the /Encoding key.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the encoding as a string. An empty string is returned if the default PDFDocEncoding/Unicode scheme is used.

See Also

  • fdf_set_encoding() - Sets FDF character encoding

fdf_get_attachment
fdf_get_file
FDF Functions


Get the value of the /F key

fdf_get_encoding
fdf_get_flags
FDF Functions
PHP Manual

fdf_get_file

(PHP 4, PHP 5)

fdf_get_file — Get the value of the /F key

Description

string fdf_get_file ( resource $fdf_document )

Gets the value of the /F key.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the key value, as a string.

See Also

  • fdf_set_file() - Set PDF document to display FDF data in

fdf_get_encoding
fdf_get_flags
FDF Functions


Gets the flags of a field

fdf_get_file
fdf_get_opt
FDF Functions
PHP Manual

fdf_get_flags

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_flags — Gets the flags of a field

Description

int fdf_get_flags ( resource $fdf_document , string $fieldname , int $whichflags )
Warning

This function is currently not documented; only its argument list is available.

fdf_get_file
fdf_get_opt
FDF Functions


Gets a value from the opt array of a field

fdf_get_flags
fdf_get_status
FDF Functions
PHP Manual

fdf_get_opt

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_opt — Gets a value from the opt array of a field

Description

mixed fdf_get_opt ( resource $fdf_document , string $fieldname [, int $element ] )
Warning

This function is currently not documented; only its argument list is available.

fdf_get_flags
fdf_get_status
FDF Functions


Get the value of the /STATUS key

fdf_get_opt
fdf_get_value
FDF Functions
PHP Manual

fdf_get_status

(PHP 4, PHP 5)

fdf_get_status — Get the value of the /STATUS key

Description

string fdf_get_status ( resource $fdf_document )

Gets the value of the /STATUS key.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the key value, as a string.

See Also

  • fdf_set_status() - Set the value of the /STATUS key

fdf_get_opt
fdf_get_value
FDF Functions


Get the value of a field

fdf_get_status
fdf_get_version
FDF Functions
PHP Manual

fdf_get_value

(PHP 4, PHP 5)

fdf_get_value — Get the value of a field

Description

mixed fdf_get_value ( resource $fdf_document , string $fieldname [, int $which ] )

Gets the value for the requested field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

which

Elements of an array field can be retrieved by passing this optional parameter, starting at zero. For non-array fields, this parameter will be ignored.

Return Values

Returns the field value.

Changelog

Version | Description
4.3.0 | Support for arrays and the which parameter were added.

See Also

  • fdf_set_value() - Set the value of a field

fdf_get_status
fdf_get_version
FDF Functions


Gets version number for FDF API or file

fdf_get_value
fdf_header
FDF Functions
PHP Manual

fdf_get_version

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_version — Gets version number for FDF API or file

Description

string fdf_get_version ([ resource $fdf_document ] )

Return the FDF version for the given document, or the toolkit API version number if no parameter is given.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the version as a string. For the current FDF toolkit 5.0 the API version number is 5.0 and the document version number is either 1.2, 1.3 or 1.4.

See Also

  • fdf_set_version() - Sets version number for a FDF file

fdf_get_value
fdf_header
FDF Functions


Sets FDF-specific output headers

fdf_get_version
fdf_next_field_name
FDF Functions
PHP Manual

fdf_header

(PHP 4 >= 4.3.0, PHP 5)

fdf_header — Sets FDF-specific output headers

Description

void fdf_header ( void )

This is a convenience function to set appropriate HTTP headers for FDF output. It sets the Content-type: to application/vnd.fdf.

Return Values

No value is returned.

fdf_get_version
fdf_next_field_name
FDF Functions


Get the next field name

fdf_header
fdf_open_string
FDF Functions
PHP Manual

fdf_next_field_name

(PHP 4, PHP 5)

fdf_next_field_name — Get the next field name

Description

string fdf_next_field_name ( resource $fdf_document [, string $fieldname ] )

Gets the name of the field after the given field. This name can be used with several functions.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string. If not given, the first field will be assumed.

Return Values

Returns the field name as a string.

Examples

Example #1 Detecting all fieldnames in a FDF

<?php
$fdf = fdf_open($HTTP_FDF_DATA);
for ($field = fdf_next_field_name($fdf);
    $field != "";
    $field = fdf_next_field_name($fdf, $field)) {
    echo "field: $field\n";
}
?>

See Also

  • fdf_get_value() - Get the value of a field

fdf_header
fdf_open_string
FDF Functions


Open a FDF document

fdf_open_string
fdf_remove_item
FDF Functions
PHP Manual

fdf_open

(PHP 4, PHP 5)

fdf_open — Open a FDF document

Description

resource fdf_open ( string $filename )

Opens a file with form data.

You can also use fdf_open_string() to process the results of a PDF form POST request.

Parameters

filename

Path to the FDF file. This file must contain the data as returned from a PDF form or created using fdf_create() and fdf_save().

Return Values

Returns a FDF document handle, or FALSE on error.

Examples

Example #1 Accessing the form data

<?php
// Save the FDF data into a temp file
$fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA));
fclose($fdffp);

// Open temp file and evaluate data
$fdf = fdf_open("test.fdf");
/* ... */
fdf_close($fdf);
?>

See Also

  • fdf_open_string() - Read a FDF document from a string
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save() - Save a FDF document

fdf_open_string
fdf_remove_item
FDF Functions


Read a FDF document from a string

fdf_next_field_name
fdf_open
FDF Functions
PHP Manual

fdf_open_string

(PHP 4 >= 4.3.0, PHP 5)

fdf_open_string — Read a FDF document from a string

Description

resource fdf_open_string ( string $fdf_data )

Reads form data from a string.

You can use fdf_open_string() together with $HTTP_FDF_DATA to process FDF form input from a remote client.

Parameters

fdf_data

The data as returned from a PDF form or created using fdf_create() and fdf_save_string().

Return Values

Returns a FDF document handle, or FALSE on error.

Examples

Example #1 Accessing the form data

<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
/* ... */
fdf_close($fdf);
?>

See Also

  • fdf_open() - Open a FDF document
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save_string() - Returns the FDF document as a string

fdf_next_field_name
fdf_open
FDF Functions


Sets target frame for form

fdf_open
fdf_save_string
FDF Functions
PHP Manual

fdf_remove_item

(PHP 4 >= 4.3.0, PHP 5)

fdf_remove_item — Sets target frame for form

Description

bool fdf_remove_item ( resource $fdf_document , string $fieldname , int $item )
Warning

This function is currently not documented; only its argument list is available.

fdf_open
fdf_save_string
FDF Functions


Save a FDF document

fdf_save_string
fdf_set_ap
FDF Functions
PHP Manual

fdf_save

(PHP 4, PHP 5)

fdf_save — Save a FDF document

Description

bool fdf_save ( resource $fdf_document [, string $filename ] )

Saves a FDF document.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

filename

If provided, the resulting FDF will be written in this parameter. Otherwise, this function will write the FDF to the default PHP output stream.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save_string() - Returns the FDF document as a string

fdf_save_string
fdf_set_ap
FDF Functions


Returns the FDF document as a string

fdf_remove_item
fdf_save
FDF Functions
PHP Manual

fdf_save_string

(PHP 4 >= 4.3.0, PHP 5)

fdf_save_string — Returns the FDF document as a string

Description

string fdf_save_string ( resource $fdf_document )

Returns the FDF document as a string.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Return Values

Returns the document as a string, or FALSE on error.

Examples

Example #1 Retrieving FDF as a string

<?php
$fdf = fdf_create();
fdf_set_value($fdf, "foo", "bar");
$str = fdf_save_string($fdf);
fdf_close($fdf);
echo $str;
?>

The above example will output:

%FDF-1.2
%âãÏÓ
1 0 obj
<<
/FDF << /Fields 2 0 R >>
>>
endobj
2 0 obj
[
<< /T (foo)/V (bar)>>
]
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF

See Also

  • fdf_open_string() - Read a FDF document from a string
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save() - Save a FDF document

fdf_remove_item
fdf_save
FDF Functions


Set the appearance of a field

fdf_save
fdf_set_encoding
FDF Functions
PHP Manual

fdf_set_ap

(PHP 4, PHP 5)

fdf_set_ap — Set the appearance of a field

Description

bool fdf_set_ap ( resource $fdf_document , string $field_name , int $face , string $filename , int $page_number )

Sets the appearance of a field (i.e. the value of the /AP key).

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

field_name

face

The possible values FDFNormalAP, FDFRolloverAP and FDFDownAP.

filename

page_number

Return Values

Returns TRUE on success or FALSE on failure.

fdf_save
fdf_set_encoding
FDF Functions


Sets FDF character encoding

fdf_set_ap
fdf_set_file
FDF Functions
PHP Manual

fdf_set_encoding

(PHP 4 >= 4.0.7, PHP 5)

fdf_set_encoding — Sets FDF character encoding

Description

bool fdf_set_encoding ( resource $fdf_document , string $encoding )

Sets the character encoding for the FDF document.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

encoding

The encoding name. The following values are supported: "Shift-JIS", "UHC", "GBK" and "BigFive".

An empty string resets the encoding to the default PDFDocEncoding/Unicode scheme.

Return Values

Returns TRUE on success or FALSE on failure.

fdf_set_ap
fdf_set_file
FDF Functions


Set PDF document to display FDF data in

fdf_set_encoding
fdf_set_flags
FDF Functions
PHP Manual

fdf_set_file

(PHP 4, PHP 5)

fdf_set_file — Set PDF document to display FDF data in

Description

bool fdf_set_file ( resource $fdf_document , string $url [, string $target_frame ] )

Selects a different PDF document to display the form results in then the form it originated from.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

url

Should be given as an absolute URL.

target_frame

Use this parameter to specify the frame in which the document will be displayed. You can also set the default value for this parameter using fdf_set_target_frame().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Passing FDF data to a second form

<?php
  /* set content type for Adobe FDF */
  fdf_header();

  /* start new fdf */
  $fdf = fdf_create();

  /* set field "foo" to value "bar" */
  fdf_set_value($fdf, "foo", "bar");

  /* tell client to display FDF data using "fdf_form.pdf" */
  fdf_set_file($fdf, "http://www.example.com/fdf_form.pdf");

  /* output fdf */
  fdf_save($fdf);

  /* clean up */
  fdf_close($fdf);
?>

See Also

  • fdf_get_file() - Get the value of the /F key
  • fdf_set_target_frame() - Set target frame for form display

fdf_set_encoding
fdf_set_flags
FDF Functions


Sets a flag of a field

fdf_set_file
fdf_set_javascript_action
FDF Functions
PHP Manual

fdf_set_flags

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_flags — Sets a flag of a field

Description

bool fdf_set_flags ( resource $fdf_document , string $fieldname , int $whichFlags , int $newFlags )

Sets certain flags of the given field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

whichFlags

newFlags

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_set_opt() - Sets an option of a field

fdf_set_file
fdf_set_javascript_action
FDF Functions


Sets an javascript action of a field

fdf_set_flags
fdf_set_on_import_javascript
FDF Functions
PHP Manual

fdf_set_javascript_action

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_javascript_action — Sets an javascript action of a field

Description

bool fdf_set_javascript_action ( resource $fdf_document , string $fieldname , int $trigger , string $script )

Sets a javascript action for the given field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

trigger

script

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_set_submit_form_action() - Sets a submit form action of a field

fdf_set_flags
fdf_set_on_import_javascript
FDF Functions


Adds javascript code to be executed when Acrobat opens the FDF

fdf_set_javascript_action
fdf_set_opt
FDF Functions
PHP Manual

fdf_set_on_import_javascript

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF

Description

bool fdf_set_on_import_javascript ( resource $fdf_document , string $script , bool $before_data_import )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • fdf_add_doc_javascript() - Adds javascript code to the FDF document
  • fdf_set_javascript_action() - Sets an javascript action of a field

fdf_set_javascript_action
fdf_set_opt
FDF Functions


Sets an option of a field

fdf_set_on_import_javascript
fdf_set_status
FDF Functions
PHP Manual

fdf_set_opt

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_opt — Sets an option of a field

Description

bool fdf_set_opt ( resource $fdf_document , string $fieldname , int $element , string $str1 , string $str2 )

Sets options of the given field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

element

str1

str2

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_set_flags() - Sets a flag of a field

fdf_set_on_import_javascript
fdf_set_status
FDF Functions


Set the value of the /STATUS key

fdf_set_opt
fdf_set_submit_form_action
FDF Functions
PHP Manual

fdf_set_status

(PHP 4, PHP 5)

fdf_set_status — Set the value of the /STATUS key

Description

bool fdf_set_status ( resource $fdf_document , string $status )

Sets the value of the /STATUS key. When a client receives a FDF with a status set it will present the value in an alert box.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

status

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_get_status() - Get the value of the /STATUS key

fdf_set_opt
fdf_set_submit_form_action
FDF Functions


Sets a submit form action of a field

fdf_set_status
fdf_set_target_frame
FDF Functions
PHP Manual

fdf_set_submit_form_action

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_submit_form_action — Sets a submit form action of a field

Description

bool fdf_set_submit_form_action ( resource $fdf_document , string $fieldname , int $trigger , string $script , int $flags )

Sets a submit form action for the given field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

trigger

script

flags

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_set_javascript_action() - Sets an javascript action of a field

fdf_set_status
fdf_set_target_frame
FDF Functions


Set target frame for form display

fdf_set_submit_form_action
fdf_set_value
FDF Functions
PHP Manual

fdf_set_target_frame

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_target_frame — Set target frame for form display

Description

bool fdf_set_target_frame ( resource $fdf_document , string $frame_name )

Sets the target frame to display a result PDF defined with fdf_save_file() in.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

frame_name

The frame name, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_save_file()

fdf_set_submit_form_action
fdf_set_value
FDF Functions


Set the value of a field

fdf_set_target_frame
fdf_set_version
FDF Functions
PHP Manual

fdf_set_value

(PHP 4, PHP 5)

fdf_set_value — Set the value of a field

Description

bool fdf_set_value ( resource $fdf_document , string $fieldname , mixed $value [, int $isName ] )

Sets the value for the given field.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

value

This parameter will be stored as a string unless it is an array. In this case all array elements will be stored as a value array.

isName

Note: In older versions of the FDF toolkit last parameter determined if the field value was to be converted to a PDF Name (= 1) or set to a PDF String (= 0).
The value is no longer used in the current toolkit version 5.0. For compatibility reasons it is still supported as an optional parameter beginning with PHP 4.3, but ignored internally.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
4.3.0 | Support for arrays in the value parameter was added.

See Also

  • fdf_get_value() - Get the value of a field
  • fdf_remove_item() - Sets target frame for form

fdf_set_target_frame
fdf_set_version
FDF Functions


Sets version number for a FDF file

fdf_set_value
GnuPG
FDF Functions
PHP Manual

fdf_set_version

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_version — Sets version number for a FDF file

Description

bool fdf_set_version ( resource $fdf_document , string $version )

Sets the FDF version for the given document.

Some features supported by this extension are only available in newer FDF versions.

Parameters

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

version

The version number. For the current FDF toolkit 5.0, this may be either 1.2, 1.3 or 1.4.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fdf_get_version() - Gets version number for FDF API or file

fdf_set_value
GnuPG
FDF Functions


Tests for end-of-file on a file pointer

fclose
fflush
Filesystem Functions
PHP Manual

feof

(PHP 4, PHP 5)

feof — Tests for end-of-file on a file pointer

Description

bool feof ( resource $handle )

Tests for end-of-file on a file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.

Notes

Warning

If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:

Example #1 Handling timeouts with feof()

<?php
function safe_feof($fp, &start = NULL) {
 $start = microtime(true);

 return feof($fp);
}

/* Assuming $fp is previously opened by fsockopen() */

$start = NULL;
$timeout = ini_get('default_socket_timeout');

while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout)
{
 /* Handle */
}
?>

Warning

If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return TRUE.

Example #2 feof() example with an invalid file pointer

<?php
// if file can not be read or doesn't exist fopen function returns FALSE
$file = @fopen("no_such_file", "r");

// FALSE from fopen will issue warning and result in infinite loop here
while (!feof($file)) {
}

fclose($file);
?>

fclose
fflush
Filesystem Functions


Flushes the output to a file

feof
fgetc
Filesystem Functions
PHP Manual

fflush

(PHP 4 >= 4.0.1, PHP 5)

fflush — Flushes the output to a file

Description

bool fflush ( resource $handle )

This function forces a write of all buffered output to the resource pointed to by the file handle .

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 File write example using fflush()

<?php
$filename = 'bar.txt';

$file = fopen($filename, 'r+');
rewind($file);
fwrite($file, 'Foo');
fflush($file);
ftruncate($file, ftell($file));
fclose($file);
?>

See Also

  • clearstatcache() - Clears file status cache
  • fwrite() - Binary-safe file write

feof
fgetc
Filesystem Functions


Gets character from file pointer

fflush
fgetcsv
Filesystem Functions
PHP Manual

fgetc

(PHP 4, PHP 5)

fgetc — Gets character from file pointer

Description

string fgetc ( resource $handle )

Gets a character from the given file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns a string containing a single character read from the file pointed to by handle . Returns FALSE on EOF.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 A fgetc() example

<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
    echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
    echo "$char\n";
}
?>

Notes

Note: This function is binary-safe.

See Also

  • fread() - Binary-safe file read
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection
  • fgets() - Gets line from file pointer

fflush
fgetcsv
Filesystem Functions


Gets line from file pointer and parse for CSV fields

fgetc
fgets
Filesystem Functions
PHP Manual

fgetcsv

(PHP 4, PHP 5)

fgetcsv — Gets line from file pointer and parse for CSV fields

Description

array fgetcsv ( resource $handle [, int $length [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '\\' ]]]] )

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

Parameters

handle

A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().

length

Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). It became optional in PHP 5. Omitting this parameter (or setting it to 0 in PHP 5.0.4 and later) the maximum line length is not limited, which is slightly slower.

delimiter

Set the field delimiter (one character only).

enclosure

Set the field enclosure character (one character only).

escape

Set the escape character (one character only). Defaults as a backslash.

Return Values

Returns an indexed array containing the fields read.

Note: A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.

Changelog

Version | Description
5.3.0 | The escape parameter was added
4.3.5 | fgetcsv() is now binary safe
4.3.0 | The enclosure parameter was added

Examples

Example #1 Read and print the entire contents of a CSV file

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

Notes

Note: Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.

See Also

  • str_getcsv() - Parse a CSV string into an array
  • explode() - Split a string by string
  • file() - Reads entire file into an array
  • pack() - Pack data into binary string
  • fputcsv() - Format line as CSV and write to file pointer

fgetc
fgets
Filesystem Functions


Gets line from file pointer

fgetcsv
fgetss
Filesystem Functions
PHP Manual

fgets

(PHP 4, PHP 5)

fgets — Gets line from file pointer

Description

string fgets ( resource $handle [, int $length ] )

Gets a line from file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

length

Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

Note: Until PHP 4.3.0, omitting it would assume 1024 as the line length. If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length.

Return Values

Returns a string of up to length - 1 bytes read from the file pointed to by handle .

If an error occurs, returns FALSE.

Changelog

Version | Description
4.3.0 | fgets() is now binary safe
4.2.0 | The length parameter became optional

Examples

Example #1 Reading a file line by line

<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?>

Notes

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

Note: People used to the 'C' semantics of fgets() should note the difference in how EOF is returned.

See Also

  • fgetss() - Gets line from file pointer and strip HTML tags
  • fread() - Binary-safe file read
  • fgetc() - Gets character from file pointer
  • stream_get_line() - Gets line from stream resource up to a given delimiter
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection
  • stream_set_timeout() - Set timeout period on a stream

fgetcsv
fgetss
Filesystem Functions


Gets line from file pointer and strip HTML tags

fgets
file_exists
Filesystem Functions
PHP Manual

fgetss

(PHP 4, PHP 5)

fgetss — Gets line from file pointer and strip HTML tags

Description

string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )

Identical to fgets(), except that fgetss() attempts to strip any HTML and PHP tags from the text it reads.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

length

Length of the data to be retrieved.

allowable_tags

You can use the optional third parameter to specify tags which should not be stripped.

Return Values

Returns a string of up to length - 1 bytes read from the file pointed to by handle , with all HTML and PHP code stripped.

If an error occurs, returns FALSE.

Changelog

Version | Description
5.0.0 | The length parameter is optional

Example #1 Reading a PHP file line-by-line

<?php
$str = <<<EOD
<html><body>
 <p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents('sample.php', $str);

$handle = @fopen("sample.php", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgetss($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?>

The above example will output something similar to:

 Welcome! Today is the  of .

Text outside of the HTML block.

Notes

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

See Also

  • fgets() - Gets line from file pointer
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection
  • strip_tags() - Strip HTML and PHP tags from a string

fgets
file_exists
Filesystem Functions


Reads entire file into an array

file_put_contents
fileatime
Filesystem Functions
PHP Manual

file

(PHP 4, PHP 5)

file — Reads entire file into an array

Description

array file ( string $filename [, int $flags = 0 [, resource $context ]] )

Reads an entire file into an array.

Note: You can use file_get_contents() to return the contents of a file as a string.

Parameters

filename

Path to the file.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

flags

The optional parameter flags can be one, or more, of the following constants:

FILE_USE_INCLUDE_PATH
Search for the file in the include_path.
FILE_IGNORE_NEW_LINES
Do not add newline at the end of each array element
FILE_SKIP_EMPTY_LINES
Skip empty lines
FILE_TEXT
The content is returned in UTF-8 encoding. You can specify a different encoding by creating a custom context. This flag cannot be used with FILE_BINARY.
FILE_BINARY
The content is read as binary data. This is the default setting and cannot be used with FILE_TEXT.

context

A context resource created with the stream_context_create() function.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Stream Functions.

Return Values

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

Note: Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

Changelog

Version | Description
6.0.0 Added support for the FILE_TEXT and FILE_BINARY flags.

Note: For forward compatibility, these constants are available as of PHP 5.2.7

5.0.0 | The context parameter was added
5.0.0 | Prior to PHP 5.0.0 the flags parameter only covered include_path and was enabled with 1
4.3.0 | file() became binary safe

Examples

Example #1 file() example

<?php
// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));

// Using the optional flags parameter since PHP 5
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

See Also

  • readfile() - Outputs a file
  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer
  • file_get_contents() - Reads entire file into a string
  • include() - include
  • stream_context_create() - Create a streams context

file_put_contents
fileatime
Filesystem Functions


Checks whether a file or directory exists

fgetss
file_get_contents
Filesystem Functions
PHP Manual

file_exists

(PHP 4, PHP 5)

file_exists — Checks whether a file or directory exists

Description

bool file_exists ( string $filename )

Checks whether a file or directory exists.

Parameters

filename

Path to the file or directory.

On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.

Return Values

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

Note: This function will return FALSE for symlinks pointing to non-existing files.

Warning

This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir.

Note: The check is done using the real UID/GID instead of the effective one.

Examples

Example #1 Testing whether a file exists

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • is_readable() - Tells whether a file exists and is readable
  • is_writable() - Tells whether the filename is writable
  • is_file() - Tells whether the filename is a regular file
  • file() - Reads entire file into an array

fgetss
file_get_contents
Filesystem Functions


Reads entire file into a string

file_exists
file_put_contents
Filesystem Functions
PHP Manual

file_get_contents

(PHP 4 >= 4.3.0, PHP 5)

file_get_contents — Reads entire file into a string

Description

string file_get_contents ( string $filename [, int $flags = 0 [, resource $context [, int $offset = -1 [, int $maxlen = -1 ]]]] )

This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE.

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

Note: If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().

Note: The default value of maxlen is not actually -1; rather, it is an internal PHP value which means to copy the entire stream until end-of-file is reached. The only way to specify this default value is to leave it out of the parameter list.

Parameters

filename

Name of the file to read.

flags

Note: Prior to PHP 6, this parameter is called use_include_path and is a bool. As of PHP 5 the FILE_USE_INCLUDE_PATH can be used to trigger include path search.

The value of flags can be any combination of the following flags (with some restrictions), joined with the binary OR (|) operator.

Available flags
Flag | Description
FILE_USE_INCLUDE_PATH | Search for filename in the include directory. See include_path for more information.
FILE_TEXT | As of PHP 6, the default encoding of the read data is UTF-8. You can specify a different encoding by creating a custom context or by changing the default using stream_default_encoding(). This flag cannot be used with FILE_BINARY.
FILE_BINARY | With this flag, the file is read in binary mode. This is the default setting and cannot be used with FILE_TEXT.

context

A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL.

offset

The offset where the reading starts.

maxlen

Maximum length of data read. The default is to read until end of file is reached.

Return Values

The function returns the read data or FALSE on failure.

Examples

Example #1 Get and output the source of the homepage of a website

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

Example #2 Searching within the include_path

<?php
// <= PHP 5
$file = file_get_contents('./people.txt', true);
// > PHP 5
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>

Example #3 Reading a section of a file

<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>

The above example will output something similar to:

string(14) "lle Bjori Ro"

Example #4 Using stream contexts

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>

Changelog

Version | Description
6.0.0 | The use_include_path parameter was replaced by the flags parameter.
5.1.0 | Added the offset and maxlen parameters.
5.0.0 | Added context support.

Notes

Note: This function is binary-safe.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

See Also

  • file() - Reads entire file into an array
  • fgets() - Gets line from file pointer
  • fread() - Binary-safe file read
  • readfile() - Outputs a file
  • file_put_contents() - Write a string to a file
  • stream_get_contents() - Reads remainder of a stream into a string
  • stream_context_create() - Create a streams context

file_exists
file_put_contents
Filesystem Functions


Write a string to a file

file_get_contents
file
Filesystem Functions
PHP Manual

file_put_contents

(PHP 5)

file_put_contents — Write a string to a file

Description

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flags is set.

Parameters

filename

Path to the file where to write the data.

data

The data to write. Can be either a string, an array or a stream resource.

If data is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

You can also specify the data parameter as a single dimension array. This is equivalent to file_put_contents($filename, implode('', $array)).

flags

The value of flags can be any combination of the following flags (with some restrictions), joined with the binary OR (|) operator.

Available flags
Flag | Description
FILE_USE_INCLUDE_PATH | Search for filename in the include directory. See include_path for more information.
FILE_APPEND | If file filename already exists, append the data to the file instead of overwriting it. Mutually exclusive with LOCK_EX since appends are atomic and thus there is no reason to lock.
LOCK_EX | Acquire an exclusive lock on the file while proceeding to the writing. Mutually exclusive with FILE_APPEND.
FILE_TEXT | data is written in text mode. If unicode semantics are enabled, the default encoding is UTF-8. You can specify a different encoding by creating a custom context or by using the stream_default_encoding() to change the default. This flag cannot be used with FILE_BINARY. This flag is only available since PHP 6.
FILE_BINARY | data will be written in binary mode. This is the default setting and cannot be used with FILE_TEXT. This flag is only available since PHP 6.

context

A valid context resource created with stream_context_create().

Return Values

The function returns the number of bytes that were written to the file, or FALSE on failure.

Examples

Example #1 Simple usage example

<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>

Example #2 Using flags

<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Append the contents of $person to the file named by $file.
file_put_contents($file, $person, FILE_APPEND);
?>

Changelog

Version | Description
5.0.0 | Added context support
5.1.0 | Added support for LOCK_EX and the ability to pass a stream resource to the data parameter
6.0.0 | Added support for the FILE_TEXT and FILE_BINARY flags

Notes

Note: This function is binary-safe.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

See Also

  • fopen() - Opens file or URL
  • fwrite() - Binary-safe file write
  • file_get_contents() - Reads entire file into a string
  • stream_context_create() - Create a streams context

file_get_contents
file
Filesystem Functions


Gets last access time of file

file
filectime
Filesystem Functions
PHP Manual

fileatime

(PHP 4, PHP 5)

fileatime — Gets last access time of file

Description

int fileatime ( string $filename )

Gets the last access time of the given file.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last accessed, or FALSE on failure. The time is returned as a Unix timestamp.

Examples

Example #1 fileatime() example

<?php

// outputs e.g.  somefile.txt was last accessed: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last accessed: " . date("F d Y H:i:s.", fileatime($filename));
}

?>

Notes

Note: The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performance-wise when an application regularly accesses a very large number of files or directories.
Some Unix filesystems can be mounted with atime updates disabled to increase the performance of such applications; USENET news spools are a common example. On such filesystems this function will be useless.

Note: Note that time resolution may differ from one file system to another.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • filemtime() - Gets file modification time
  • fileinode() - Gets file inode
  • date() - Format a local time/date

file
filectime
Filesystem Functions


Gets inode change time of file

fileatime
filegroup
Filesystem Functions
PHP Manual

filectime

(PHP 4, PHP 5)

filectime — Gets inode change time of file

Description

int filectime ( string $filename )

Gets the inode change time of a file.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last changed, or FALSE on failure. The time is returned as a Unix timestamp.

Examples

Example #1 A filectime() example

<?php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last changed: " . date("F d Y H:i:s.", filectime($filename));
}

?>

Notes

Note: Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().

Note: Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

Note: Note that time resolution may differ from one file system to another.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • filemtime() - Gets file modification time

fileatime
filegroup
Filesystem Functions


Gets file group

filectime
fileinode
Filesystem Functions
PHP Manual

filegroup

(PHP 4, PHP 5)

filegroup — Gets file group

Description

int filegroup ( string $filename )

Gets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.

Parameters

filename

Path to the file.

Return Values

Returns the group ID of the file, or FALSE in case of an error. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. Upon failure, FALSE is returned.

Examples

Example #1 Finding the group of a file

<?php
$filename = 'index.php';
print_r(posix_getgrgid(filegroup($filename)));
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • fileowner() - Gets file owner
  • posix_getgrgid() - Return info about a group by group id
  • safe_mode_gid

filectime
fileinode
Filesystem Functions


Gets file inode

filegroup
filemtime
Filesystem Functions
PHP Manual

fileinode

(PHP 4, PHP 5)

fileinode — Gets file inode

Description

int fileinode ( string $filename )

Gets the file inode.

Parameters

filename

Path to the file.

Return Values

Returns the inode number of the file, or FALSE on failure.

Examples

Example #1 Comparing the inode of a file with the current file

<?php
$filename = 'index.php';
if (getmyinode() == fileinode($filename)) {
    echo 'You are checking the current file.';
}
?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • getmyinode() - Gets the inode of the current script
  • stat() - Gives information about a file

filegroup
filemtime
Filesystem Functions


Gets file modification time

fileinode
fileowner
Filesystem Functions
PHP Manual

filemtime

(PHP 4, PHP 5)

filemtime — Gets file modification time

Description

int filemtime ( string $filename )

This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last modified, or FALSE on failure. The time is returned as a Unix timestamp, which is suitable for the date() function.

Examples

Example #1 filemtime() example

<?php
// outputs e.g.  somefile.txt was last modified: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>

Notes

Note: Note that time resolution may differ from one file system to another.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • filectime() - Gets inode change time of file
  • stat() - Gives information about a file
  • touch() - Sets access and modification time of file
  • getlastmod() - Gets time of last page modification

fileinode
fileowner
Filesystem Functions


Gets file owner

filemtime
fileperms
Filesystem Functions
PHP Manual

fileowner

(PHP 4, PHP 5)

fileowner — Gets file owner

Description

int fileowner ( string $filename )

Gets the file owner.

Parameters

filename

Path to the file.

Return Values

Returns the user ID of the owner of the file, or FALSE on failure. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username.

Examples

Example #1 Finding the owner of a file

<?php
$filename = 'index.php';
print_r(posix_getpwuid(fileowner($filename)));
?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • posix_getpwuid() - Return info about a user by user id

filemtime
fileperms
Filesystem Functions


Gets file permissions

fileowner
filesize
Filesystem Functions
PHP Manual

fileperms

(PHP 4, PHP 5)

fileperms — Gets file permissions

Description

int fileperms ( string $filename )

Gets permissions for the given file.

Parameters

filename

Path to the file.

Return Values

Returns the permissions on the file, or FALSE on failure.

Examples

Example #1 Display permissions as an octal value

<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>

The above example will output:

1777
0644

Example #2 Display full permissions

<?php
$perms = fileperms('/etc/passwd');

if (($perms & 0xC000) == 0xC000) {
    // Socket
    $info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
    // Symbolic Link
    $info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
    // Regular
    $info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
    // Block special
    $info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
    // Directory
    $info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
    // Character special
    $info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
    // FIFO pipe
    $info = 'p';
} else {
    // Unknown
    $info = 'u';
}

// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
            (($perms & 0x0800) ? 's' : 'x' ) :
            (($perms & 0x0800) ? 'S' : '-'));

// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
            (($perms & 0x0400) ? 's' : 'x' ) :
            (($perms & 0x0400) ? 'S' : '-'));

// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
            (($perms & 0x0200) ? 't' : 'x' ) :
            (($perms & 0x0200) ? 'T' : '-'));

echo $info;
?>

The above example will output:

-rw-r--r--

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • chmod() - Changes file mode
  • is_readable() - Tells whether a file exists and is readable
  • stat() - Gives information about a file

fileowner
filesize
Filesystem Functions


Read and verify the map file

filepro_rowcount
Firebird/InterBase
filePro Functions
PHP Manual

filepro

(PHP 4, PHP 5 <= 5.1.6)

filepro — Read and verify the map file

Description

bool filepro ( string $directory )

This reads and verifies the map file, storing the field count and info.

No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Parameters

directory

The map directory.

Return Values

Returns TRUE on success or FALSE on failure.

filepro_rowcount
Firebird/InterBase
filePro Functions


Find out how many fields are in a filePro database

filePro Functions
filepro_fieldname
filePro Functions
PHP Manual

filepro_fieldcount

(PHP 4, PHP 5 <= 5.1.6)

filepro_fieldcount — Find out how many fields are in a filePro database

Description

int filepro_fieldcount ( void )

Returns the number of fields (columns) in the opened filePro database.

Return Values

Returns the number of fields in the opened filePro database, or FALSE on errors.

See Also

  • filepro() - Read and verify the map file

filePro Functions
filepro_fieldname
filePro Functions


Gets the name of a field

filepro_fieldcount
filepro_fieldtype
filePro Functions
PHP Manual

filepro_fieldname

(PHP 4, PHP 5 <= 5.1.6)

filepro_fieldname — Gets the name of a field

Description

string filepro_fieldname ( int $field_number )

Returns the name of the field corresponding to field_number .

Parameters

field_number

The field number.

Return Values

Returns the name of the field as a string, or FALSE on errors.

filepro_fieldcount
filepro_fieldtype
filePro Functions


Gets the type of a field

filepro_fieldname
filepro_fieldwidth
filePro Functions
PHP Manual

filepro_fieldtype

(PHP 4, PHP 5 <= 5.1.6)

filepro_fieldtype — Gets the type of a field

Description

string filepro_fieldtype ( int $field_number )

Returns the edit type of the field corresponding to field_number .

Parameters

field_number

The field number.

Return Values

Returns the edit type of the field as a string, or FALSE on errors.

filepro_fieldname
filepro_fieldwidth
filePro Functions


Gets the width of a field

filepro_fieldtype
filepro_retrieve
filePro Functions
PHP Manual

filepro_fieldwidth

(PHP 4, PHP 5 <= 5.1.6)

filepro_fieldwidth — Gets the width of a field

Description

int filepro_fieldwidth ( int $field_number )

Returns the width of the field corresponding to field_number .

Parameters

field_number

The field number.

Return Values

Returns the width of the field as a integer, or FALSE on errors.

filepro_fieldtype
filepro_retrieve
filePro Functions


Retrieves data from a filePro database

filepro_fieldwidth
filepro_rowcount
filePro Functions
PHP Manual

filepro_retrieve

(PHP 4, PHP 5 <= 5.1.6)

filepro_retrieve — Retrieves data from a filePro database

Description

string filepro_retrieve ( int $row_number , int $field_number )

Returns the data from the specified location in the database.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Parameters

row_number

The row number. Must be between zero and the total number of rows minus one (0..filepro_rowcount() - 1)

field_number

The field number. Accepts values between zero and the total number of fields minus one (0..filepro_fieldcount() - 1)

Return Values

Returns the specified data, or FALSE on errors.

filepro_fieldwidth
filepro_rowcount
filePro Functions


Find out how many rows are in a filePro database

filepro_retrieve
filepro
filePro Functions
PHP Manual

filepro_rowcount

(PHP 4, PHP 5 <= 5.1.6)

filepro_rowcount — Find out how many rows are in a filePro database

Description

int filepro_rowcount ( void )

Returns the number of rows in the opened filePro database.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Return Values

Returns the number of rows in the opened filePro database, or FALSE on errors.

See Also

  • filepro() - Read and verify the map file

filepro_retrieve
filepro
filePro Functions


Gets file size

fileperms
filetype
Filesystem Functions
PHP Manual

filesize

(PHP 4, PHP 5)

filesize — Gets file size

Description

int filesize ( string $filename )

Gets the size for the given file.

Parameters

filename

Path to the file.

Return Values

Returns the size of the file in bytes, or FALSE (and generates an error of level E_WARNING) in case of an error.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, filesize() may return unexpected results for files which are larger than 2GB. For files between 2GB and 4GB in size this can usually be overcome by using sprintf("%u", filesize($file)).

Examples

Example #1 filesize() example

<?php

// outputs e.g.  somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • file_exists() - Checks whether a file or directory exists

fileperms
filetype
Filesystem Functions


Gets file type

filesize
flock
Filesystem Functions
PHP Manual

filetype

(PHP 4, PHP 5)

filetype — Gets file type

Description

string filetype ( string $filename )

Returns the type of the given file.

Parameters

filename

Path to the file.

Return Values

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, socket and unknown.

Returns FALSE if an error occurs. filetype() will also produce an E_NOTICE message if the stat call fails or if the file type is unknown.

Examples

Example #1 filetype() example

<?php

echo filetype('/etc/passwd');  // file
echo filetype('/etc/');        // dir

?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • is_dir() - Tells whether the filename is a directory
  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link
  • file_exists() - Checks whether a file or directory exists
  • stat() - Gives information about a file
  • mime_content_type() - Detect MIME Content-type for a file (deprecated)

filesize
flock
Filesystem Functions


Return information about a string buffer

Fileinfo Functions
finfo_close
Fileinfo Functions
PHP Manual

finfo_buffer

(PHP 5 >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_buffer — Return information about a string buffer

Description

string finfo_buffer ( resource $finfo , string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )
finfo
string buffer ( string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

This function is used to get information about binary data in a string.

Parameters

finfo

Fileinfo resource returned by finfo_open().

string

Content of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

Return Values

Returns a textual description of the string argument, or FALSE if an error occurred.

Examples

Example #1 A finfo_buffer() example

<?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer($_POST["script"]) . "\n";
?>

The above example will output something similar to:

application/x-sh; charset=us-ascii

See Also

  • finfo_file() - Return information about a file

Fileinfo Functions
finfo_close
Fileinfo Functions


Close fileinfo resource

finfo_buffer
finfo_file
Fileinfo Functions
PHP Manual

finfo_close

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_close — Close fileinfo resource

Description

bool finfo_close ( resource $finfo )
finfo
__destruct ( void )

This function closes the resource opened by finfo_open().

Parameters

finfo

Fileinfo resource returned by finfo_open().

Return Values

Returns TRUE on success or FALSE on failure.

finfo_buffer
finfo_file
Fileinfo Functions


Return information about a file

finfo_close
finfo_open
Fileinfo Functions
PHP Manual

finfo_file

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_file — Return information about a file

Description

string finfo_file ( resource $finfo , string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )
finfo
string file ( string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

This function is used to get information about a file.

Parameters

finfo

Fileinfo resource returned by finfo_open().

file_name

Name of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

For a description of contexts, refer to Stream Functions.

Return Values

Returns a textual description of the contents of the filename argument, or FALSE if an error occurred.

Examples

Example #1 A finfo_file() example

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>

The above example will output something similar to:

text/html
image/gif
application/vnd.ms-excel

See Also

  • finfo_buffer() - Return information about a string buffer

finfo_close
finfo_open
Fileinfo Functions


Create a new fileinfo resource

finfo_file
finfo_set_flags
Fileinfo Functions
PHP Manual

finfo_open

finfo->__construct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_open -- finfo->__construct — Create a new fileinfo resource

Description

Procedural style

resource finfo_open ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

Object oriented style (constructor):

finfo
__construct ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

This function opens a magic database and returns its resource.

Parameters

options

One or disjunction of more Fileinfo constants.

magic_file

Name of a magic database file, usually something like /path/to/magic.mime. If not specified, the MAGIC environment variable is used. If this variable is not set either, /usr/share/misc/magic is used by default. A .mime and/or .mgc suffix is added if needed.

Return Values

Returns a magic database resource on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>

Example #2 Procedural style

<?php
$finfo = finfo_open(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo finfo_file($finfo, $filename);

/* close connection */
finfo_close($finfo);
?>

The above example will output:

text/plain; charset=us-ascii

See Also

  • finfo_close() - Close fileinfo resource

finfo_file
finfo_set_flags
Fileinfo Functions


Set libmagic configuration options

finfo_open
mime_content_type
Fileinfo Functions
PHP Manual

finfo_set_flags

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_set_flags — Set libmagic configuration options

Description

bool finfo_set_flags ( resource $finfo , int $options )
finfo
bool set_flags ( int $options )

This function sets various Fileinfo options. Options can be set also directly in finfo_open() or other Fileinfo functions.

Parameters

finfo

Fileinfo resource returned by finfo_open().

options

One or disjunction of more Fileinfo constants.

Return Values

Returns TRUE on success or FALSE on failure.

finfo_open
mime_content_type
Fileinfo Functions


Portable advisory file locking

filetype
fnmatch
Filesystem Functions
PHP Manual

flock

(PHP 4, PHP 5)

flock — Portable advisory file locking

Description

bool flock ( resource $handle , int $operation [, int &$wouldblock ] )

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows).

The lock is released also by fclose() (which is also called automatically when script finished).

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). By default, this function will block until the requested lock is acquired; this may be controlled (on non-Windows platforms) with the LOCK_NB option documented below.

Parameters

handle

An open file pointer.

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).

It is also possible to add LOCK_NB as a bitmask to one of the above operations if you don't want flock() to block while locking. (not supported on Windows)

wouldblock

The optional third argument is set to TRUE if the lock would block (EWOULDBLOCK errno condition). (not supported on Windows)

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
4.0.1 | The LOCK_XXX constants were added. Prior to that you must use 1 for LOCK_SH, 2 for LOCK_EX, 3 for LOCK_UN and 4 for LOCK_NB

Examples

Example #1 flock() example

<?php

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) { // do an exclusive lock
    ftruncate($fp, 0); // truncate file
    fwrite($fp, "Write something here\n");
    flock($fp, LOCK_UN); // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

?>

Example #2 flock() using the LOCK_NB option

<?php
$fp = fopen('/tmp/lock.txt', 'r+');

/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fp, LOCK_EX | LOCK_NB)) {
    echo 'Unable to obtain lock';
    exit(-1);
}

/* ... */

fclose($fp);
?>

Notes

Note: flock() locks mandatory under Windows aswell as some POSIX based operating systems.

Note: Because flock() requires a file pointer, you may have to use a special lock file to protect access to a file that you intend to truncate by opening it in write mode (with a "w" or "w+" argument to fopen()).

Note: POSIX.1 compatible systems will release the scripts flock()'s on a file, if the scripts uses fclose() on any file handle on that file.

Warning

Assigning other value to handle argument in the consecutive code would release the lock.

Warning

On some operating systems flock() is implemented at the process level. When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!

flock() is not supported on antiquated filesystems like FAT and its derivates and will therefore always return FALSE under this environments (this is especially true for Windows 98 users).

filetype
fnmatch
Filesystem Functions


Round fractions down

expm1
fmod
Math Functions
PHP Manual

floor

(PHP 4, PHP 5)

floor — Round fractions down

Description

float floor ( float $value )

Returns the next lowest integer value by rounding down value if necessary.

Parameters

value

The numeric value to round

Return Values

value rounded to the next lowest integer. The return value of floor() is still of type float because the value range of float is usually bigger than that of integer.

Examples

Example #1 floor() example

<?php
echo floor(4.3);   // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>

See Also

  • ceil() - Round fractions up
  • round() - Rounds a float

expm1
fmod
Math Functions


Flush the output buffer

Output Control Functions
ob_clean
Output Control Functions
PHP Manual

flush

(PHP 4, PHP 5)

flush — Flush the output buffer

Description

void flush ( void )

Flushes the write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats.

flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.

Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.

Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.

Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.

Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.

Return Values

No value is returned.

Output Control Functions
ob_clean
Output Control Functions


Returns the floating point remainder (modulo) of the division of the arguments

floor
getrandmax
Math Functions
PHP Manual

fmod

(PHP 4 >= 4.2.0, PHP 5)

fmod — Returns the floating point remainder (modulo) of the division of the arguments

Description

float fmod ( float $x , float $y )

Returns the floating point remainder of dividing the dividend (x ) by the divisor (y ). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y .

Parameters

x

The dividend

y

The divisor

Return Values

The floating point remainder of x /y

Examples

Example #1 Using fmod()

<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?>

floor
getrandmax
Math Functions


Match filename against a pattern

flock
fopen
Filesystem Functions
PHP Manual

fnmatch

(PHP 4 >= 4.3.0, PHP 5)

fnmatch — Match filename against a pattern

Description

bool fnmatch ( string $pattern , string $string [, int $flags = 0 ] )

fnmatch() checks if the passed string would match the given shell wildcard pattern .

Parameters

pattern

The shell wildcard pattern.

string

The tested string. This function is especially useful for filenames, but may also be used on regular strings.

The average user may be used to shell patterns or at least in their simplest form to '?' and '*' wildcards so using fnmatch() instead of preg_match() for frontend search expression input may be way more convenient for non-programming users.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

A list of possible flags for fnmatch()
Flag | Description
FNM_NOESCAPE | Disable backslash escaping.
FNM_PATHNAME | Slash in string only matches slash in the given pattern.
FNM_PERIOD | Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD | Caseless match. Part of the GNU extension.

Return Values

Returns TRUE if there is a match, FALSE otherwise.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Examples

Example #1 Checking a color name against a shell wildcard pattern

<?php
if (fnmatch("*gr[ae]y", $color)) {
  echo "some form of gray ...";
}
?>

Notes

Warning

For now this function is not available on non-POSIX compliant systems.

See Also

  • glob() - Find pathnames matching a pattern
  • preg_match() - Perform a regular expression match
  • sscanf() - Parses input from a string according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string

flock
fopen
Filesystem Functions


Opens file or URL

fnmatch
fpassthru
Filesystem Functions
PHP Manual

fopen

(PHP 4, PHP 5)

fopen — Opens file or URL

Description

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

fopen() binds a named resource, specified by filename , to a stream.

Parameters

filename

If filename is of the form "scheme://...", it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled safe mode, or open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Note: The list of supported protocols can be found in List of Supported Protocols/Wrappers. Some protocols (also referred to as wrappers) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

<?php
$handle = fopen("c:\\data\\info.txt", "r");
?>

mode

The mode parameter specifies the type of access you require to the stream. It may be any of the following:

A list of possible modes for fopen() using mode
mode | Description
'r' | Open for reading only; place the file pointer at the beginning of the file.
'r+' | Open for reading and writing; place the file pointer at the beginning of the file.
'w' | Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' | Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' | Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' | Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'x' | Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
'x+' | Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.

Note: Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems use \r as the line ending character.
If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will "look funny".
Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.
The default translation mode depends on the SAPI and version of PHP that you are using, so you are encouraged to always specify the appropriate flag for portability reasons. You should use the 't' mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as notepad. You should use the 'b' in all other cases.
If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

Note: For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen().

Note: Again, for portability, it is also strongly recommended that you re-write code that uses or relies upon the 't' mode so that it uses the correct line endings and 'b' mode instead.

use_include_path

The optional third use_include_path parameter can be set to '1' or TRUE if you want to search for the file in the include_path, too.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Stream Functions.

Return Values

Returns a file pointer resource on success, or FALSE on error.

Errors/Exceptions

If the open fails, an error of level E_WARNING is generated. You may use @ to suppress this warning.

Changelog

Version | Description
4.3.2 | As of PHP 4.3.2, the default mode is set to binary for all platforms that distinguish between binary and text mode. If you are having problems with your scripts after upgrading, try using the 't' flag as a workaround until you have made your script more portable as mentioned before
4.3.2 | The 'x' and 'x+' option was added

Examples

Example #1 fopen() examples

<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.

See Also

  • List of Supported Protocols/Wrappers
  • fclose() - Closes an open file pointer
  • fgets() - Gets line from file pointer
  • fread() - Binary-safe file read
  • fwrite() - Binary-safe file write
  • fsockopen() - Open Internet or Unix domain socket connection
  • file() - Reads entire file into an array
  • file_exists() - Checks whether a file or directory exists
  • is_readable() - Tells whether a file exists and is readable
  • stream_set_timeout() - Set timeout period on a stream
  • popen() - Opens process file pointer
  • stream_context_create() - Create a streams context

fnmatch
fpassthru
Filesystem Functions


Output all remaining data on a file pointer

fopen
fputcsv
Filesystem Functions
PHP Manual

fpassthru

(PHP 4, PHP 5)

fpassthru — Output all remaining data on a file pointer

Description

int fpassthru ( resource $handle )

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readfile(), which saves you the fopen() call.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru() returns the number of characters read from handle and passed through to the output.

Examples

Example #1 Using fpassthru() with binary files

<?php

// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;

?>

Notes

Note: When using fpassthru() on a binary file on Windows systems, you should make sure to open the file in binary mode by appending a b to the mode used in the call to fopen().
You are encouraged to use the b flag when dealing with binary files, even if your system does not require it, so that your scripts will be more portable.

See Also

  • readfile() - Outputs a file
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection

fopen
fputcsv
Filesystem Functions


Format line as CSV and write to file pointer

fpassthru
fputs
Filesystem Functions
PHP Manual

fputcsv

(PHP 5 >= 5.1.0)

fputcsv — Format line as CSV and write to file pointer

Description

int fputcsv ( resource $handle , array $fields [, string $delimiter = ',' [, string $enclosure = '"' ]] )

fputcsv() formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle .

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

fields

An array of values.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure (one character only).

Return Values

Returns the length of the written string or FALSE on failure.

Examples

Example #1 fputcsv() example

<?php

$list = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"'
);

$fp = fopen('file.csv', 'w');

foreach ($list as $line) {
    fputcsv($fp, split(',', $line));
}

fclose($fp);
?>

Notes

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

See Also

  • fgetcsv() - Gets line from file pointer and parse for CSV fields

fpassthru
fputs
Filesystem Functions


Alias of fwrite

fputcsv
fread
Filesystem Functions
PHP Manual

fputs

(PHP 4, PHP 5)

fputs — Alias of fwrite()

Description

This function is an alias of: fwrite().

fputcsv
fread
Filesystem Functions


Binary-safe file read

fputs
fscanf
Filesystem Functions
PHP Manual

fread

(PHP 4, PHP 5)

fread — Binary-safe file read

Description

string fread ( resource $handle , int $length )

fread() reads up to length bytes from the file pointer referenced by handle . Reading stops as soon as one of the following conditions is met:

  • length bytes have been read
  • EOF (end of file) is reached
  • a packet becomes available (for network streams)
  • 8192 bytes have been read (after opening userspace stream)

Parameters

handle

A file system pointer resource that is typically created using fopen().

length

Up to length number of bytes read.

Return Values

Returns the read string or FALSE on failure.

Examples

Example #1 A simple fread() example

<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #2 Binary fread() example

Warning

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #3 Remote fread() examples

Warning

When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below.

<?php
// For PHP 5 and up
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle = fopen("http://www.example.com/", "rb");
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
?>

Notes

Note: If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above.

Note: Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.

See Also

  • fwrite() - Binary-safe file write
  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fscanf() - Parses input from a file according to a format
  • file() - Reads entire file into an array
  • fpassthru() - Output all remaining data on a file pointer
  • ftell() - Returns the current position of the file read/write pointer
  • rewind() - Rewind the position of a file pointer

fputs
fscanf
Filesystem Functions


Converts a date from the French Republican Calendar to a Julian Day Count

easter_days
GregorianToJD
Calendar Functions
PHP Manual

FrenchToJD

(PHP 4, PHP 5)

FrenchToJD — Converts a date from the French Republican Calendar to a Julian Day Count

Description

int frenchtojd ( int $month , int $day , int $year )

Converts a date from the French Republican Calendar to a Julian Day Count.

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

Parameters

month

The month as a number from 1 (for Vendémiaire) to 13 (for the period of 5-6 days at the end of each year)

day

The day as a number from 1 to 30

year

The year as a number between 1 and 14

Return Values

The julian day for the given french revolution date as an integer.

See Also

  • jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count

easter_days
GregorianToJD
Calendar Functions


Convert a logical string to a visual one

FriBiDi Functions
Gettext
FriBiDi Functions
PHP Manual

fribidi_log2vis

(PHP 4 >= 4.0.4 and PHP 4 <= 4.1.0, PECL fribidi >= 1.0)

fribidi_log2vis — Convert a logical string to a visual one

Description

string fribidi_log2vis ( string $str , string $direction , int $charset )

Converts a logical string to a visual one.

Parameters

str

The logical string.

direction

One of FRIBIDI_RTL, FRIBIDI_LTR or FRIBIDI_AUTO.

charset

One of the FRIBIDI_CHARSET_XXX constants.

Return Values

Returns the visual string on success or FALSE on failure.

FriBiDi Functions
Gettext
FriBiDi Functions


Parses input from a file according to a format

fread
fseek
Filesystem Functions
PHP Manual

fscanf

(PHP 4 >= 4.0.1, PHP 5)

fscanf — Parses input from a file according to a format

Description

mixed fscanf ( resource $handle , string $format [, mixed &$... ] )

The function fscanf() is similar to sscanf(), but it takes its input from a file associated with handle and interprets the input according to the specified format , which is described in the documentation for sprintf().

Any whitespace in the format string matches any whitespace in the input stream. This means that even a tab \t in the format string can match a single space character in the input stream.

Each call to fscanf() reads one line from the file.

Parameters

handle

A file system pointer resource that is typically created using fopen().

format

The specified format as described in the sprintf() documentation.

...

The optional assigned values.

Return Values

If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Changelog

Version | Description
4.3.0 | Before this time, the maximum number of characters read from the file was 512 (or up to the first \n, whichever came first). But now, arbitrarily long lines will be read and scanned.

Examples

Example #1 fscanf() Example

<?php
$handle = fopen("users.txt", "r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
    list ($name, $profession, $countrycode) = $userinfo;
    //... do something with the values
}
fclose($handle);
?>

Example #2 Contents of users.txt

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

See Also

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • sscanf() - Parses input from a string according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string

fread
fseek
Filesystem Functions


Seeks on a file pointer

fscanf
fstat
Filesystem Functions
PHP Manual

fseek

(PHP 4, PHP 5)

fseek — Seeks on a file pointer

Description

int fseek ( resource $handle , int $offset [, int $whence ] )

Sets the file position indicator for the file referenced by handle . The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence .

Parameters

handle

A file system pointer resource that is typically created using fopen().

offset

The offset.

To move to a position before the end-of-file, you need to pass a negative value in offset and set whence to SEEK_END.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset .
  • SEEK_END - Set position to end-of-file plus offset .

If whence is not specified, it is assumed to be SEEK_SET.

Return Values

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

Examples

Example #1 fseek() example

<?php

$fp = fopen('somefile.txt', 'r');

// read some data
$data = fgets($fp, 4096);

// move back to the beginning of the file
// same as rewind($fp);
fseek($fp, 0);

?>

Notes

Note: If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.

Note: May not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats. fseek() gives also undefined results for append-only streams (opened with "a" flag).

See Also

  • ftell() - Returns the current position of the file read/write pointer
  • rewind() - Rewind the position of a file pointer

fscanf
fstat
Filesystem Functions


Gets information about a file using an open file pointer

fseek
ftell
Filesystem Functions
PHP Manual

fstat

(PHP 4, PHP 5)

fstat — Gets information about a file using an open file pointer

Description

array fstat ( resource $handle )

Gathers the statistics of the file opened by the file pointer handle . This function is similar to the stat() function except that it operates on an open file pointer instead of a filename.

Parameters

handle

A file system pointer resource that is typically created using fopen().

Return Values

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

Examples

Example #1 fstat() example

<?php

// open a file
$fp = fopen("/etc/passwd", "r");

// gather statistics
$fstat = fstat($fp);

// close the file
fclose($fp);

// print only the associative part
print_r(array_slice($fstat, 13));

?>

The above example will output something similar to:

Array
(
    [dev] => 771
    [ino] => 488704
    [mode] => 33188
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 1114
    [atime] => 1061067181
    [mtime] => 1056136526
    [ctime] => 1056136526
    [blksize] => 4096
    [blocks] => 8
)

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

fseek
ftell
Filesystem Functions


Returns the current position of the file read/write pointer

fstat
ftruncate
Filesystem Functions
PHP Manual

ftell

(PHP 4, PHP 5)

ftell — Returns the current position of the file read/write pointer

Description

int ftell ( resource $handle )

Returns the position of the file pointer referenced by handle .

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen(). ftell() gives undefined results for append-only streams (opened with "a" flag).

Return Values

Returns the position of the file pointer referenced by handle as an integer; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

Examples

Example #1 ftell() example

<?php

// opens a file and read some data
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);

// where are we ?
echo ftell($fp); // 11

fclose($fp);

?>

See Also

  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fseek() - Seeks on a file pointer
  • rewind() - Rewind the position of a file pointer

fstat
ftruncate
Filesystem Functions


Convert a pathname and a project identifier to a System V IPC key

Semaphore Functions
msg_get_queue
Semaphore Functions
PHP Manual

ftok

(PHP 4 >= 4.2.0, PHP 5)

ftok — Convert a pathname and a project identifier to a System V IPC key

Description

int ftok ( string $pathname , string $proj )

The function converts the pathname of an existing accessible file and a project identifier into an integer for use with for example shmop_open() and other System V IPC keys.

Parameters

pathname

Path to an accessible file.

proj

Project identifier. This must be a one character string.

Return Values

On success the return value will be the created key value, otherwise -1 is returned.

See Also

  • shmop_open() - Create or open shared memory block
  • sem_get() - Get a semaphore id

Semaphore Functions
msg_get_queue
Semaphore Functions


Truncates a file to a given length

ftell
fwrite
Filesystem Functions
PHP Manual

ftruncate

(PHP 4, PHP 5)

ftruncate — Truncates a file to a given length

Description

bool ftruncate ( resource $handle , int $size )

Takes the filepointer, handle , and truncates the file to length, size .

Parameters

handle

The file pointer.

Note: The handle must be open for writing.

size

The size to truncate to.

Note: If size is larger than the file it is extended with null bytes.
If size is smaller than the extra data will be lost.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
PHP 4.3.3 | Prior to this release ftruncate() returned an integer value of 1 on success, instead of boolean TRUE.

Examples

Example #1 File truncation example

<?php
$filename = 'lorem_ipsum.txt';

$handle = fopen($filename, 'r+');
ftruncate($handle, rand(1, filesize($filename)));
rewind($handle);
echo fread($handle, filesize($filename));
fclose($handle);
?>

Notes

Note: The file pointer is not changed.

See Also

  • fopen() - Opens file or URL
  • fseek() - Seeks on a file pointer

ftell
fwrite
Filesystem Functions


Binary-safe file write

ftruncate
glob
Filesystem Functions
PHP Manual

fwrite

(PHP 4, PHP 5)

fwrite — Binary-safe file write

Description

int fwrite ( resource $handle , string $string [, int $length ] )

fwrite() writes the contents of string to the file stream pointed to by handle .

Parameters

handle

A file system pointer resource that is typically created using fopen().

string

The string that is to be written.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string .

Return Values

fwrite() returns the number of bytes written, or FALSE on error.

Notes

Note: Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

<?php
function fwrite_stream($fp, $string) {
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
        $fwrite = fwrite($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}
?>

Note: On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

Note: If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.

Note: If writing twice to the file pointer, then the data will be appended to the end of the file content:

<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);

// the content of 'data.txt' is now 123 and not 23!
?>

Examples

Example #1 A simple fwrite() example

<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>

See Also

  • fread() - Binary-safe file read
  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer
  • file_get_contents() - Reads entire file into a string

ftruncate
glob
Filesystem Functions


Forces collection of any existing garbage cycles

extension_loaded
gc_disable
PHP Options/Info Functions
PHP Manual

gc_collect_cycles

(PHP 5 >= 5.3.0)

gc_collect_cycles — Forces collection of any existing garbage cycles

Description

int gc_collect_cycles ( void )
Warning

This function is currently not documented; only its argument list is available.

Forces collection of any existing garbage cycles.

Parameters

This function has no parameters.

Return Values

Returns number of collected cycles.

extension_loaded
gc_disable
PHP Options/Info Functions


Deactivates the circular reference collector

gc_collect_cycles
gc_enable
PHP Options/Info Functions
PHP Manual

gc_disable

(PHP 5 >= 5.3.0)

gc_disable — Deactivates the circular reference collector

Description

void gc_disable ( void )
Warning

This function is currently not documented; only its argument list is available.

Deactivates the circular reference collector.

Parameters

This function has no parameters.

Return Values

No value is returned.

gc_collect_cycles
gc_enable
PHP Options/Info Functions


Activates the circular reference collector

gc_disable
gc_enabled
PHP Options/Info Functions
PHP Manual

gc_enable

(PHP 5 >= 5.3.0)

gc_enable — Activates the circular reference collector

Description

void gc_enable ( void )
Warning

This function is currently not documented; only its argument list is available.

Activates the circular reference collector.

Parameters

This function has no parameters.

Return Values

No value is returned.

gc_disable
gc_enabled
PHP Options/Info Functions


Returns status of the circular reference collector

gc_enable
get_cfg_var
PHP Options/Info Functions
PHP Manual

gc_enabled

(PHP 5 >= 5.3.0)

gc_enabled — Returns status of the circular reference collector

Description

bool gc_enabled ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns status of the circular reference collector.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the garbage collector is enabled, FALSE otherwise.

gc_enable
get_cfg_var
PHP Options/Info Functions


Retrieve information about the currently installed GD library

GD and Image Functions
getimagesize
GD and Image Functions
PHP Manual

gd_info

(PHP 4 >= 4.3.0, PHP 5)

gd_info — Retrieve information about the currently installed GD library

Description

array gd_info ( void )

Gets information about the version and capabilities of the installed GD library.

Return Values

Returns an associative array.

Elements of array returned by gd_info()
Attribute | Meaning
GD Version | string value describing the installed libgd version.
Freetype Support | boolean value. TRUE if Freetype Support is installed.
Freetype Linkage | string value describing the way in which Freetype was linked. Expected values are: 'with freetype', 'with TTF library', and 'with unknown library'. This element will only be defined if Freetype Support evaluated to TRUE.
T1Lib Support | boolean value. TRUE if T1Lib support is included.
GIF Read Support | boolean value. TRUE if support for reading GIF images is included.
GIF Create Support | boolean value. TRUE if support for creating GIF images is included.
JPEG Support | boolean value. TRUE if JPEG support is included.
PNG Support | boolean value. TRUE if PNG support is included.
WBMP Support | boolean value. TRUE if WBMP support is included.
XBM Support | boolean value. TRUE if XBM support is included.

Note: Previous to PHP 5.3.0, the JPEG Support attribute was named JPG Support.

Examples

Example #1 Using gd_info()

<?php
var_dump(gd_info());
?>

The above example will output something similar to:

array(9) {
  ["GD Version"]=>
  string(24) "bundled (2.0 compatible)"
  ["FreeType Support"]=>
  bool(false)
  ["T1Lib Support"]=>
  bool(false)
  ["GIF Read Support"]=>
  bool(true)
  ["GIF Create Support"]=>
  bool(false)
  ["JPEG Support"]=>
  bool(false)
  ["PNG Support"]=>
  bool(true)
  ["WBMP Support"]=>
  bool(true)
  ["XBM Support"]=>
  bool(false)
}

Changelog

Version | Description
5.3.0 | JPG Support attribute renamed to JPEG Support.

See Also

  • imagepng() - Output a PNG image to either the browser or a file
  • imagejpeg() - Output image to browser or file
  • imagegif() - Output image to browser or file
  • imagewbmp() - Output image to browser or file
  • imagetypes() - Return the image types supported by this PHP build

GD and Image Functions
getimagesize
GD and Image Functions


Get the two letter continent code

GeoIP Functions
geoip_country_code_by_name
GeoIP Functions
PHP Manual

geoip_continent_code_by_name

(PECL geoip >= 1.0.3)

geoip_continent_code_by_name — Get the two letter continent code

Description

string geoip_continent_code_by_name ( string $hostname )

The geoip_continent_code_by_name() function will return the two letter continent code corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the two letter continent code on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_continent_code_by_name() example

This will print where the host example.com is located.

<?php
$continent = geoip_continent_code_by_name('www.example.com');
if ($continent) {
    echo 'This host is located in: ' . $continent;
}
?>

The above example will output:

 This host is located in: NA

See Also

  • geoip_country_code_by_name() - Get the two letter country code

GeoIP Functions
geoip_country_code_by_name
GeoIP Functions


Get the three letter country code

geoip_country_code_by_name
geoip_country_name_by_name
GeoIP Functions
PHP Manual

geoip_country_code3_by_name

(PECL geoip >= 0.2.0)

geoip_country_code3_by_name — Get the three letter country code

Description

string geoip_country_code3_by_name ( string $hostname )

The geoip_country_code3_by_name() function will return the three letter country code corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the three letter country code on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_country_code3_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_code3_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

This host is located in: USA

See Also

  • geoip_country_code_by_name() - Get the two letter country code
  • geoip_country_name_by_name() - Get the full country name

geoip_country_code_by_name
geoip_country_name_by_name
GeoIP Functions


Get the two letter country code

geoip_continent_code_by_name
geoip_country_code3_by_name
GeoIP Functions
PHP Manual

geoip_country_code_by_name

(PECL geoip >= 0.2.0)

geoip_country_code_by_name — Get the two letter country code

Description

string geoip_country_code_by_name ( string $hostname )

The geoip_country_code_by_name() function will return the two letter country code corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the two letter ISO country code on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_country_code_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_code_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

This host is located in: US

See Also

  • geoip_country_code3_by_name() - Get the three letter country code
  • geoip_country_name_by_name() - Get the full country name

geoip_continent_code_by_name
geoip_country_code3_by_name
GeoIP Functions


Get the full country name

geoip_country_code3_by_name
geoip_database_info
GeoIP Functions
PHP Manual

geoip_country_name_by_name

(PECL geoip >= 0.2.0)

geoip_country_name_by_name — Get the full country name

Description

string geoip_country_name_by_name ( string $hostname )

The geoip_country_name_by_name() function will return the full country name corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the country name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_country_name_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_name_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

 This host is located in: United States

See Also

  • geoip_country_code_by_name() - Get the two letter country code
  • geoip_country_code3_by_name() - Get the three letter country code

geoip_country_code3_by_name
geoip_database_info
GeoIP Functions


Get GeoIP Database information

geoip_country_name_by_name
geoip_db_avail
GeoIP Functions
PHP Manual

geoip_database_info

(PECL geoip >= 0.2.0)

geoip_database_info — Get GeoIP Database information

Description

string geoip_database_info ([ int $database = GEOIP_COUNTRY_EDITION ] )

The geoip_database_info() function returns the corresponding GeoIP Database version as it is defined inside the binary file.

If this function is called without arguments, it returns the version of the GeoIP Free Country Edition.

Parameters

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Return Values

Returns the corresponding database version, or NULL on error.

Examples

Example #1 A geoip_region_by_name() example

This will output the current database version string.

<?php
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

The above example will output:

GEO-106FREE 20060801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

geoip_country_name_by_name
geoip_db_avail
GeoIP Functions


Determine if GeoIP Database is available

geoip_database_info
geoip_db_filename
GeoIP Functions
PHP Manual

geoip_db_avail

(PECL geoip >= 1.0.1)

geoip_db_avail — Determine if GeoIP Database is available

Description

bool geoip_db_avail ( int $database )

The geoip_db_avail() function returns if the corresponding GeoIP Database is available and can be opened on disk.

It does not indicate if the file is a proper database, only if it is readable.

Parameters

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Return Values

Returns TRUE is database exists, FALSE if not found, or NULL on error.

Examples

Example #1 A geoip_db_avail() example

This will output the current database version string.

<?php

if (geoip_db_avail(GEOIP_COUNTRY_EDITION))
    print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

The above example will output:

GEO-106FREE 20080801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

geoip_database_info
geoip_db_filename
GeoIP Functions


Returns the filename of the corresponding GeoIP Database

geoip_db_avail
geoip_db_get_all_info
GeoIP Functions
PHP Manual

geoip_db_filename

(PECL geoip >= 1.0.1)

geoip_db_filename — Returns the filename of the corresponding GeoIP Database

Description

string geoip_db_filename ( int $database )

The geoip_db_filename() function returns the filename of the corresponding GeoIP Database.

It does not indicate if the file exists or not on disk, only where the library is looking for the database.

Parameters

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Return Values

Returns the filename of the corresponding database, or NULL on error.

Examples

Example #1 A geoip_db_filename() example

This will output the filename of the corresponding database.

<?php

print geoip_db_filename(GEOIP_COUNTRY_EDITION);

?>

The above example will output:

/usr/share/GeoIP/GeoIP.dat

geoip_db_avail
geoip_db_get_all_info
GeoIP Functions


Returns detailed information about all GeoIP database types

geoip_db_filename
geoip_id_by_name
GeoIP Functions
PHP Manual

geoip_db_get_all_info

(PECL geoip >= 1.0.1)

geoip_db_get_all_info — Returns detailed information about all GeoIP database types

Description

array geoip_db_get_all_info ( void )

The geoip_db_get_all_info() function will return detailed information as a multi-dimensional array about all the GeoIP database types.

This function is available even if no databases are installed. It will simply list them as non-available.

The names of the different keys of the returning associative array are as follows:

  • "available" -- Boolean, indicate if DB is available (see geoip_db_avail())
  • "description" -- The database description
  • "filename" -- The database filename on disk (see geoip_db_filename())

Return Values

Returns the associative array.

Examples

Example #1 A geoip_db_get_all_info() example

This will print the array containing all the information.

<?php
$infos = geoip_db_get_all_info();
if (is_array($infos)) {
    var_dump($infos);
}
?>

The above example will output:

array(11) {
  [1]=>
  array(3) {
    ["available"]=>
    bool(true)
    ["description"]=>
    string(21) "GeoIP Country Edition"
    ["filename"]=>
    string(32) "/usr/share/GeoIP/GeoIP.dat"
  }

[ ... ]

  [11]=>
  array(3) {
    ["available"]=>
    bool(false)
    ["description"]=>
    string(25) "GeoIP Domain Name Edition"
    ["filename"]=>
    string(38) "/usr/share/GeoIP/GeoIPDomain.dat"
  }
}

Example #2 A geoip_db_get_all_info() example

You can use the various constants as keys to get only parts of the information.

<?php
$infos = geoip_db_get_all_info();
if ($infos[GEOIP_COUNTRY_EDITION]['available']) {
    echo $infos[GEOIP_COUNTRY_EDITION]['description'];
}
?>

The above example will output:

GeoIP Country Edition

geoip_db_filename
geoip_id_by_name
GeoIP Functions


Get the Internet connection speed

geoip_db_get_all_info
geoip_isp_by_name
GeoIP Functions
PHP Manual

geoip_id_by_name

(PECL geoip >= 0.2.0)

geoip_id_by_name — Get the Internet connection speed

Description

int geoip_id_by_name ( string $hostname )

The geoip_id_by_name() function will return the country and region corresponding to a hostname or an IP address.

The return value is numeric and can be compared to the following constants:

  • GEOIP_UNKNOWN_SPEED
  • GEOIP_DIALUP_SPEED
  • GEOIP_CABLEDSL_SPEED
  • GEOIP_CORPORATE_SPEED

Parameters

hostname

The hostname or IP address whose net speed is to be looked-up.

Return Values

Returns the net speed.

Examples

Example #1 A geoip_id_by_name() example

This will output the net speed of the host example.com.

<?php
$netspeed = geoip_id_by_name('www.example.com');

echo 'The connection type is ';

switch ($netspeed) {
    case GEOIP_DIALUP_SPEED:
        echo 'dial-up';
        break;
    case GEOIP_CABLEDSL_SPEED:
        echo 'cable or DSL';
        break;
    case GEOIP_CORPORATE_SPEED:
        echo 'corporate';
        break;
    case GEOIP_UNKNOWN_SPEED:
    default:
        echo 'unknown';
}
?>

The above example will output:

The connection type is corporate

geoip_db_get_all_info
geoip_isp_by_name
GeoIP Functions


Get the Internet Service Provider (ISP) name

geoip_id_by_name
geoip_org_by_name
GeoIP Functions
PHP Manual

geoip_isp_by_name

(PECL geoip >= 1.0.2)

geoip_isp_by_name — Get the Internet Service Provider (ISP) name

Description

string geoip_isp_by_name ( string $hostname )

The geoip_isp_by_name() function will return the name of the Internet Service Provider (ISP) that an IP is assigned to.

This function is currently only available to users who have bought a commercial GeoIP ISP Edition. A warning will be issued if the proper database cannot be located.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the ISP name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_isp_by_name() example

This will print the ISP name of host example.com.

<?php
$isp = geoip_isp_by_name('www.example.com');
if ($isp) {
    echo 'This host IP is from ISP: ' . $isp;
}
?>

The above example will output:

This host IP is allocated to: ICANN c/o Internet Assigned Numbers Authority

geoip_id_by_name
geoip_org_by_name
GeoIP Functions


Get the organization name

geoip_isp_by_name
geoip_record_by_name
GeoIP Functions
PHP Manual

geoip_org_by_name

(PECL geoip >= 0.2.0)

geoip_org_by_name — Get the organization name

Description

string geoip_org_by_name ( string $hostname )

The geoip_org_by_name() function will return the name of the organization that an IP is assigned to.

This function is currently only available to users who have bought a commercial GeoIP Organization, ISP or AS Edition. A warning will be issued if the proper database cannot be located.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the organization name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_org_by_name() example

This will print to whom the host example.com IP is allocated.

<?php
$org = geoip_org_by_name('www.example.com');
if ($org) {
    echo 'This host IP is allocated to: ' . $org;
}
?>

The above example will output:

This host IP is allocated to: ICANN c/o Internet Assigned Numbers Authority

geoip_isp_by_name
geoip_record_by_name
GeoIP Functions


Returns the detailed City information found in the GeoIP Database

geoip_org_by_name
geoip_region_by_name
GeoIP Functions
PHP Manual

geoip_record_by_name

(PECL geoip >= 0.2.0)

geoip_record_by_name — Returns the detailed City information found in the GeoIP Database

Description

array geoip_record_by_name ( string $hostname )

The geoip_record_by_name() function will return the record information corresponding to a hostname or an IP address.

This function is available for both GeoLite City Edition and commercial GeoIP City Edition. A warning will be issued if the proper database cannot be located.

The names of the different keys of the returning associative array are as follows:

  • "continent_code" -- Two letter continent code (as of version 1.0.4 with libgeoip 1.4.3 or newer)
  • "country_code" -- Two letter country code (see geoip_country_code_by_name())
  • "country_code3" -- Three letter country code (see geoip_country_code3_by_name())
  • "country_name" -- The country name (see geoip_country_name_by_name())
  • "region" -- The region code (ex: CA for California)
  • "city" -- The city.
  • "postal_code" -- The Postal Code, FSA or Zip Code.
  • "latitude" -- The Latitude as signed double.
  • "longitude" -- The Longitude as signed double.
  • "dma_code" -- Designated Market Area code (USA and Canada only)
  • "area_code" -- The PSTN area code (ex: 212)

Parameters

hostname

The hostname or IP address whose record is to be looked-up.

Return Values

Returns the associative array on success, or FALSE if the address cannot be found in the database.

Changelog

Version | Description
1.0.4 | Adding the continent_code with GeoIP Library 1.4.3 or newer only
1.0.3 | Adding country_code3 and country_name

Examples

Example #1 A geoip_record_by_name() example

This will print the array containing the record of host example.com.

<?php
$record = geoip_record_by_name('www.example.com');
if ($record) {
    print_r($record);
}
?>

The above example will output:

Array
(
    [continent_code] => NA
    [country_code] => US
    [country_code3] => USA
    [country_name] => United States
    [region] => CA
    [city] => Marina Del Rey
    [postal_code] =>
    [latitude] => 33.9776992798
    [longitude] => -118.435096741
    [dma_code] => 803
    [area_code] => 310
)

geoip_org_by_name
geoip_region_by_name
GeoIP Functions


Get the country code and region

geoip_record_by_name
geoip_region_name_by_code
GeoIP Functions
PHP Manual

geoip_region_by_name

(PECL geoip >= 0.2.0)

geoip_region_by_name — Get the country code and region

Description

array geoip_region_by_name ( string $hostname )

The geoip_region_by_name() function will return the country and region corresponding to a hostname or an IP address.

This function is currently only available to users who have bought a commercial GeoIP Region Edition. A warning will be issued if the proper database cannot be located.

The names of the different keys of the returning associative array are as follows:

  • "country_code" -- Two letter country code (see geoip_country_code_by_name())
  • "region" -- The region code (ex: CA for California)

Parameters

hostname

The hostname or IP address whose region is to be looked-up.

Return Values

Returns the associative array on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_region_by_name() example

This will print the array containing the country code and region of the host example.com.

<?php
$region = geoip_region_by_name('www.example.com');
if ($region) {
    print_r($region);
}
?>

The above example will output:

Array
(
    [country_code] => US
    [region] => CA
)

geoip_record_by_name
geoip_region_name_by_code
GeoIP Functions


Returns the region name for some country and region code combo

geoip_region_by_name
geoip_time_zone_by_country_and_region
GeoIP Functions
PHP Manual

geoip_region_name_by_code

(PECL geoip >= 1.0.4)

geoip_region_name_by_code — Returns the region name for some country and region code combo

Description

string geoip_region_name_by_code ( string $country_code , string $region_code )

The geoip_region_name_by_code() function will return the region name corresponding to a country and region code combo.

In the United States, the region code corresponds to the two-letter abbreviation of each state. In Canada, the region code corresponds to the two-letter province or territory code as attributed by Canada Post.

For the rest of the world, GeoIP uses FIPS 10-4 codes to represent regions. You can check » http://www.maxmind.com/app/fips10_4 for a detailed list of FIPS 10-4 codes.

This function is always available if using GeoIP Library version 1.4.1 or newer. The data is taken directly from the GeoIP Library and not from any database.

Parameters

country_code

The two-letter country code (see geoip_country_code_by_name())

region_code

The two-letter (or digit) region code (see geoip_region_by_name())

Return Values

Returns the region name on success, or FALSE if the country and region code combo cannot be found.

Examples

Example #1 A geoip_region_name_by_code() example using region code for US/Canada

This will print the region name for country CA (Canada), region QC (Quebec).

<?php
$region = geoip_region_name_by_code('CA', 'QC');
if ($region) {
    echo 'Region name for CA/QC is: ' . $region;
}
?>

The above example will output:

Region name for CA/QC is: Quebec

Example #2 A geoip_region_name_by_code() example using FIPS codes

This will print the region name for country JP (Japan), region 01.

<?php
$region = geoip_region_name_by_code('JP', '01');
if ($region) {
    echo 'Region name for JP/01 is: ' . $region;
}
?>

The above example will output:

Region name for JP/01 is: Aichi

geoip_region_by_name
geoip_time_zone_by_country_and_region
GeoIP Functions


Returns the time zone for some country and region code combo

geoip_region_name_by_code
JSON
GeoIP Functions
PHP Manual

geoip_time_zone_by_country_and_region

(PECL geoip >= 1.0.4)

geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo

Description

string geoip_time_zone_by_country_and_region ( string $country_code [, string $region_code ] )

The geoip_time_zone_by_country_and_region() function will return the time zone corresponding to a country and region code combo.

In the United States, the region code corresponds to the two-letter abbreviation of each state. In Canada, the region code corresponds to the two-letter province or territory code as attributed by Canada Post.

For the rest of the world, GeoIP uses FIPS 10-4 codes to represent regions. You can check » http://www.maxmind.com/app/fips10_4 for a detailed list of FIPS 10-4 codes.

This function is always available if using GeoIP Library version 1.4.1 or newer. The data is taken directly from the GeoIP Library and not from any database.

Parameters

country_code

The two-letter country code (see geoip_country_code_by_name())

region_code

The two-letter (or digit) region code (see geoip_region_by_name())

Return Values

Returns the time zone on success, or FALSE if the country and region code combo cannot be found.

Examples

Example #1 A geoip_time_zone_by_country_and_region() example using region code for US/Canada

This will print the time zone for country CA (Canada), region QC (Quebec).

<?php
$timezone = geoip_time_zone_by_country_and_region('CA', 'QC');
if ($timezone) {
    echo 'Time zone for CA/QC is: ' . $timezone;
}
?>

The above example will output:

Time zone for CA/QC is: America/Montreal

Example #2 A geoip_time_zone_by_country_and_region() example using FIPS codes

This will print the time zone for country JP (Japan), region 01 (Aichi).

<?php
$timezone = geoip_time_zone_by_country_and_region('JP', '01');
if ($timezone) {
    echo 'Time zone for JP/01 is: ' . $timezone;
}
?>

The above example will output:

Time zone for JP/01 is: Asia/Tokyo

geoip_region_name_by_code
JSON
GeoIP Functions


Tells what the user's browser is capable of

exit
__halt_compiler
Misc. Functions
PHP Manual

get_browser

(PHP 4, PHP 5)

get_browser — Tells what the user's browser is capable of

Description

mixed get_browser ([ string $user_agent [, bool $return_array = false ]] )

Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file.

Parameters

user_agent

The User Agent to be analyzed. By default, the value of HTTP User-Agent header is used; however, you can alter this (i.e., look up another browser's info) by passing this parameter.

You can bypass this parameter with a NULL value.

return_array

If set to TRUE, this function will return an array instead of an object.

Return Values

The information is returned in an object or an array which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; TRUE/FALSE values for features such as frames, JavaScript, and cookies; and so forth.

The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not. The only way to test if cookies are accepted is to set one with setcookie(), reload, and check for the value.

Changelog

Version | Description
4.3.2 | The optional parameter return_array was added.

Examples

Example #1 Listing all information about the users browser

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

The above example will output something similar to:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

Notes

Note: In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.
browscap.ini is not bundled with PHP, but you may find an up-to-date » php_browscap.ini file here.
While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.

exit
__halt_compiler
Misc. Functions


Gets the value of a PHP configuration option

gc_enabled
get_current_user
PHP Options/Info Functions
PHP Manual

get_cfg_var

(PHP 4, PHP 5)

get_cfg_var — Gets the value of a PHP configuration option

Description

string get_cfg_var ( string $option )

Gets the value of a PHP configuration option .

This function will not return configuration information set when the PHP was compiled, or read from an Apache configuration file.

To check whether the system is using a configuration file, try retrieving the value of the cfg_file_path configuration setting. If this is available, a configuration file is being used.

Parameters

option

The configuration option name.

Return Values

Returns the current value of the PHP configuration variable specified by option , or FALSE if an error occurs.

Changelog

Version | Description
5.3.0 | get_cfg_var() was fixed to be able to return "array" ini options.

See Also

  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options

gc_enabled
get_current_user
PHP Options/Info Functions


Gets the name of the owner of the current PHP script

get_cfg_var
get_defined_constants
PHP Options/Info Functions
PHP Manual

get_current_user

(PHP 4, PHP 5)

get_current_user — Gets the name of the owner of the current PHP script

Description

string get_current_user ( void )

Returns the name of the owner of the current PHP script.

Return Values

Returns the username as a string.

Examples

Example #1 get_current_user() example

<?php
echo 'Current script owner: ' . get_current_user();
?>

The above example will output something similar to:

Current script owner: SYSTEM

See Also

  • getmyuid() - Gets PHP script owner's UID
  • getmygid() - Get PHP script owner's GID
  • getmypid() - Gets PHP's process ID
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

get_cfg_var
get_defined_constants
PHP Options/Info Functions


Returns an associative array with the names of all the constants and their values

get_current_user
get_extension_funcs
PHP Options/Info Functions
PHP Manual

get_defined_constants

(PHP 4 >= 4.1.0, PHP 5)

get_defined_constants — Returns an associative array with the names of all the constants and their values

Description

array get_defined_constants ([ bool $categorize ] )

Returns the names and values of all the constants currently defined. This includes those created by extensions as well as those created with the define() function.

Parameters

categorize

Causing this function to return a multi-dimensional array with categories in the keys of the first dimension and constants and their values in the second dimension.

<?php
define("MY_CONSTANT", 1);
print_r(get_defined_constants(true));
?>

The above example will output something similar to:

Array
(
    [Core] => Array
        (
            [E_ERROR] => 1
            [E_WARNING] => 2
            [E_PARSE] => 4
            [E_NOTICE] => 8
            [E_CORE_ERROR] => 16
            [E_CORE_WARNING] => 32
            [E_COMPILE_ERROR] => 64
            [E_COMPILE_WARNING] => 128
            [E_USER_ERROR] => 256
            [E_USER_WARNING] => 512
            [E_USER_NOTICE] => 1024
            [E_ALL] => 2047
            [TRUE] => 1
        )

    [pcre] => Array
        (
            [PREG_PATTERN_ORDER] => 1
            [PREG_SET_ORDER] => 2
            [PREG_OFFSET_CAPTURE] => 256
            [PREG_SPLIT_NO_EMPTY] => 1
            [PREG_SPLIT_DELIM_CAPTURE] => 2
            [PREG_SPLIT_OFFSET_CAPTURE] => 4
            [PREG_GREP_INVERT] => 1
        )

    [user] => Array
        (
            [MY_CONSTANT] => 1
        )

)

Return Values

Changelog

Version | Description
5.3.1 | Windows only : Core constants are categorized under Core, previously mhash.
5.3.0 | Core constants are categorized under Core, previously internal. On Windows, the Core Constants are categorized under mhash.
5.0.0 | The categorize parameter was added.

Examples

Example #1 get_defined_constants() Example

<?php
print_r(get_defined_constants());
?>

The above example will output something similar to:

Array
(
    [E_ERROR] => 1
    [E_WARNING] => 2
    [E_PARSE] => 4
    [E_NOTICE] => 8
    [E_CORE_ERROR] => 16
    [E_CORE_WARNING] => 32
    [E_COMPILE_ERROR] => 64
    [E_COMPILE_WARNING] => 128
    [E_USER_ERROR] => 256
    [E_USER_WARNING] => 512
    [E_USER_NOTICE] => 1024
    [E_ALL] => 2047
    [TRUE] => 1
)

See Also

  • defined() - Checks whether a given named constant exists
  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • get_defined_functions() - Returns an array of all defined functions
  • get_defined_vars() - Returns an array of all defined variables

get_current_user
get_extension_funcs
PHP Options/Info Functions


Returns an array with the names of the functions of a module

get_defined_constants
get_include_path
PHP Options/Info Functions
PHP Manual

get_extension_funcs

(PHP 4, PHP 5)

get_extension_funcs — Returns an array with the names of the functions of a module

Description

array get_extension_funcs ( string $module_name )

This function returns the names of all the functions defined in the module indicated by module_name .

Parameters

module_name

The module name.

Note: This parameter must be in lowercase.

Return Values

Returns an array with all the functions, or FALSE if module_name is not a valid extension.

Examples

Example #1 Prints the XML functions

<?php
print_r(get_extension_funcs("xml"));
?>

The above example will output something similar to:

Array
(
    [0] => xml_parser_create
    [1] => xml_parser_create_ns
    [2] => xml_set_object
    [3] => xml_set_element_handler
    [4] => xml_set_character_data_handler
    [5] => xml_set_processing_instruction_handler
    [6] => xml_set_default_handler
    [7] => xml_set_unparsed_entity_decl_handler
    [8] => xml_set_notation_decl_handler
    [9] => xml_set_external_entity_ref_handler
    [10] => xml_set_start_namespace_decl_handler
    [11] => xml_set_end_namespace_decl_handler
    [12] => xml_parse
    [13] => xml_parse_into_struct
    [14] => xml_get_error_code
    [15] => xml_error_string
    [16] => xml_get_current_line_number
    [17] => xml_get_current_column_number
    [18] => xml_get_current_byte_index
    [19] => xml_parser_free
    [20] => xml_parser_set_option
    [21] => xml_parser_get_option
    [22] => utf8_encode
    [23] => utf8_decode
)

See Also

  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded

get_defined_constants
get_include_path
PHP Options/Info Functions


Gets the current include_path configuration option

get_extension_funcs
get_included_files
PHP Options/Info Functions
PHP Manual

get_include_path

(PHP 4 >= 4.3.0, PHP 5)

get_include_path — Gets the current include_path configuration option

Description

string get_include_path ( void )

Gets the current include_path configuration option value.

Return Values

Returns the path, as a string.

Examples

Example #1 get_include_path() example

<?php
// Works as of PHP 4.3.0
echo get_include_path();

// Works in all PHP versions
echo ini_get('include_path');
?>

See Also

  • ini_get() - Gets the value of a configuration option
  • restore_include_path() - Restores the value of the include_path configuration option
  • set_include_path() - Sets the include_path configuration option
  • include() - include

get_extension_funcs
get_included_files
PHP Options/Info Functions


Returns an array with the names of included or required files

get_include_path
get_loaded_extensions
PHP Options/Info Functions
PHP Manual

get_included_files

(PHP 4, PHP 5)

get_included_files — Returns an array with the names of included or required files

Description

array get_included_files ( void )

Gets the names of all files that have been included using include(), include_once(), require() or require_once().

Return Values

Returns an array of the names of all files.

The script originally called is considered an "included file," so it will be listed together with the files referenced by include() and family.

Files that are included or required multiple times only show up once in the returned array.

Changelog

Version | Description
4.0.1 | In PHP 4.0.1 and previous versions this function assumed that the required files ended in the extension .php; other extensions would not be returned. The array returned by get_included_files() was an associative array and only listed files included by include() and include_once().

Examples

Example #1 get_included_files() example

<?php
// This file is abc.php

include 'test1.php';
include_once 'test2.php';
require 'test3.php';
require_once 'test4.php';

$included_files = get_included_files();

foreach ($included_files as $filename) {
    echo "$filename\n";
}

?>

The above example will output:

abc.php
test1.php
test2.php
test3.php
test4.php

Notes

Note: Files included using the auto_prepend_file configuration directive are not included in the returned array.

See Also

  • include() - include
  • include_once() - include_once
  • require() - require
  • require_once() - require_once
  • get_required_files() - Alias of get_included_files

get_include_path
get_loaded_extensions
PHP Options/Info Functions


Returns an array with the names of all modules compiled and loaded

get_included_files
get_magic_quotes_gpc
PHP Options/Info Functions
PHP Manual

get_loaded_extensions

(PHP 4, PHP 5)

get_loaded_extensions — Returns an array with the names of all modules compiled and loaded

Description

array get_loaded_extensions ([ bool $zend_extensions = false ] )

This function returns the names of all the modules compiled and loaded in the PHP interpreter.

Parameters

zend_extensions

Return zend_extensions or not, defaults to FALSE (do not list zend_extensions).

Return Values

Returns an indexed array of all the modules names.

Changelog

Version | Description
5.2.4 | The optional zend_extensions parameter was added

Examples

Example #1 get_loaded_extensions() Example

<?php
print_r(get_loaded_extensions());
?>

The above example will output something similar to:

Array
(
   [0] => xml
   [1] => wddx
   [2] => standard
   [3] => session
   [4] => posix
   [5] => pgsql
   [6] => pcre
   [7] => gd
   [8] => ftp
   [9] => db
   [10] => calendar
   [11] => bcmath
)

See Also

  • get_extension_funcs() - Returns an array with the names of the functions of a module
  • extension_loaded() - Find out whether an extension is loaded
  • dl() - Loads a PHP extension at runtime
  • phpinfo() - Outputs lots of PHP information

get_included_files
get_magic_quotes_gpc
PHP Options/Info Functions


Gets the current configuration setting of magic_quotes_gpc

get_loaded_extensions
get_magic_quotes_runtime
PHP Options/Info Functions
PHP Manual

get_magic_quotes_gpc

(PHP 4, PHP 5)

get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc

Description

int get_magic_quotes_gpc ( void )

Returns the current configuration setting of magic_quotes_gpc

Keep in mind that attempting to set magic_quotes_gpc at runtime will not work.

For more information about magic_quotes, see this security section.

Return Values

Returns 0 if magic_quotes_gpc is off, 1 otherwise.

Examples

Example #1 get_magic_quotes_gpc() example

<?php
echo get_magic_quotes_gpc();         // 1
echo $_POST['lastname'];             // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly

if (!get_magic_quotes_gpc()) {
    $lastname = addslashes($_POST['lastname']);
} else {
    $lastname = $_POST['lastname'];
}

echo $lastname; // O\'reilly
$sql = "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
?>

Notes

Note: If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc. So even when get_magic_quotes_gpc() returns TRUE neither double quotes, backslashes or NUL's will be escaped. Only single quotes will be escaped. In this case they'll look like: ''

See Also

  • addslashes() - Quote string with slashes
  • stripslashes() - Un-quotes a quoted string
  • get_magic_quotes_runtime() - Gets the current active configuration setting of magic_quotes_runtime
  • ini_get() - Gets the value of a configuration option

get_loaded_extensions
get_magic_quotes_runtime
PHP Options/Info Functions


Gets the current active configuration setting of magic_quotes_runtime

get_magic_quotes_gpc
get_required_files
PHP Options/Info Functions
PHP Manual

get_magic_quotes_runtime

(PHP 4, PHP 5)

get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime

Description

int get_magic_quotes_runtime ( void )

Returns the current active configuration setting of magic_quotes_runtime.

Return Values

Returns 0 if magic_quotes_runtime is off, 1 otherwise.

Examples

Example #1 get_magic_quotes_runtime() example

<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
    // Deactivate
    set_magic_quotes_runtime(false);
}
?>

See Also

  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc
  • set_magic_quotes_runtime() - Sets the current active configuration setting of magic_quotes_runtime

get_magic_quotes_gpc
get_required_files
PHP Options/Info Functions


Alias of get_included_files

get_magic_quotes_runtime
getenv
PHP Options/Info Functions
PHP Manual

get_required_files

(PHP 4, PHP 5)

get_required_files — Alias of get_included_files()

Description

This function is an alias of: get_included_files().

get_magic_quotes_runtime
getenv
PHP Options/Info Functions


Gets the current working directory

closedir
opendir
Directory Functions
PHP Manual

getcwd

(PHP 4, PHP 5)

getcwd — Gets the current working directory

Description

string getcwd ( void )

Gets the current working directory.

Return Values

Returns the current working directory on success, or FALSE on failure.

On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does. See chmod() for more information on modes and permissions.

Examples

Example #1 getcwd() example

<?php

// current directory
echo getcwd() . "\n";

chdir('cvs');

// current directory
echo getcwd() . "\n";

?>

The above example will output something similar to:

/home/didou
/home/didou/cvs

See Also

  • chdir() - Change directory
  • chmod() - Changes file mode

closedir
opendir
Directory Functions


Get date/time information

date
gettimeofday
Date/Time Functions
PHP Manual

getdate

(PHP 4, PHP 5)

getdate — Get date/time information

Description

array getdate ([ int $timestamp = time() ] )

Returns an associative array containing the date information of the timestamp , or the current local time if no timestamp is given.

Parameters

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns an associative array of information related to the timestamp . Elements from the returned associative array are as follows:

Key elements of the returned associative array
Key | Description | Example returned values
"seconds" | Numeric representation of seconds | 0 to 59
"minutes" | Numeric representation of minutes | 0 to 59
"hours" | Numeric representation of hours | 0 to 23
"mday" | Numeric representation of the day of the month | 1 to 31
"wday" | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday)
"mon" | Numeric representation of a month | 1 through 12
"year" | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003
"yday" | Numeric representation of the day of the year | 0 through 365
"weekday" | A full textual representation of the day of the week | Sunday through Saturday
"month" | A full textual representation of a month, such as January or March | January through December
0 | Seconds since the Unix Epoch, similar to the values returned by time() and used by date(). | System Dependent, typically -2147483648 through 2147483647.

Examples

Example #1 getdate() example

<?php
$today = getdate();
print_r($today);
?>

The above example will output something similar to:

Array
(
    [seconds] => 40
    [minutes] => 58
    [hours]   => 21
    [mday]    => 17
    [wday]    => 2
    [mon]     => 6
    [year]    => 2003
    [yday]    => 167
    [weekday] => Tuesday
    [month]   => June
    [0]       => 1055901520
)

See Also

  • date() - Format a local time/date
  • idate() - Format a local time/date as integer
  • time() - Return current Unix timestamp
  • setlocale() - Set locale information

date
gettimeofday
Date/Time Functions


Gets the value of an environment variable

get_required_files
getlastmod
PHP Options/Info Functions
PHP Manual

getenv

(PHP 4, PHP 5)

getenv — Gets the value of an environment variable

Description

string getenv ( string $varname )

Gets the value of an environment variable.

You can see a list of all the environmental variables by using phpinfo(). You can find out what many of them mean by taking a look at the » CGI specification, specifically the » page on environmental variables.

Parameters

varname

The variable name.

Return Values

Returns the value of the environment variable varname , or FALSE on an error.

Examples

Example #1 getenv() Example

<?php
// Example use of getenv()
$ip = getenv('REMOTE_ADDR');

// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];
?>

See Also

  • putenv() - Sets the value of an environment variable
  • apache_getenv() - Get an Apache subprocess_env variable
  • Superglobals

get_required_files
getlastmod
PHP Options/Info Functions


Get the size of an image

gd_info
image_type_to_extension
GD and Image Functions
PHP Manual

getimagesize

(PHP 4, PHP 5)

getimagesize — Get the size of an image

Description

array getimagesize ( string $filename [, array &$imageinfo ] )

The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML <IMG> tag and the correspondant HTTP content type.

getimagesize() can also return some more information in imageinfo parameter.

Note: Note that JPC and JP2 are capable of having components with different bit depths. In this case, the value for "bits" is the highest bit depth encountered. Also, JP2 files may contain multiple JPEG 2000 codestreams. In this case, getimagesize() returns the values for the first codestream it encounters in the root of the file.

Note: The information about icons are retrieved from the icon with the highest bitrate.

Parameters

filename

This parameter specifies the file you wish to retrieve information about. It can reference a local file or (configuration permitting) a remote file using one of the supported streams.

imageinfo

This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed » IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.

Return Values

Returns an array with 7 elements.

Index 0 and 1 contains respectively the width and the height of the image.

Note: Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.

Index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image.

Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.

mime is the correspondant MIME type of the image. This information can be used to deliver images with correct the HTTP Content-type header:

Example #1 getimagesize() and MIME types

<?php
$size = getimagesize($filename);
$fp = fopen($filename, "rb");
if ($size && $fp) {
    header("Content-type: {$size['mime']}");
    fpassthru($fp);
    exit;
} else {
    // error
}
?>

channels will be 3 for RGB pictures and 4 for CMYK pictures.

bits is the number of bits for each color.

For some image types, the presence of channels and bits values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table.

On failure, FALSE is returned.

Errors/Exceptions

If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will generate an error of level E_WARNING. On read error, getimagesize() will generate an error of level E_NOTICE.

Changelog

Version | Description
5.3.0 | Added icon support.
5.2.3 | Read errors generated by this function downgraded to E_NOTICE from E_WARNING.
4.3.2 | Support for JPC, JP2, JPX, JB2, XBM, and WBMP became available.
4.3.2 | JPEG 2000 support was added for the imageinfo parameter.
4.3.0 | bits and channels are present for other image types, too.
4.3.0 | mime was added.
4.3.0 | Support for SWC and IFF was added.
4.2.0 | Support for TIFF was added.
4.0.6 | Support for BMP and PSD was added.
4.0.5 | URL support was added.

Examples

Example #2 getimagesize() example

<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>

Example #3 getimagesize (URL)

<?php
$size = getimagesize("http://www.example.com/gifs/logo.gif");

// if the file name has space in it, encode it properly
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");

?>

Example #4 getimagesize() returning IPTC

<?php
$size = getimagesize("testimg.jpg", $info);
if (isset($info["APP13"])) {
    $iptc = iptcparse($info["APP13"]);
    var_dump($iptc);
}
?>

Notes

Note: This function does not require the GD image library.

See Also

  • image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
  • exif_imagetype() - Determine the type of an image
  • exif_read_data() - Reads the EXIF headers from JPEG or TIFF
  • exif_thumbnail() - Retrieve the embedded thumbnail of a TIFF or JPEG image

gd_info
image_type_to_extension
GD and Image Functions


Gets time of last page modification

getenv
getmygid
PHP Options/Info Functions
PHP Manual

getlastmod

(PHP 4, PHP 5)

getlastmod — Gets time of last page modification

Description

int getlastmod ( void )

Gets the time of the last modification of the current page.

If you're interested in getting the last modification time of a different file, consider using filemtime().

Return Values

Returns the time of the last modification of the current page. The value returned is a Unix timestamp, suitable for feeding to date(). Returns FALSE on error.

Examples

Example #1 getlastmod() example

<?php
// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod());
?>

See Also

  • date() - Format a local time/date
  • getmyuid() - Gets PHP script owner's UID
  • getmygid() - Get PHP script owner's GID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getmypid() - Gets PHP's process ID
  • filemtime() - Gets file modification time

getenv
getmygid
PHP Options/Info Functions


Get PHP script owner's GID

getlastmod
getmyinode
PHP Options/Info Functions
PHP Manual

getmygid

(PHP 4 >= 4.1.0, PHP 5)

getmygid — Get PHP script owner's GID

Description

int getmygid ( void )

Gets the group ID of the current script.

Return Values

Returns the group ID of the current script, or FALSE on error.

See Also

  • getmyuid() - Gets PHP script owner's UID
  • getmypid() - Gets PHP's process ID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

getlastmod
getmyinode
PHP Options/Info Functions


Gets the inode of the current script

getmygid
getmypid
PHP Options/Info Functions
PHP Manual

getmyinode

(PHP 4, PHP 5)

getmyinode — Gets the inode of the current script

Description

int getmyinode ( void )

Gets the inode of the current script.

Return Values

Returns the current script's inode as an integer, or FALSE on error.

See Also

  • getmygid() - Get PHP script owner's GID
  • getmyuid() - Gets PHP script owner's UID
  • getmypid() - Gets PHP's process ID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getlastmod() - Gets time of last page modification

getmygid
getmypid
PHP Options/Info Functions


Gets PHP's process ID

getmyinode
getmyuid
PHP Options/Info Functions
PHP Manual

getmypid

(PHP 4, PHP 5)

getmypid — Gets PHP's process ID

Description

int getmypid ( void )

Gets the current PHP process ID.

Return Values

Returns the current PHP process ID, or FALSE on error.

Notes

Warning

Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.

See Also

  • getmygid() - Get PHP script owner's GID
  • getmyuid() - Gets PHP script owner's UID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

getmyinode
getmyuid
PHP Options/Info Functions


Gets PHP script owner's UID

getmypid
getopt
PHP Options/Info Functions
PHP Manual

getmyuid

(PHP 4, PHP 5)

getmyuid — Gets PHP script owner's UID

Description

int getmyuid ( void )

Gets the user ID of the current script.

Return Values

Returns the user ID of the current script, or FALSE on error.

See Also

  • getmygid() - Get PHP script owner's GID
  • getmypid() - Gets PHP's process ID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

getmypid
getopt
PHP Options/Info Functions


Gets options from the command line argument list

getmyuid
getrusage
PHP Options/Info Functions
PHP Manual

getopt

(PHP 4 >= 4.3.0, PHP 5)

getopt — Gets options from the command line argument list

Description

array getopt ( string $options [, array $longopts ] )

Parses options passed to the script.

Parameters

options
Each character in this string will be used as option characters and matched against options passed to the script starting with a single hyphen (-). For example, an option string "x" recognizes an option -x. Only a-z, A-Z and 0-9 are allowed.
longopts
An array of options. Each element in this array will be used as option strings and matched against options passed to the script starting with two hyphens (--). For example, an longopts element "opt" recognizes an option --opt.

Note: Prior to PHP5.3.0 this parameter was only available on few systems

The options parameter may contain the following elements:

  • Individual characters (do not accept values)
  • Characters followed by a colon (parameter requires value)
  • Characters followed by two colons (optional value)

Option values are the first argument after the string. It does not matter if a value has leading white space or not.

Note: Optional values do not accept " " (space) as a separator.

Note: The format for the options and longopts is almost the same, the only difference is that longopts takes an array of options (where each element is the option) where as options takes a string (where each character is the option).

Return Values

This function will return an array of option / argument pairs or FALSE on failure.

Note: The parsing of options will end at the first non-option found, anything that follows is discarded.

Changelog

Version | Description
5.3.0 | Added support for "=" as argument/value separator.
5.3.0 | Added support for optional values (specified with "::").
5.3.0 | This function is no longer system dependent and works on Windows too.

Examples

Example #1 getopt() example

<?php
$options = getopt("f:hp:");
var_dump($options);
?>

Running the above script with php script.php -fvalue -h will output:

array(2) {
  ["f"]=>
  string(5) "value"
  ["h"]=>
  bool(false)
}

Example #2 getopt() example#2

<?php
$shortopts  = "";
$shortopts .= "f:";  // Required value
$shortopts .= "v::"; // Optional value
$shortopts .= "abc"; // These options do not accept values

$longopts  = array(
    "required:",     // Required value
    "optional::",    // Optional value
    "option",        // No value
    "opt",           // No value
);
$options = getopt($shortopts, $longopts);
var_dump($options);
?>

Running the above script with php script.php -f "value for f" -v -a --required value --optional="optional value" --option will output:

array(6) {
  ["f"]=>
  string(11) "value for f"
  ["v"]=>
  bool(false)
  ["a"]=>
  bool(false)
  ["required"]=>
  string(5) "value"
  ["optional"]=>
  string(14) "optional value"
  ["option"]=>
  bool(false)
}

Example #3 getopt() example#3

Passing multiple options as one

<?php
$options = getopt("abc");
var_dump($options);
?>

Running the above script with php script.php -aaac will output:

array(2) {
  ["a"]=>
  array(3) {
    [0]=>
    bool(false)
    [1]=>
    bool(false)
    [2]=>
    bool(false)
  }
  ["c"]=>
  bool(false)
}

getmyuid
getrusage
PHP Options/Info Functions


Show largest possible random value

fmod
hexdec
Math Functions
PHP Manual

getrandmax

(PHP 4, PHP 5)

getrandmax — Show largest possible random value

Description

int getrandmax ( void )

Returns the maximum value that can be returned by a call to rand().

Return Values

The largest possible random value returned by rand()

See Also

  • rand() - Generate a random integer
  • srand() - Seed the random number generator
  • mt_getrandmax() - Show largest possible random value

fmod
hexdec
Math Functions


Gets the current resource usages

getopt
ini_alter
PHP Options/Info Functions
PHP Manual

getrusage

(PHP 4, PHP 5)

getrusage — Gets the current resource usages

Description

array getrusage ([ int $who = 0 ] )

This is an interface to getrusage(2). It gets data returned from the system call.

Parameters

who

If who is 1, getrusage will be called with RUSAGE_CHILDREN.

Return Values

Returns an associative array containing the data returned from the system call. All entries are accessible by using their documented field names.

Examples

Example #1 getrusage() example

<?php
$dat = getrusage();
echo $dat["ru_nswap"];         // number of swaps
echo $dat["ru_majflt"];        // number of page faults
echo $dat["ru_utime.tv_sec"];  // user time used (seconds)
echo $dat["ru_utime.tv_usec"]; // user time used (microseconds)
?>

Notes

Note: This function is not implemented on Windows platforms.

See Also

  • Your system's man page on getrusage(2)

getopt
ini_alter
PHP Options/Info Functions


Lookup a message in the current domain

dngettext
ngettext
Gettext Functions
PHP Manual

gettext

(PHP 4, PHP 5)

gettext — Lookup a message in the current domain

Description

string gettext ( string $message )

Looks up a message in the current domain.

Parameters

message

The message being translated.

Return Values

Returns a translated string if one is found in the translation table, or the submitted message if not found.

Examples

Example #1 gettext()-check

<?php
// Set language to German
putenv('LC_ALL=de_DE');
setlocale(LC_ALL, 'de_DE');

// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");

// Choose domain
textdomain("myPHPApp");

// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now

// Print a test message
echo gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
echo _("Have a nice day");
?>

Notes

Note: You may use the underscore character '_' as an alias to this function.

Note: Setting a language isn't enough for some systems and the putenv() should be used to define the current locale.

See Also

  • setlocale() - Set locale information

dngettext
ngettext
Gettext Functions


Get current time

getdate
gmdate
Date/Time Functions
PHP Manual

gettimeofday

(PHP 4, PHP 5)

gettimeofday — Get current time

Description

mixed gettimeofday ([ bool $return_float ] )

This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.

Parameters

return_float

When set to TRUE, a float instead of an array is returned.

Return Values

By default an array is returned. If return_float is set, then a float is returned.

Array keys:

  • "sec" - seconds since the Unix Epoch
  • "usec" - microseconds
  • "minuteswest" - minutes west of Greenwich
  • "dsttime" - type of dst correction

Changelog

Version | Description
5.1.0 | The return_float parameter was added.

Examples

Example #1 gettimeofday() example

<?php
print_r(gettimeofday());

echo gettimeofday(true);
?>

The above example will output something similar to:

Array
(
    [sec] => 1073504408
    [usec] => 238215
    [minuteswest] => 0
    [dsttime] => 1
)

1073504408.23910

getdate
gmdate
Date/Time Functions


Find pathnames matching a pattern

fwrite
is_dir
Filesystem Functions
PHP Manual

glob

(PHP 4 >= 4.3.0, PHP 5)

glob — Find pathnames matching a pattern

Description

array glob ( string $pattern [, int $flags = 0 ] )

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

Parameters

pattern

The pattern. No tilde expansion or parameter substitution is done.

flags

Valid flags:

  • GLOB_MARK - Adds a slash to each directory returned
  • GLOB_NOSORT - Return files as they appear in the directory (no sorting)
  • GLOB_NOCHECK - Return the search pattern if no files matching it were found
  • GLOB_NOESCAPE - Backslashes do not quote metacharacters
  • GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
  • GLOB_ONLYDIR - Return only directory entries which match the pattern
  • GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored.

Return Values

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

Note: On some systems it is impossible to distinguish between empty match and an error.

Changelog

Version | Description
5.1.0 | GLOB_ERR was added
4.3.3 | GLOB_ONLYDIR became available on Windows and other systems not using the GNU C library

Examples

Example #1 Convenient way how glob() can replace opendir() and friends.

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

The above example will output something similar to:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: This function isn't available on some systems (e.g. old Sun OS).

Note: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris.

See Also

  • opendir() - Open directory handle
  • readdir() - Read entry from directory handle
  • closedir() - Close directory handle
  • fnmatch() - Match filename against a pattern

fwrite
is_dir
Filesystem Functions


Format a GMT/UTC date/time

gettimeofday
gmmktime
Date/Time Functions
PHP Manual

gmdate

(PHP 4, PHP 5)

gmdate — Format a GMT/UTC date/time

Description

string gmdate ( string $format [, int $timestamp ] )

Identical to the date() function except that the time returned is Greenwich Mean Time (GMT).

Parameters

format

The format of the outputted date string. See the formatting options for the date() function.

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a formatted date string. If a non-numeric value is used for timestamp , FALSE is returned and an E_WARNING level error is emitted.

Changelog

Version | Description
5.1.0 | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
5.1.1 | There are useful constants of standard date/time formats that can be used to specify the format parameter.

Examples

Example #1 gmdate() example

When run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "Dec 31 1997 22:00:00".

<?php
echo date("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
?>

See Also

  • date() - Format a local time/date
  • mktime() - Get Unix timestamp for a date
  • gmmktime() - Get Unix timestamp for a GMT date
  • strftime() - Format a local time/date according to locale settings

gettimeofday
gmmktime
Date/Time Functions


Get Unix timestamp for a GMT date

gmdate
gmstrftime
Date/Time Functions
PHP Manual

gmmktime

(PHP 4, PHP 5)

gmmktime — Get Unix timestamp for a GMT date

Description

 int gmmktime
  ([ int $hour = gmdate("H")
 [, int $minute = gmdate("i")
 [, int $second = gmdate("s")
 [, int $month = gmdate("n")
 [, int $day = gmdate("j")
 [, int $year = gmdate("Y")
 [, int $is_dst = -1
]]]]]]] )

Identical to mktime() except the passed parameters represents a GMT date. gmmktime() internally uses mktime() so only times valid in derived local time can be used.

Like mktime(), arguments may be left out in order from right to left, with any omitted arguments being set to the current corresponding GMT value.

Parameters

hour

The hour

minute

The minute

second

The second

month

The month

day

The day

year

The year

is_dst

Parameters always represent a GMT date so is_dst doesn't influence the result.

Return Values

Returns a integer Unix timestamp.

Changelog

Version | Description
5.1.0 | As of PHP 5.1.0, the is_dst parameter became deprecated. As a result, the new timezone handling features should be used instead.

Examples

Example #1 gmmktime() on Windows boundary

<?php
gmmktime(0, 0, 0, 1, 1, 1970); // valid in GMT and west, invalid in east
?>

See Also

  • mktime() - Get Unix timestamp for a date
  • date() - Format a local time/date
  • time() - Return current Unix timestamp

gmdate
gmstrftime
Date/Time Functions


Absolute value

GMP Functions
gmp_add
GMP Functions
PHP Manual

gmp_abs

(PHP 4 >= 4.0.4, PHP 5)

gmp_abs — Absolute value

Description

resource gmp_abs ( resource $a )

Get the absolute value of a number.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

Returns the absolute value of a , as a GMP number.

Examples

Example #1 gmp_abs() example

<?php
$abs1 = gmp_abs("274982683358");
$abs2 = gmp_abs("-274982683358");

echo gmp_strval($abs1) . "\n";
echo gmp_strval($abs2) . "\n";
?>

The above example will output:

274982683358
274982683358

GMP Functions
gmp_add
GMP Functions


Add numbers

gmp_abs
gmp_and
GMP Functions
PHP Manual

gmp_add

(PHP 4 >= 4.0.4, PHP 5)

gmp_add — Add numbers

Description

resource gmp_add ( resource $a , resource $b )

Add two numbers.

Parameters

a

A number that will be added.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

A number that will be added.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number representing the sum of the arguments.

Examples

Example #1 gmp_add() example

<?php
$sum = gmp_add("123456789012345", "76543210987655");
echo gmp_strval($sum) . "\n";
?>

The above example will output:

200000000000000

gmp_abs
gmp_and
GMP Functions


Bitwise AND

gmp_add
gmp_clrbit
GMP Functions
PHP Manual

gmp_and

(PHP 4 >= 4.0.4, PHP 5)

gmp_and — Bitwise AND

Description

resource gmp_and ( resource $a , resource $b )

Calculates bitwise AND of two GMP numbers.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number representing the bitwise AND comparison.

Examples

Example #1 gmp_and() example

<?php
$and1 = gmp_and("0xfffffffff4", "0x4");
$and2 = gmp_and("0xfffffffff4", "0x8");
echo gmp_strval($and1) . "\n";
echo gmp_strval($and2) . "\n";
?>

The above example will output:

4
0
gmp_add
gmp_clrbit
GMP Functions


Clear bit

gmp_and
gmp_cmp
GMP Functions
PHP Manual

gmp_clrbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_clrbit — Clear bit

Description

void gmp_clrbit ( resource $a , int $index )

Clears (sets to 0) bit index in a . The index starts at 0.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

index

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

Examples

Example #1 gmp_clrbit() example

<?php
$a = gmp_init("0xff");
gmp_clrbit($a, 0); // index starts at 0, least significant bit
echo gmp_strval($a) . "\n";
?>

The above example will output:

254

Notes

Note: Unlike most of the other GMP functions, gmp_clrbit() must be called with a GMP resource that already exists (using gmp_init() for example). One will not be automatically created.

See Also

  • gmp_setbit() - Set bit
  • gmp_testbit() - Tests if a bit is set

gmp_and
gmp_cmp
GMP Functions


Compare numbers

gmp_clrbit
gmp_com
GMP Functions
PHP Manual

gmp_cmp

(PHP 4 >= 4.0.4, PHP 5)

gmp_cmp — Compare numbers

Description

int gmp_cmp ( resource $a , resource $b )

Compares two numbers.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

Returns a positive value if a > b, zero if a = b and a negative value if a < b.

Examples

Example #1 gmp_cmp() example

<?php
$cmp1 = gmp_cmp("1234", "1000"); // greater than
$cmp2 = gmp_cmp("1000", "1234"); // less than
$cmp3 = gmp_cmp("1234", "1234"); // equal to

echo "$cmp1 $cmp2 $cmp3\n";
?>

The above example will output:

1 -1 0
gmp_clrbit
gmp_com
GMP Functions


Calculates one's complement

gmp_cmp
gmp_div_q
GMP Functions
PHP Manual

gmp_com

(PHP 4 >= 4.0.4, PHP 5)

gmp_com — Calculates one's complement

Description

resource gmp_com ( resource $a )

Returns the one's complement of a .

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

Returns the one's complement of a , as a GMP number.

Examples

Example #1 gmp_com() example

<?php
$com = gmp_com("1234");
echo gmp_strval($com) . "\n";
?>

The above example will output:

-1235
gmp_cmp
gmp_div_q
GMP Functions


Alias of gmp_div_q

gmp_div_r
gmp_divexact
GMP Functions
PHP Manual

gmp_div

(PHP 4 >= 4.0.4, PHP 5)

gmp_div — Alias of gmp_div_q()

Description

This function is an alias of: gmp_div_q().

gmp_div_r
gmp_divexact
GMP Functions


Divide numbers

gmp_com
gmp_div_qr
GMP Functions
PHP Manual

gmp_div_q

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_q — Divide numbers

Description

resource gmp_div_q ( resource $a , resource $b [, int $round = GMP_ROUND_ZERO ] )

Divides a by b and returns the integer result.

Parameters

a

The number being divided.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

The number that a is being divided by.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

round

The result rounding is defined by the round , which can have the following values:

  • GMP_ROUND_ZERO: The result is truncated towards 0.
  • GMP_ROUND_PLUSINF: The result is rounded towards +infinity.
  • GMP_ROUND_MINUSINF: The result is rounded towards -infinity.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

Examples

Example #1 gmp_div_q() example

<?php
$div1 = gmp_div_q("100", "5");
echo gmp_strval($div1) . "\n";

$div2 = gmp_div_q("1", "3");
echo gmp_strval($div2) . "\n";

$div3 = gmp_div_q("1", "3", GMP_ROUND_PLUSINF);
echo gmp_strval($div3) . "\n";

$div4 = gmp_div_q("-1", "4", GMP_ROUND_PLUSINF);
echo gmp_strval($div4) . "\n";

$div5 = gmp_div_q("-1", "4", GMP_ROUND_MINUSINF);
echo gmp_strval($div5) . "\n";
?>

The above example will output:

20
0
1
0
-1

Notes

Note: This function can also be called as gmp_div().

See Also

  • gmp_div_r() - Remainder of the division of numbers
  • gmp_div_qr() - Divide numbers and get quotient and remainder

gmp_com
gmp_div_qr
GMP Functions


Divide numbers and get quotient and remainder

gmp_div_q
gmp_div_r
GMP Functions
PHP Manual

gmp_div_qr

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_qr — Divide numbers and get quotient and remainder

Description

array gmp_div_qr ( resource $n , resource $d [, int $round = GMP_ROUND_ZERO ] )

The function divides n by d .

Parameters

n

The number being divided.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

d

The number that n is being divided by.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

round

See the gmp_div_q() function for description of the round argument.

Return Values

Returns an array, with the first element being [n/d] (the integer result of the division) and the second being (n - [n/d] * d) (the remainder of the division).

Examples

Example #1 Division of GMP numbers

<?php
$a = gmp_init("0x41682179fbf5");
$res = gmp_div_qr($a, "0xDEFE75");
printf("Result is: q - %s, r - %s",
       gmp_strval($res[0]), gmp_strval($res[1]));
?>

See Also

  • gmp_div_q() - Divide numbers
  • gmp_div_r() - Remainder of the division of numbers

gmp_div_q
gmp_div_r
GMP Functions


Remainder of the division of numbers

gmp_div_qr
gmp_div
GMP Functions
PHP Manual

gmp_div_r

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_r — Remainder of the division of numbers

Description

resource gmp_div_r ( resource $n , resource $d [, int $round = GMP_ROUND_ZERO ] )

Calculates remainder of the integer division of n by d . The remainder has the sign of the n argument, if not zero.

Parameters

n

The number being divided.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

d

The number that n is being divided by.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

round

See the gmp_div_q() function for description of the round argument.

Return Values

The remainder, as a GMP number.

Examples

Example #1 gmp_div_r() example

<?php
$div = gmp_div_r("105", "20");
echo gmp_strval($div) . "\n";
?>

The above example will output:

5

See Also

  • gmp_div_q() - Divide numbers
  • gmp_div_qr() - Divide numbers and get quotient and remainder

gmp_div_qr
gmp_div
GMP Functions


Exact division of numbers

gmp_div
gmp_fact
GMP Functions
PHP Manual

gmp_divexact

(PHP 4 >= 4.0.4, PHP 5)

gmp_divexact — Exact division of numbers

Description

resource gmp_divexact ( resource $n , resource $d )

Divides n by d , using fast "exact division" algorithm. This function produces correct results only when it is known in advance that d divides n .

Parameters

n

The number being divided.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

d

The number that a is being divided by.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

Examples

Example #1 gmp_divexact() example

<?php
$div1 = gmp_divexact("10", "2");
echo gmp_strval($div1) . "\n";

$div2 = gmp_divexact("10", "3"); // bogus result
echo gmp_strval($div2) . "\n";
?>

The above example will output:

5
2863311534

gmp_div
gmp_fact
GMP Functions


Factorial

gmp_divexact
gmp_gcd
GMP Functions
PHP Manual

gmp_fact

(PHP 4 >= 4.0.4, PHP 5)

gmp_fact — Factorial

Description

resource gmp_fact ( mixed $a )

Calculates factorial (a!) of a .

Parameters

a

The factorial number.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

Examples

Example #1 gmp_fact() example

<?php
$fact1 = gmp_fact(5); // 5 * 4 * 3 * 2 * 1
echo gmp_strval($fact1) . "\n";

$fact2 = gmp_fact(50); // 50 * 49 * 48, ... etc
echo gmp_strval($fact2) . "\n";
?>

The above example will output:

120
30414093201713378043612608166064768844377641568960512000000000000

gmp_divexact
gmp_gcd
GMP Functions


Calculate GCD

gmp_fact
gmp_gcdext
GMP Functions
PHP Manual

gmp_gcd

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcd — Calculate GCD

Description

resource gmp_gcd ( resource $a , resource $b )

Calculate greatest common divisor of a and b . The result is always positive even if either of, or both, input operands are negative.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A positive GMP number that divides into both a and b .

Examples

Example #1 gmp_gcd() example

<?php
$gcd = gmp_gcd("12", "21");
echo gmp_strval($gcd) . "\n";
?>

The above example will output:

3

gmp_fact
gmp_gcdext
GMP Functions


Calculate GCD and multipliers

gmp_gcd
gmp_hamdist
GMP Functions
PHP Manual

gmp_gcdext

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcdext — Calculate GCD and multipliers

Description

array gmp_gcdext ( resource $a , resource $b )

Calculates g, s, and t, such that a*s + b*t = g = gcd(a,b), where gcd is the greatest common divisor. Returns an array with respective elements g, s and t.

This function can be used to solve linear Diophantine equations in two variables. These are equations that allow only integer solutions and have the form: a*x + b*y = c. For more information, go to the » "Diophantine Equation" page at MathWorld

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

An array of GMP numbers.

Examples

Example #1 Solving a linear Diophantine equation

<?php
// Solve the equation a*s + b*t = g
// where a = 12, b = 21, g = gcd(12, 21) = 3
$a = gmp_init(12);
$b = gmp_init(21);
$g = gmp_gcd($a, $b);
$r = gmp_gcdext($a, $b);

$check_gcd = (gmp_strval($g) == gmp_strval($r['g']));
$eq_res = gmp_add(gmp_mul($a, $r['s']), gmp_mul($b, $r['t']));
$check_res = (gmp_strval($g) == gmp_strval($eq_res));

if ($check_gcd && $check_res) {
    $fmt = "Solution: %d*%d + %d*%d = %d\n";
    printf($fmt, gmp_strval($a), gmp_strval($r['s']), gmp_strval($b),
    gmp_strval($r['t']), gmp_strval($r['g']));
} else {
    echo "Error while solving the equation\n";
}

// output: Solution: 12*2 + 21*-1 = 3
?>

gmp_gcd
gmp_hamdist
GMP Functions


Hamming distance

gmp_gcdext
gmp_init
GMP Functions
PHP Manual

gmp_hamdist

(PHP 4 >= 4.0.4, PHP 5)

gmp_hamdist — Hamming distance

Description

int gmp_hamdist ( resource $a , resource $b )

Returns the hamming distance between a and b . Both operands should be non-negative.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

It should be positive.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

It should be positive.

Return Values

A GMP number resource.

Examples

Example #1 gmp_hamdist() example

<?php
$ham1 = gmp_init("1001010011", 2);
$ham2 = gmp_init("1011111100", 2);
echo gmp_hamdist($ham1, $ham2) . "\n";

/* hamdist is equivilent to: */
echo gmp_popcount(gmp_xor($ham1, $ham2)) . "\n";
?>

The above example will output:

6
6

See Also

  • gmp_popcount() - Population count
  • gmp_xor() - Bitwise XOR

gmp_gcdext
gmp_init
GMP Functions


Create GMP number

gmp_hamdist
gmp_intval
GMP Functions
PHP Manual

gmp_init

(PHP 4 >= 4.0.4, PHP 5)

gmp_init — Create GMP number

Description

resource gmp_init ( mixed $number [, int $base = 0 ] )

Creates a GMP number from an integer or string.

Parameters

number

An integer or a string. The string representation can be decimal, hexadecimal or octal.

base

The base.

The base may vary from 2 to 36. If base is 0 (default value), the actual base is determined from the leading characters: if the first two characters are 0x or 0X, hexadecimal is assumed, otherwise if the first character is "0", octal is assumed, otherwise decimal is assumed.

Return Values

A GMP number resource.

Changelog

Version | Description
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.
4.1.0 | The optional base parameter was added.

Notes

Note: To use the extended base introduced in PHP 5.3.2, then PHP must be compiled against GMP 4.2.0 or greater.

Examples

Example #1 Creating GMP number

<?php
$a = gmp_init(123456);
$b = gmp_init("0xFFFFDEBACDFEDF7200");
?>

Notes

Note: It is not necessary to call this function if you want to use integer or string in place of GMP number in GMP functions, like gmp_add(). Function arguments are automatically converted to GMP numbers, if such conversion is possible and needed, using the same rules as gmp_init().

gmp_hamdist
gmp_intval
GMP Functions


Convert GMP number to integer

gmp_init
gmp_invert
GMP Functions
PHP Manual

gmp_intval

(PHP 4 >= 4.0.4, PHP 5)

gmp_intval — Convert GMP number to integer

Description

int gmp_intval ( resource $gmpnumber )

This function allows to convert GMP number to integer.

Parameters

gmpnumber

A GMP number.

Return Values

An integer value of gmpnumber .

Examples

Example #1 gmp_intval() example

<?php
// displays correct result
echo gmp_intval("2147483647") . "\n";

// displays wrong result, above PHP integer limit
echo gmp_intval("2147483648") . "\n";

// displays correct result
echo gmp_strval("2147483648") . "\n";
?>

The above example will output:

2147483647
2147483647
2147483648

Notes

Warning

This function returns a useful result only if the number actually fits the PHP integer (i.e., signed long type). If you want just to print the GMP number, use gmp_strval().

gmp_init
gmp_invert
GMP Functions


Inverse by modulo

gmp_intval
gmp_jacobi
GMP Functions
PHP Manual

gmp_invert

(PHP 4 >= 4.0.4, PHP 5)

gmp_invert — Inverse by modulo

Description

resource gmp_invert ( resource $a , resource $b )

Computes the inverse of a modulo b .

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number on success or FALSE if an inverse does not exist.

Examples

Example #1 gmp_invert() example

<?php
echo gmp_invert("5", "10"); // no inverse, outputs nothing, result is FALSE
$invert = gmp_invert("5", "11");
echo gmp_strval($invert) . "\n";
?>

The above example will output:

9

gmp_intval
gmp_jacobi
GMP Functions


Jacobi symbol

gmp_invert
gmp_legendre
GMP Functions
PHP Manual

gmp_jacobi

(PHP 4 >= 4.0.4, PHP 5)

gmp_jacobi — Jacobi symbol

Description

int gmp_jacobi ( resource $a , resource $p )

Computes » Jacobi symbol of a and p . p should be odd and must be positive.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

p

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Should be odd and must be positive.

Return Values

A GMP number resource.

Examples

Example #1 gmp_jacobi() example

<?php
echo gmp_jacobi("1", "3") . "\n";
echo gmp_jacobi("2", "3") . "\n";
?>

The above example will output:

1
0

gmp_invert
gmp_legendre
GMP Functions


Legendre symbol

gmp_jacobi
gmp_mod
GMP Functions
PHP Manual

gmp_legendre

(PHP 4 >= 4.0.4, PHP 5)

gmp_legendre — Legendre symbol

Description

int gmp_legendre ( resource $a , resource $p )

Compute the » Legendre symbol of a and p . p should be odd and must be positive.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

p

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Should be odd and must be positive.

Return Values

A GMP number resource.

Examples

Example #1 gmp_legendre() example

<?php
echo gmp_legendre("1", "3") . "\n";
echo gmp_legendre("2", "3") . "\n";
?>

The above example will output:

1
0

gmp_jacobi
gmp_mod
GMP Functions


Modulo operation

gmp_legendre
gmp_mul
GMP Functions
PHP Manual

gmp_mod

(PHP 4 >= 4.0.4, PHP 5)

gmp_mod — Modulo operation

Description

resource gmp_mod ( resource $n , resource $d )

Calculates n modulo d . The result is always non-negative, the sign of d is ignored.

Parameters

n

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

d

The modulo that is being evaluated.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

Examples

Example #1 gmp_mod() example

<?php
$mod = gmp_mod("8", "3");
echo gmp_strval($mod) . "\n";
?>

The above example will output:

2

gmp_legendre
gmp_mul
GMP Functions


Multiply numbers

gmp_mod
gmp_neg
GMP Functions
PHP Manual

gmp_mul

(PHP 4 >= 4.0.4, PHP 5)

gmp_mul — Multiply numbers

Description

resource gmp_mul ( resource $a , resource $b )

Multiplies a by b and returns the result.

Parameters

a

A number that will be multiplied by b .

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

A number that will be multiplied by a .

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

Examples

Example #1 gmp_mul() example

<?php
$mul = gmp_mul("12345678", "2000");
echo gmp_strval($mul) . "\n";
?>

The above example will output:

24691356000

gmp_mod
gmp_neg
GMP Functions


Negate number

gmp_mul
gmp_nextprime
GMP Functions
PHP Manual

gmp_neg

(PHP 4 >= 4.0.4, PHP 5)

gmp_neg — Negate number

Description

resource gmp_neg ( resource $a )

Returns the negative value of a number.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

Returns -a , as a GMP number.

Examples

Example #1 gmp_neg() example

<?php
$neg1 = gmp_neg("1");
echo gmp_strval($neg1) . "\n";
$neg2 = gmp_neg("-1");
echo gmp_strval($neg2) . "\n";
?>

The above example will output:

-1
1

gmp_mul
gmp_nextprime
GMP Functions


Find next prime number

gmp_neg
gmp_or
GMP Functions
PHP Manual

gmp_nextprime

(PHP 5 >= 5.2.0)

gmp_nextprime — Find next prime number

Description

resource gmp_nextprime ( int $a )

Find next prime number

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

Return the next prime number greater than a , as a GMP number.

Examples

Example #1 gmp_nextprime() example

<?php
$prime1 = gmp_nextprime(10); // next prime number greater than 10
$prime2 = gmp_nextprime(-1000); // next prime number greater than -1000

echo gmp_strval($prime1) . "\n";
echo gmp_strval($prime2) . "\n";
?>

The above example will output:

11
-997

Notes

Note: This function uses a probabilistic algorithm to identify primes and chances to get a composite number are extremely small.

gmp_neg
gmp_or
GMP Functions


Bitwise OR

gmp_nextprime
gmp_perfect_square
GMP Functions
PHP Manual

gmp_or

(PHP 4 >= 4.0.4, PHP 5)

gmp_or — Bitwise OR

Description

resource gmp_or ( resource $a , resource $b )

Calculates bitwise inclusive OR of two GMP numbers.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

Examples

Example #1 gmp_or() example

<?php
$or1 = gmp_or("0xfffffff2", "4");
echo gmp_strval($or1, 16) . "\n";
$or2 = gmp_or("0xfffffff2", "2");
echo gmp_strval($or2, 16) . "\n";
?>

The above example will output:

fffffff6
fffffff2

gmp_nextprime
gmp_perfect_square
GMP Functions


Perfect square check

gmp_or
gmp_popcount
GMP Functions
PHP Manual

gmp_perfect_square

(PHP 4 >= 4.0.4, PHP 5)

gmp_perfect_square — Perfect square check

Description

bool gmp_perfect_square ( resource $a )

Check if a number is a perfect square.

Parameters

a

The number being checked as a perfect square.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

Returns TRUE if a is a perfect square, FALSE otherwise.

Examples

Example #1 gmp_perfect_square() example

<?php
// 3 * 3, perfect square
var_dump(gmp_perfect_square("9"));

// not a perfect square
var_dump(gmp_perfect_square("7"));

// 1234567890 * 1234567890, perfect square
var_dump(gmp_perfect_square("1524157875019052100"));
?>

The above example will output:

bool(true)
bool(false)
bool(true)

See Also

  • gmp_sqrt() - Calculate square root
  • gmp_sqrtrem() - Square root with remainder

gmp_or
gmp_popcount
GMP Functions


Population count

gmp_perfect_square
gmp_pow
GMP Functions
PHP Manual

gmp_popcount

(PHP 4 >= 4.0.4, PHP 5)

gmp_popcount — Population count

Description

int gmp_popcount ( resource $a )

Get the population count.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

The population count of a , as an integer.

Examples

Example #1 gmp_popcount() example

<?php
$pop1 = gmp_init("10000101", 2); // 3 1's
echo gmp_popcount($pop1) . "\n";
$pop2 = gmp_init("11111110", 2); // 7 1's
echo gmp_popcount($pop2) . "\n";
?>

The above example will output:

3
7

gmp_perfect_square
gmp_pow
GMP Functions


Raise number into power

gmp_popcount
gmp_powm
GMP Functions
PHP Manual

gmp_pow

(PHP 4 >= 4.0.4, PHP 5)

gmp_pow — Raise number into power

Description

resource gmp_pow ( resource $base , int $exp )

Raise base into power exp .

Parameters

base

The base number.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

exp

The positive power to raise the base .

Return Values

The new (raised) number, as a GMP number. The case of 0^0 yields 1.

Examples

Example #1 gmp_pow() example

<?php
$pow1 = gmp_pow("2", 31);
echo gmp_strval($pow1) . "\n";
$pow2 = gmp_pow("0", 0);
echo gmp_strval($pow2) . "\n";
$pow3 = gmp_pow("2", -1); // Negative exp, generates warning
echo gmp_strval($pow3) . "\n";
?>

The above example will output:

2147483648
1

gmp_popcount
gmp_powm
GMP Functions


Raise number into power with modulo

gmp_pow
gmp_prob_prime
GMP Functions
PHP Manual

gmp_powm

(PHP 4 >= 4.0.4, PHP 5)

gmp_powm — Raise number into power with modulo

Description

resource gmp_powm ( resource $base , resource $exp , resource $mod )

Calculate (base raised into power exp ) modulo mod . If exp is negative, result is undefined.

Parameters

base

The base number.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

exp

The positive power to raise the base .

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

mod

The modulo.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

The new (raised) number, as a GMP number.

Examples

Example #1 gmp_powm() example

<?php
$pow1 = gmp_powm("2", "31", "2147483649");
echo gmp_strval($pow1) . "\n";
?>

The above example will output:

2147483648

gmp_pow
gmp_prob_prime
GMP Functions


Check if number is "probably prime"

gmp_powm
gmp_random
GMP Functions
PHP Manual

gmp_prob_prime

(PHP 4 >= 4.0.4, PHP 5)

gmp_prob_prime — Check if number is "probably prime"

Description

int gmp_prob_prime ( resource $a [, int $reps = 10 ] )

The function uses Miller-Rabin's probabilistic test to check if a number is a prime.

Parameters

a

The number being checked as a prime.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

reps

Reasonable values of reps vary from 5 to 10 (default being 10); a higher value lowers the probability for a non-prime to pass as a "probable" prime.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

If this function returns 0, a is definitely not prime. If it returns 1, then a is "probably" prime. If it returns 2, then a is surely prime.

Examples

Example #1 gmp_prob_prime() example

<?php
// definitely not a prime
echo gmp_prob_prime("6") . "\n";

// probably a prime
echo gmp_prob_prime("1111111111111111111") . "\n";

// definitely a prime
echo gmp_prob_prime("11") . "\n";
?>

The above example will output:

0
1
2

gmp_powm
gmp_random
GMP Functions


Random number

gmp_prob_prime
gmp_scan0
GMP Functions
PHP Manual

gmp_random

(PHP 4 >= 4.0.4, PHP 5)

gmp_random — Random number

Description

resource gmp_random ([ int $limiter = 20 ] )

Generate a random number. The number will be between zero and the number of bits per limb multiplied by limiter . If limiter is negative, negative numbers are generated.

A limb is an internal GMP mechanism. The number of bits in a limb is not static, and can vary from system to system. Generally, the number of bits in a limb is either 16 or 32, but this is not guaranteed.

Parameters

limiter

The limiter.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A random GMP number.

Examples

Example #1 gmp_random() example

<?php
$rand1 = gmp_random(1); // random number from 0 to 1 * bits per limb
$rand2 = gmp_random(2); // random number from 0 to 2 * bits per limb

echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>

The above example will output:

1915834968
8642564075890328087

gmp_prob_prime
gmp_scan0
GMP Functions


Scan for 0

gmp_random
gmp_scan1
GMP Functions
PHP Manual

gmp_scan0

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan0 — Scan for 0

Description

int gmp_scan0 ( resource $a , int $start )

Scans a , starting with bit start , towards more significant bits, until the first clear bit is found.

Parameters

a

The number to scan.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

start

The starting bit.

Return Values

Returns the index of the found bit, as an integer. The index starts from 0.

Examples

Example #1 gmp_scan0() example

<?php
// "0" bit is found at position 3. index starts at 0
$s1 = gmp_init("10111", 2);
echo gmp_scan0($s1, 0) . "\n";

// "0" bit is found at position 7. index starts at 5
$s2 = gmp_init("101110000", 2);
echo gmp_scan0($s2, 5) . "\n";
?>

The above example will output:

3
7

gmp_random
gmp_scan1
GMP Functions


Scan for 1

gmp_scan0
gmp_setbit
GMP Functions
PHP Manual

gmp_scan1

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan1 — Scan for 1

Description

int gmp_scan1 ( resource $a , int $start )

Scans a , starting with bit start , towards more significant bits, until the first set bit is found.

Parameters

a

The number to scan.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

start

The starting bit.

Return Values

Returns the index of the found bit, as an integer. If no set bit is found, -1 is returned.

Examples

Example #1 gmp_scan1() example

<?php
// "1" bit is found at position 3. index starts at 0
$s1 = gmp_init("01000", 2);
echo gmp_scan1($s1, 0) . "\n";

// "1" bit is found at position 9. index starts at 5
$s2 = gmp_init("01000001111", 2);
echo gmp_scan1($s2, 5) . "\n";
?>

The above example will output:

3
9

gmp_scan0
gmp_setbit
GMP Functions


Set bit

gmp_scan1
gmp_sign
GMP Functions
PHP Manual

gmp_setbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_setbit — Set bit

Description

void gmp_setbit ( resource $a , int $index [, bool $set_clear = true ] )

Sets bit index in a .

Parameters

a

The number being set to.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

index

The set bit.

set_clear

Defines if the bit is set to 0 or 1. By default the bit is set to 1. Index starts at 0.

Return Values

A GMP number resource.

Examples

Example #1 gmp_setbit() example

<?php
$a = gmp_init("0xfd");
gmp_setbit($a, 1); // index starts at 0
echo gmp_strval($a) . "\n";
?>

The above example will output:

255

Notes

Note: Unlike most of the other GMP functions, gmp_setbit() must be called with a GMP resource that already exists (using gmp_init() for example). One will not be automatically created.

See Also

  • gmp_clrbit() - Clear bit
  • gmp_testbit() - Tests if a bit is set

gmp_scan1
gmp_sign
GMP Functions


Sign of number

gmp_setbit
gmp_sqrt
GMP Functions
PHP Manual

gmp_sign

(PHP 4 >= 4.0.4, PHP 5)

gmp_sign — Sign of number

Description

int gmp_sign ( resource $a )

Checks the sign of a number.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

Returns 1 if a is positive, -1 if a is negative, and 0 if a is zero.

Examples

Example #1 gmp_sign() example

<?php
// positive
echo gmp_sign("500") . "\n";

// negative
echo gmp_sign("-500") . "\n";

// zero
echo gmp_sign("0") . "\n";
?>

The above example will output:

1
-1
0

gmp_setbit
gmp_sqrt
GMP Functions


Calculate square root

gmp_sign
gmp_sqrtrem
GMP Functions
PHP Manual

gmp_sqrt

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrt — Calculate square root

Description

resource gmp_sqrt ( resource $a )

Calculates square root of a .

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

The integer portion of the square root, as a GMP number.

Examples

Example #1 gmp_sqrt() example

<?php
$sqrt1 = gmp_sqrt("9");
$sqrt2 = gmp_sqrt("7");
$sqrt3 = gmp_sqrt("1524157875019052100");

echo gmp_strval($sqrt1) . "\n";
echo gmp_strval($sqrt2) . "\n";
echo gmp_strval($sqrt3) . "\n";
?>

The above example will output:

3
2
1234567890

gmp_sign
gmp_sqrtrem
GMP Functions


Square root with remainder

gmp_sqrt
gmp_strval
GMP Functions
PHP Manual

gmp_sqrtrem

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrtrem — Square root with remainder

Description

array gmp_sqrtrem ( resource $a )

Calculate the square root of a number, with remainder.

Parameters

a

The number being square rooted.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

Returns array where first element is the integer square root of a and the second is the remainder (i.e., the difference between a and the first element squared).

Examples

Example #1 gmp_sqrtrem() example

<?php
list($sqrt1, $sqrt1rem) = gmp_sqrtrem("9");
list($sqrt2, $sqrt2rem) = gmp_sqrtrem("7");
list($sqrt3, $sqrt3rem) = gmp_sqrtrem("1048576");

echo gmp_strval($sqrt1) . ", " . gmp_strval($sqrt1rem) . "\n";
echo gmp_strval($sqrt2) . ", " . gmp_strval($sqrt2rem) . "\n";
echo gmp_strval($sqrt3) . ", " . gmp_strval($sqrt3rem) . "\n";
?>

The above example will output:

3, 0
2, 3
1024, 0

gmp_sqrt
gmp_strval
GMP Functions


Convert GMP number to string

gmp_sqrtrem
gmp_sub
GMP Functions
PHP Manual

gmp_strval

(PHP 4 >= 4.0.4, PHP 5)

gmp_strval — Convert GMP number to string

Description

string gmp_strval ( resource $gmpnumber [, int $base ] )

Convert GMP number to string representation in base base . The default base is 10.

Parameters

gmpnumber

The GMP number that will be converted to a string.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

base

The base of the returned number. The default base is 10. Allowed values for the base are from 2 to 62 and -2 to -36.

Return Values

The number, as a string.

Changelog

Version | Description
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.

Notes

Note: To use the extended base introduced in PHP 5.3.2, then PHP must be compiled against GMP 4.2.0 or greater.

Examples

Example #1 Converting a GMP number to a string

<?php
$a = gmp_init("0x41682179fbf5");
printf("Decimal: %s, 36-based: %s", gmp_strval($a), gmp_strval($a,36));
?>

gmp_sqrtrem
gmp_sub
GMP Functions


Subtract numbers

gmp_strval
gmp_testbit
GMP Functions
PHP Manual

gmp_sub

(PHP 4 >= 4.0.4, PHP 5)

gmp_sub — Subtract numbers

Description

resource gmp_sub ( resource $a , resource $b )

Subtracts b from a and returns the result.

Parameters

a

The number being subtracted from.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

The number subtracted from a .

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

Examples

Example #1 gmp_sub() example

<?php
$sub = gmp_sub("281474976710656", "4294967296"); // 2^48 - 2^32
echo gmp_strval($sub) . "\n";
?>

The above example will output:

281470681743360

gmp_strval
gmp_testbit
GMP Functions


Tests if a bit is set

gmp_sub
gmp_xor
GMP Functions
PHP Manual

gmp_testbit

(PHP 5 >= 5.3.0)

gmp_testbit — Tests if a bit is set

Description

bool gmp_testbit ( resource $a , int $index )

Tests if the specified bit is set.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

index

The bit to test

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

E_WARNING is issued when index is less than zero.

Examples

Example #1 gmp_testbit() example

<?php
$n = gmp_init("1000000");
var_dump(gmp_testbit($n, 1));
gmp_setbit($n, 1);
var_dump(gmp_testbit($n, 1));
?>

The above example will output:

bool(false)
bool(true)

See Also

  • gmp_setbit() - Set bit
  • gmp_clrbit() - Clear bit

gmp_sub
gmp_xor
GMP Functions


Bitwise XOR

gmp_testbit
Math
GMP Functions
PHP Manual

gmp_xor

(PHP 4 >= 4.0.4, PHP 5)

gmp_xor — Bitwise XOR

Description

resource gmp_xor ( resource $a , resource $b )

Calculates bitwise exclusive OR (XOR) of two GMP numbers.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

Examples

Example #1 gmp_xor() example

<?php
$xor1 = gmp_init("1101101110011101", 2);
$xor2 = gmp_init("0110011001011001", 2);

$xor3 = gmp_xor($xor1, $xor2);

echo gmp_strval($xor3, 2) . "\n";
?>

The above example will output:

1011110111000100

gmp_testbit
Math
GMP Functions


Format a GMT/UTC time/date according to locale settings

gmmktime
idate
Date/Time Functions
PHP Manual

gmstrftime

(PHP 4, PHP 5)

gmstrftime — Format a GMT/UTC time/date according to locale settings

Description

string gmstrftime ( string $format [, int $timestamp = time() ] )

Behaves the same as strftime() except that the time returned is Greenwich Mean Time (GMT). For example, when run in Eastern Standard Time (GMT -0500), the first line below prints "Dec 31 1998 20:00:00", while the second prints "Jan 01 1999 01:00:00".

Parameters

format

See description in strftime().

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a string formatted according to the given format string using the given timestamp or the current local time if no timestamp is given. Month and weekday names and other language dependent strings respect the current locale set with setlocale().

Examples

Example #1 gmstrftime() example

<?php
setlocale(LC_TIME, 'en_US');
echo strftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";
echo gmstrftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";
?>

See Also

  • strftime() - Format a local time/date according to locale settings

gmmktime
idate
Date/Time Functions


Add a key for decryption

GnuPG Functions
gnupg_addencryptkey
GnuPG Functions
PHP Manual

gnupg_adddecryptkey

(PECL gnupg >= 0.5)

gnupg_adddecryptkey — Add a key for decryption

Description

bool gnupg_adddecryptkey ( resource $identifier , string $fingerprint , string $passphrase )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

fingerprint

The fingerprint key.

passphrase

The pass phrase.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_adddecryptkey() example

<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

Example #2 OO gnupg_adddecryptkey() example

<?php
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

GnuPG Functions
gnupg_addencryptkey
GnuPG Functions


Add a key for encryption

gnupg_adddecryptkey
gnupg_addsignkey
GnuPG Functions
PHP Manual

gnupg_addencryptkey

(PECL gnupg >= 0.5)

gnupg_addencryptkey — Add a key for encryption

Description

bool gnupg_addencryptkey ( resource $identifier , string $fingerprint )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

fingerprint

The fingerprint key.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_addencryptkey() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
?>

Example #2 OO gnupg_addencryptkey() example

<?php
$gpg = new gnupg();
$gpg -> addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
?>

gnupg_adddecryptkey
gnupg_addsignkey
GnuPG Functions


Add a key for signing

gnupg_addencryptkey
gnupg_cleardecryptkeys
GnuPG Functions
PHP Manual

gnupg_addsignkey

(PECL gnupg >= 0.5)

gnupg_addsignkey — Add a key for signing

Description

bool gnupg_addsignkey ( resource $identifier , string $fingerprint [, string $passphrase ] )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

fingerprint

The fingerprint key.

passphrase

The pass phrase.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_addsignkey() example

<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

Example #2 OO gnupg_addsignkey() example

<?php
$gpg = new gnupg();
$gpg -> addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

gnupg_addencryptkey
gnupg_cleardecryptkeys
GnuPG Functions


Removes all keys which were set for decryption before

gnupg_addsignkey
gnupg_clearencryptkeys
GnuPG Functions
PHP Manual

gnupg_cleardecryptkeys

(PECL gnupg >= 0.5)

gnupg_cleardecryptkeys — Removes all keys which were set for decryption before

Description

bool gnupg_cleardecryptkeys ( resource $identifier )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_cleardecryptkeys() example

<?php
$res = gnupg_init();
gnupg_cleardecryptkeys($res);
?>

Example #2 OO gnupg_cleardecryptkeys() example

<?php
$gpg = new gnupg();
$gpg -> cleardecryptkeys();
?>

gnupg_addsignkey
gnupg_clearencryptkeys
GnuPG Functions


Removes all keys which were set for encryption before

gnupg_cleardecryptkeys
gnupg_clearsignkeys
GnuPG Functions
PHP Manual

gnupg_clearencryptkeys

(PECL gnupg >= 0.5)

gnupg_clearencryptkeys — Removes all keys which were set for encryption before

Description

bool gnupg_clearencryptkeys ( resource $identifier )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_clearencryptkeys() example

<?php
$res = gnupg_init();
gnupg_clearencryptkeys($res);
?>

Example #2 OO gnupg_clearencryptkeys() example

<?php
$gpg = new gnupg();
$gpg -> clearencryptkeys();
?>

gnupg_cleardecryptkeys
gnupg_clearsignkeys
GnuPG Functions


Removes all keys which were set for signing before

gnupg_clearencryptkeys
gnupg_decrypt
GnuPG Functions
PHP Manual

gnupg_clearsignkeys

(PECL gnupg >= 0.5)

gnupg_clearsignkeys — Removes all keys which were set for signing before

Description

bool gnupg_clearsignkeys ( resource $identifier )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_clearsignkeys() example

<?php
$res = gnupg_init();
gnupg_clearsignkeys($res);
?>

Example #2 OO gnupg_clearsignkeys() example

<?php
$gpg = new gnupg();
$gpg -> clearsignkeys();
?>

gnupg_clearencryptkeys
gnupg_decrypt
GnuPG Functions


Decrypts a given text

gnupg_clearsignkeys
gnupg_decryptverify
GnuPG Functions
PHP Manual

gnupg_decrypt

(PECL gnupg >= 0.1)

gnupg_decrypt — Decrypts a given text

Description

string gnupg_decrypt ( resource $identifier , string $text )

Decrypts the given text with the keys, which were set with gnupg_adddecryptkey before.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

text

The text being decrypted.

Return Values

On success, this function returns the decrypted text. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_decrypt() example

<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = gnupg_decrypt($res,$encrypted_text);
echo $plain;
?>

Example #2 OO gnupg_encrypt() example

<?php
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = $gpg -> decrypt($encrypted_text);
echo $plain;
?>

gnupg_clearsignkeys
gnupg_decryptverify
GnuPG Functions


Decrypts and verifies a given text

gnupg_decrypt
gnupg_encrypt
GnuPG Functions
PHP Manual

gnupg_decryptverify

(PECL gnupg >= 0.2)

gnupg_decryptverify — Decrypts and verifies a given text

Description

array gnupg_decryptverify ( resource $identifier , string $text , string &$plaintext )

Decrypts and verifies a given text and returns information about the signature.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

text

The text being decrypted.

plaintext

The parameter plaintext gets filled with the decrypted text.

Return Values

On success, this function returns information about the signature and fills the plaintext parameter with the decrypted text. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_decryptverify() example

<?php
$plaintext = "";
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = gnupg_decryptverify($res,$text,$plaintext);
print_r($info);
?>

Example #2 OO gnupg_decryptverify() example

<?php
$plaintext = "";
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = $gpg -> decryptverify($text,$plaintext);
print_r($info);
?>

gnupg_decrypt
gnupg_encrypt
GnuPG Functions


Encrypts a given text

gnupg_decryptverify
gnupg_encryptsign
GnuPG Functions
PHP Manual

gnupg_encrypt

(PECL gnupg >= 0.1)

gnupg_encrypt — Encrypts a given text

Description

string gnupg_encrypt ( resource $identifier , string $plaintext )

Encrypts the given plaintext with the keys, which were set with gnupg_addencryptkey before and returns the encrypted text.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

plaintext

The text being encrypted.

Return Values

On success, this function returns the encrypted text. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_encrypt() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
$enc = gnupg_encrypt($res, "just a test");
echo $enc;
?>

Example #2 OO gnupg_encrypt() example

<?php
$gpg = new gnupg();
$gpg -> addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$enc = $gpg -> encrypt("just a test");
echo $enc;
?>

gnupg_decryptverify
gnupg_encryptsign
GnuPG Functions


Encrypts and signs a given text

gnupg_encrypt
gnupg_export
GnuPG Functions
PHP Manual

gnupg_encryptsign

(PECL gnupg >= 0.2)

gnupg_encryptsign — Encrypts and signs a given text

Description

string gnupg_encryptsign ( resource $identifier , string $plaintext )

Encrypts and signs the given plaintext with the keys, which were set with gnupg_addsignkey and gnupg_addencryptkey before and returns the encrypted and signed text.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

plaintext

The text being encrypted.

Return Values

On success, this function returns the encrypted and signed text. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_encryptsign() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = gnupg_encryptsign($res, "just a test");
echo $enc;
?>

Example #2 OO gnupg_encryptsign() example

<?php
$gpg = new gnupg();
$gpg -> addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$gpg -> addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = $gpg -> encryptsign("just a test");
echo $enc;
?>

gnupg_encrypt
gnupg_export
GnuPG Functions


Exports a key

gnupg_encryptsign
gnupg_geterror
GnuPG Functions
PHP Manual

gnupg_export

(PECL gnupg >= 0.1)

gnupg_export — Exports a key

Description

string gnupg_export ( resource $identifier , string $fingerprint )

Exports the key fingerprint .

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

fingerprint

The fingerprint key.

Return Values

On success, this function returns the keydata. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_export() example

<?php
$res = gnupg_init();
$export = gnupg_export($res,"8660281B6051D071D94B5B230549F9DC851566DC");
echo $export;
?>

Example #2 OO gnupg_export() example

<?php
$gpg = new gnupg();
$export = $gpg -> export("8660281B6051D071D94B5B230549F9DC851566DC");
?>

gnupg_encryptsign
gnupg_geterror
GnuPG Functions


Returns the errortext, if a function fails

gnupg_export
gnupg_getprotocol
GnuPG Functions
PHP Manual

gnupg_geterror

(PECL gnupg >= 0.1)

gnupg_geterror — Returns the errortext, if a function fails

Description

string gnupg_geterror ( resource $identifier )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

Return Values

Returns an errortext, if an error has occurred, otherwise FALSE.

Examples

Example #1 Procedural gnupg_geterror() example

<?php
$res = gnupg_init();
echo gnupg_geterror($res);
?>

Example #2 OO gnupg_geterror() example

<?php
$gpg = new gnupg();
echo $gpg -> geterror();
?>

gnupg_export
gnupg_getprotocol
GnuPG Functions


Returns the currently active protocol for all operations

gnupg_geterror
gnupg_import
GnuPG Functions
PHP Manual

gnupg_getprotocol

(PECL gnupg >= 0.1)

gnupg_getprotocol — Returns the currently active protocol for all operations

Description

int gnupg_getprotocol ( resource $identifier )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

Return Values

Returns the currently active protocol, which can be one of GNUPG_PROTOCOL_OpenPGP or GNUPG_PROTOCOL_CMS.

Examples

Example #1 Procedural gnupg_getprotocol() example

<?php
$res = gnupg_init();
echo gnupg_getprotocol($res);
?>

Example #2 OO gnupg_getprotocol() example

<?php
$gpg = new gnupg();
echo $gpg -> getprotocol();
?>

gnupg_geterror
gnupg_import
GnuPG Functions


Imports a key

gnupg_getprotocol
gnupg_init
GnuPG Functions
PHP Manual

gnupg_import

(PECL gnupg >= 0.3)

gnupg_import — Imports a key

Description

array gnupg_import ( resource $identifier , string $keydata )

Imports the key keydata and returns an array with information about the importprocess.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

keydata

The data key that is being imported.

Return Values

On success, this function returns and info-array about the importprocess. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_import() example

<?php
$res = gnupg_init();
$info = gnupg_import($res,$keydata);
print_r($info);
?>

Example #2 OO gnupg_import() example

<?php
$gpg = new gnupg();
$info = $gpg -> import($keydata);
print_r($info);
?>

gnupg_getprotocol
gnupg_init
GnuPG Functions


Initialize a connection

gnupg_import
gnupg_keyinfo
GnuPG Functions
PHP Manual

gnupg_init

(PECL gnupg >= 0.4)

gnupg_init — Initialize a connection

Description

resource gnupg_init ( void )

Parameters

This function has no parameters.

Return Values

A GnuPG resource connection used by other GnuPG functions.

Examples

Example #1 Procedural gnupg_init() example

<?php
$res = gnupg_init();
?>

Example #2 OO gnupg initializer example

<?php
$gpg = new gnupg();
?>

gnupg_import
gnupg_keyinfo
GnuPG Functions


Returns an array with information about all keys that matches the given pattern

gnupg_init
gnupg_setarmor
GnuPG Functions
PHP Manual

gnupg_keyinfo

(PECL gnupg >= 0.1)

gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern

Description

array gnupg_keyinfo ( resource $identifier , string $pattern )

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

pattern

The pattern being checked against the keys.

Return Values

Returns an array with information about all keys that matches the given pattern or FALSE, if an error has occurred.

Examples

Example #1 Procedural gnupg_keyinfo() example

<?php
$res = gnupg_init();
$info = gnupg_keyinfo($res, 'test');
print_r($info);
?>

Example #2 OO gnupg_keyinfo() example

<?php
$gpg = new gnupg();
$info = $gpg -> keyinfo("test");
print_r($info);
?>

gnupg_init
gnupg_setarmor
GnuPG Functions


Toggle armored output

gnupg_keyinfo
gnupg_seterrormode
GnuPG Functions
PHP Manual

gnupg_setarmor

(PECL gnupg >= 0.1)

gnupg_setarmor — Toggle armored output

Description

bool gnupg_setarmor ( resource $identifier , int $armor )

Toggle the armored output.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

armor

Pass a non-zero integer-value to this function to enable armored-output (default). Pass 0 to disable armored output.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_setarmor() example

<?php
$res = gnupg_init();
gnupg_setarmor($res,1); // enable armored output;
gnupg_setarmor($res,0); // disable armored output;
?>

Example #2 OO gnupg_setarmor() example

<?php
$gpg = new gnupg();
$gpg -> setarmor(1); // enable armored output;
$gpg -> setarmor(0); // disable armored output;
?>

gnupg_keyinfo
gnupg_seterrormode
GnuPG Functions


Sets the mode for error_reporting

gnupg_setarmor
gnupg_setsignmode
GnuPG Functions
PHP Manual

gnupg_seterrormode

(PECL gnupg >= 0.6)

gnupg_seterrormode — Sets the mode for error_reporting

Description

void gnupg_seterrormode ( resource $identifier , int $errormode )

Sets the mode for error_reporting.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

errormode

The error mode.

errormode takes a constant indicating what type of error_reporting should be used. The possible values are GNUPG_ERROR_WARNING, GNUPG_ERROR_EXCEPTION and GNUPG_ERROR_SILENT. By default GNUPG_ERROR_SILENT is used.

Return Values

No value is returned.

Examples

Example #1 Procedural gnupg_seterrormode() example

<?php
$res = gnupg_init();
gnupg_seterrormode($res,GNUPG_ERROR_WARNING); // raise a PHP-Warning in case of an error
?>

Example #2 OO gnupg_seterrormode() example

<?php
$gpg = new gnupg();
$gpg -> seterrormode(gnupg::ERROR_EXCEPTION); // throw an exception in case of an error
?>

gnupg_setarmor
gnupg_setsignmode
GnuPG Functions


Sets the mode for signing

gnupg_seterrormode
gnupg_sign
GnuPG Functions
PHP Manual

gnupg_setsignmode

(PECL gnupg >= 0.1)

gnupg_setsignmode — Sets the mode for signing

Description

bool gnupg_setsignmode ( resource $identifier , int $signmode )

Sets the mode for signing.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

sigmode

The mode for signing.

signmode takes a constant indicating what type of signature should be produced. The possible values are GNUPG_SIG_MODE_NORMAL, GNUPG_SIG_MODE_DETACH and GNUPG_SIG_MODE_CLEAR. By default GNUPG_SIG_MODE_CLEAR is used.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural gnupg_setsignmode() example

<?php
$res = gnupg_init();
gnupg_setsignmode($res,GNUPG_SIG_MODE_DETACH); // produce a detached signature
?>

Example #2 OO gnupg_setsignmode() example

<?php
$gpg = new gnupg();
$gpg -> setsignmode(gnupg::SIG_MODE_DETACH); // produce a detached signature
?>

gnupg_seterrormode
gnupg_sign
GnuPG Functions


Signs a given text

gnupg_setsignmode
gnupg_verify
GnuPG Functions
PHP Manual

gnupg_sign

(PECL gnupg >= 0.1)

gnupg_sign — Signs a given text

Description

string gnupg_sign ( resource $identifier , string $plaintext )

Signs the given plaintext with the keys, which were set with gnupg_addsignkey before and returns the signed text or the signature, depending on what was set with gnupg_setsignmode.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

plaintext

The plain text being signed.

Return Values

On success, this function returns the signed text or the signature. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_sign() example

<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = gnupg_sign($res, "just a test");
echo $signed;
?>

Example #2 OO gnupg_sign() example

<?php
$gpg = new gnupg();
$gpg -> setsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = $gpg -> sign("just a test");
echo $signed;
?>

gnupg_setsignmode
gnupg_verify
GnuPG Functions


Verifies a signed text

gnupg_sign
haru
GnuPG Functions
PHP Manual

gnupg_verify

(PECL gnupg >= 0.1)

gnupg_verify — Verifies a signed text

Description

array gnupg_verify ( resource $identifier , string $signed_text , string $signature [, string &$plaintext ] )

Verifies the given signed_text and returns information about the signature.

Parameters

identifier

The gnupg identifier, from a call to gnupg_init() or gnupg.

signed_text

The signed text.

signature

The signature. To verify a clearsigned text, set signature to FALSE.

plaintext

The plain text. If this optional parameter is passed, it is filled with the plain text.

Return Values

On success, this function returns information about the signature. On failure, this function returns FALSE.

Examples

Example #1 Procedural gnupg_verify() example

<?php
$plaintext = "";
$res = gnupg_init();
// clearsigned
$info = gnupg_verify($res,$signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = gnupg_verify($res,$signed_text,$signature);
print_r($info);
?>

Example #2 OO gnupg_verify() example

<?php
$plaintext = "";
$gpg = new gnupg();
// clearsigned
$info = $gpg -> verify($signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = $gpg -> verify($signed_text,$signature);
print_r($info);
?>

gnupg_sign
haru
GnuPG Functions


Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

Grapheme Functions
grapheme_stripos
Grapheme Functions
PHP Manual

grapheme_extract

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

Description

Procedural style

string grapheme_extract ( string $haystack , int $size [, int $extract_type [, int $start = 0 [, int &$next ]]] )

Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

Parameters

haystack

String to search.

size

Maximum number items - based on the $extract_type - to return.

extract_type

Defines the type of units referred to by the $size parameter:

  • GRAPHEME_EXTR_COUNT (default) - $size is the number of default grapheme clusters to extract.
  • GRAPHEME_EXTR_MAXBYTES - $size is the maximum number of bytes returned.
  • GRAPHEME_EXTR_MAXCHARS - $size is the maximum number of UTF-8 characters returned.

start

Starting position in $haystack in bytes - if given, it must be zero or a positive value that is less than or equal to the length of $haystack in bytes. If $start does not point to the first byte of a UTF-8 character, the start position is moved to the next character boundary.

next

Reference to a value that will be set to the next starting position. When the call returns, this may point to the first byte position past the end of the string.

Return Values

A string starting at offset $start and ending on a default grapheme cluster boundary that conforms to the $size and $extract_type specified.

Examples

Example #1 grapheme_extract() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_extract( $char_a_ring_nfd . $char_o_diaeresis_nfd, 1, GRAPHEME_EXTR_COUNT, 2));

?>

The above example will output:

o%CC%88

See Also

  • grapheme_substr() - Return part of a string
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

Grapheme Functions
grapheme_stripos
Grapheme Functions


Find position (in grapheme units) of first occurrence of a case-insensitive string

grapheme_extract
grapheme_stristr
Grapheme Functions
PHP Manual

grapheme_stripos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string

Description

Procedural style

int grapheme_stripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of first occurrence of a case-insensitive string

Parameters

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Return Values

Returns the position as an integer. If needle is not found, grapheme_stripos() will return boolean FALSE.

Examples

Example #1 grapheme_stripos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print grapheme_stripos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd);

?>

The above example will output:

2

See Also

  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_extract
grapheme_stristr
Grapheme Functions


Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

grapheme_stripos
grapheme_strlen
Grapheme Functions
PHP Manual

grapheme_stristr

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

Description

Procedural style

string grapheme_stristr ( string $haystack , string $needle [, bool $before_needle = false ] )

Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

Parameters

haystack

The input string. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

before_needle

If TRUE, grapheme_strstr() returns the part of the haystack before the first occurrence of the needle.

Return Values

Returns the portion of $haystack, or FALSE if $needle is not found.

Examples

Example #1 grapheme_stristr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_O_diaeresis_nfd));

?>

The above example will output:

o%CC%88a%CC%8A

See Also

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_stripos
grapheme_strlen
Grapheme Functions


Get string length in grapheme units

grapheme_stristr
grapheme_strpos
Grapheme Functions
PHP Manual

grapheme_strlen

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strlen — Get string length in grapheme units

Description

Procedural style

int grapheme_strlen ( string $input )

Get string length in grapheme units (not bytes or characters)

Parameters

input

The string being measured for length. It must be a valid UTF-8 string.

Return Values

The length of the string on success, and 0 if the string is empty.

Examples

Example #1 grapheme_strlen() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strlen( 'abc' . $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd);

?>

The above example will output:

6

See Also

  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_stristr
grapheme_strpos
Grapheme Functions


Find position (in grapheme units) of first occurrence of a string

grapheme_strlen
grapheme_strripos
Grapheme Functions
PHP Manual

grapheme_strpos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strpos — Find position (in grapheme units) of first occurrence of a string

Description

Procedural style

int grapheme_strpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of first occurrence of a string

Parameters

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in $haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Return Values

Returns the position as an integer. If needle is not found, strpos() will return boolean FALSE.

Examples

Example #1 grapheme_strpos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strpos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_o_diaeresis_nfd);

?>

The above example will output:

2

See Also

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_strlen
grapheme_strripos
Grapheme Functions


Find position (in grapheme units) of last occurrence of a case-insensitive string

grapheme_strpos
grapheme_strrpos
Grapheme Functions
PHP Manual

grapheme_strripos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string

Description

Procedural style

int grapheme_strripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of last occurrence of a case-insensitive string

Parameters

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in $haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Return Values

Returns the position as an integer. If needle is not found, grapheme_strripos() will return boolean FALSE.

Examples

Example #1 grapheme_strripos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print grapheme_strripos( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd);

?>

The above example will output:

2

See Also

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_strpos
grapheme_strrpos
Grapheme Functions


Find position (in grapheme units) of last occurrence of a string

grapheme_strripos
grapheme_strstr
Grapheme Functions
PHP Manual

grapheme_strrpos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string

Description

Procedural style

int grapheme_strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of last occurrence of a string

Parameters

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in $haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Return Values

Returns the position as an integer. If needle is not found, grapheme_strrpos() will return boolean FALSE.

Examples

Example #1 grapheme_strrpos() example

< ?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strrpos( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_o_diaeresis_nfd, $char_o_diaeresis_nfd);

?>

The above example will output:

2

See Also

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_strripos
grapheme_strstr
Grapheme Functions


Returns part of haystack string from the first occurrence of needle to the end of haystack.

grapheme_strrpos
grapheme_substr
Grapheme Functions
PHP Manual

grapheme_strstr

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack.

Description

Procedural style

string grapheme_strstr ( string $haystack , string $needle [, bool $before_needle = false ] )

Returns part of haystack string from the first occurrence of needle to the end of haystack.

Parameters

haystack

The input string. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

before_needle

If TRUE, grapheme_strstr() returns the part of the haystack before the first occurrence of the needle.

Return Values

Returns the portion of string, or FALSE if needle is not found.

Examples

Example #1 grapheme_strstr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_o_diaeresis_nfd));

?>

The above example will output:

o%CC%88a%CC%8A

See Also

  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_strrpos
grapheme_substr
Grapheme Functions


Return part of a string

grapheme_strstr
IDN Functions
Grapheme Functions
PHP Manual

grapheme_substr

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_substr — Return part of a string

Description

Procedural style

int grapheme_substr ( string $string , int $start [, int $length ] )

Return part of a string

Parameters

string

The input string. Must be valid UTF-8.

start

Start position in default grapheme units. If $start is non-negative, the returned string will start at the $start'th position in $string, counting from zero. If $start is negative, the returned string will start at the $start'th grapheme unit from the end of string.

length

Length in grapheme units. If $length is given and is positive, the string returned will contain at most $length grapheme units beginning from $start (depending on the length of string). If $string is less than or equal to $start grapheme units long, FALSE will be returned. If $length is given and is negative, then that many grapheme units will be omitted from the end of string (after the start position has been calculated when a start is negative). If $start denotes a position beyond this truncation, an empty string will be returned.

Return Values

Returns the extracted part of $string.

Examples

Example #1 grapheme_substr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_substr( "ao" . $char_a_ring_nfd . "bc" . $char_o_diaeresis_nfd . "O", 2, -1 ));
?>

The above example will output:

a%CC%8Abco%CC%88

See Also

  • grapheme_extract() - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_strstr
IDN Functions
Grapheme Functions


Converts a Gregorian date to Julian Day Count

FrenchToJD
JDDayOfWeek
Calendar Functions
PHP Manual

GregorianToJD

(PHP 4, PHP 5)

GregorianToJD — Converts a Gregorian date to Julian Day Count

Description

int gregoriantojd ( int $month , int $day , int $year )

Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.

Parameters

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4714 and 9999

Return Values

The julian day for the given gregorian date as an integer.

Examples

Example #1 Calendar functions

<?php
$jd = GregorianToJD(10, 11, 1970);
echo "$jd\n";
$gregorian = JDToGregorian($jd);
echo "$gregorian\n";
?>

See Also

  • jdtogregorian() - Converts Julian Day Count to Gregorian date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count

FrenchToJD
JDDayOfWeek
Calendar Functions


Close an open gz-file pointer

Zlib Functions
gzcompress
Zlib Functions
PHP Manual

gzclose

(PHP 4, PHP 5)

gzclose — Close an open gz-file pointer

Description

bool gzclose ( resource $zp )

Closes the given gz-file pointer.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 gzclose() example

<?php
$gz = gzopen('somefile.gz','w9');
gzputs ($gz, 'I was added to somefile.gz');
gzclose($gz);
?>

See Also

  • gzopen() - Open gz-file

Zlib Functions
gzcompress
Zlib Functions


Compress a string

gzclose
gzdecode
Zlib Functions
PHP Manual

gzcompress

(PHP 4 >= 4.0.1, PHP 5)

gzcompress — Compress a string

Description

string gzcompress ( string $data [, int $level = -1 ] )

This function compress the given string using the ZLIB data format.

For details on the ZLIB compression algorithm see the document "» ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

Note: This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

Parameters

data

The data to compress.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression.

Return Values

The compressed string or FALSE if an error occurred.

Examples

Example #1 gzcompress() example

<?php
$compressed = gzcompress('Compress me', 9);
echo $compressed;
?>

See Also

  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

gzclose
gzdecode
Zlib Functions


Decodes a gzip compressed string

gzcompress
gzdeflate
Zlib Functions
PHP Manual

gzdecode

(PHP 6 >= 6.0.0)

gzdecode — Decodes a gzip compressed string

Description

string gzdecode ( string $data [, int $length ] )

This function returns a decoded version of the input data .

Parameters

data

The data to decode, encoded by gzencode().

length

The maximum length of data to decode.

Return Values

The decoded string, or FALSE if an error occurred.

See Also

  • gzencode() - Create a gzip compressed string

gzcompress
gzdeflate
Zlib Functions


Deflate a string

gzdecode
gzencode
Zlib Functions
PHP Manual

gzdeflate

(PHP 4 >= 4.0.4, PHP 5)

gzdeflate — Deflate a string

Description

string gzdeflate ( string $data [, int $level = -1 ] )

This function compress the given string using the DEFLATE data format.

For details on the DEFLATE compression algorithm see the document "» DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).

Parameters

data

The data to deflate.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library.

Return Values

The deflated string or FALSE if an error occurred.

Examples

Example #1 gzdeflate() example

<?php
$compressed = gzdeflate('Compress me', 9);
echo $compressed;
?>

See Also

  • gzinflate() - Inflate a deflated string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

gzdecode
gzencode
Zlib Functions


Create a gzip compressed string

gzdeflate
gzeof
Zlib Functions
PHP Manual

gzencode

(PHP 4 >= 4.0.4, PHP 5)

gzencode — Create a gzip compressed string

Description

string gzencode ( string $data [, int $level = -1 [, int $encoding_mode = FORCE_GZIP ]] )

This function returns a compressed version of the input data compatible with the output of the gzip program.

For more information on the GZIP file format, see the document: » GZIP file format specification version 4.3 (RFC 1952).

Parameters

data

The data to encode.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library.

encoding_mode

The encoding mode. Can be FORCE_GZIP (the default) or FORCE_DEFLATE.

If you use FORCE_DEFLATE, you get a standard zlib deflated string (inclusive zlib headers) after the gzip file header but without the trailing crc32 checksum.

Return Values

The encoded string, or FALSE if an error occurred.

Changelog

Version | Description
4.2.0 | The encoding_mode parameter was added

Examples

The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:

Example #1 Creating a gzip file

<?php
$data = implode("", file("bigfile.txt"));
$gzdata = gzencode($data, 9);
$fp = fopen("bigfile.txt.gz", "w");
fwrite($fp, $gzdata);
fclose($fp);
?>

See Also

  • gzdecode() - Decodes a gzip compressed string
  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzcompress() - Compress a string

gzdeflate
gzeof
Zlib Functions


Test for EOF on a gz-file pointer

gzencode
gzfile
Zlib Functions
PHP Manual

gzeof

(PHP 4, PHP 5)

gzeof — Test for EOF on a gz-file pointer

Description

int gzeof ( resource $zp )

Tests the given GZ file pointer for EOF.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.

Examples

Example #1 gzeof() example

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>

gzencode
gzfile
Zlib Functions


Read entire gz-file into an array

gzeof
gzgetc
Zlib Functions
PHP Manual

gzfile

(PHP 4, PHP 5)

gzfile — Read entire gz-file into an array

Description

array gzfile ( string $filename [, int $use_include_path = 0 ] )

This function is identical to readgzfile(), except that it returns the file in an array.

Parameters

filename

The file name.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Return Values

An array containing the file, one line per cell.

Examples

Example #1 gzfile() example

<?php
$lines = gzfile('somefile.gz');
foreach ($lines as $line) {
    echo $line;
}
?>

See Also

  • readgzfile() - Output a gz-file
  • gzopen() - Open gz-file

gzeof
gzgetc
Zlib Functions


Get character from gz-file pointer

gzfile
gzgets
Zlib Functions
PHP Manual

gzgetc

(PHP 4, PHP 5)

gzgetc — Get character from gz-file pointer

Description

string gzgetc ( resource $zp )

Returns a string containing a single (uncompressed) character read from the given gz-file pointer.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

The uncompressed character or FALSE on EOF (unlike gzeof()).

Examples

Example #1 gzgetc() example

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>

See Also

  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer

gzfile
gzgets
Zlib Functions


Get line from file pointer

gzgetc
gzgetss
Zlib Functions
PHP Manual

gzgets

(PHP 4, PHP 5)

gzgets — Get line from file pointer

Description

string gzgets ( resource $zp , int $length )

Gets a (uncompressed) string of up to length - 1 bytes read from the given file pointer. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The length of data to get.

Return Values

The uncompressed string, or FALSE on error.

Examples

Example #1 gzgets() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgets($handle, 4096);
   echo $buffer;
}
gzclose($handle);
?>

See Also

  • gzopen() - Open gz-file
  • gzgetc() - Get character from gz-file pointer
  • gzwrite() - Binary-safe gz-file write

gzgetc
gzgetss
Zlib Functions


Get line from gz-file pointer and strip HTML tags

gzgets
gzinflate
Zlib Functions
PHP Manual

gzgetss

(PHP 4, PHP 5)

gzgetss — Get line from gz-file pointer and strip HTML tags

Description

string gzgetss ( resource $zp , int $length [, string $allowable_tags ] )

Identical to gzgets(), except that gzgetss() attempts to strip any HTML and PHP tags from the text it reads.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The length of data to get.

allowable_tags

You can use this optional parameter to specify tags which should not be stripped.

Return Values

The uncompressed and striped string, or FALSE on error.

Examples

Example #1 gzgetss() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgetss($handle, 4096);
   echo $buffer;
}
gzclose($handle);
?>

See Also

  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer
  • strip_tags() - Strip HTML and PHP tags from a string

gzgets
gzinflate
Zlib Functions


Inflate a deflated string

gzgetss
gzopen
Zlib Functions
PHP Manual

gzinflate

(PHP 4 >= 4.0.4, PHP 5)

gzinflate — Inflate a deflated string

Description

string gzinflate ( string $data [, int $length = 0 ] )

This function inflate a deflated string.

Parameters

data

The data compressed by gzdeflate().

length

The maximum length of data to decode.

Return Values

The original uncompressed data or FALSE on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length .

Examples

Example #1 gzinflate() example

<?php
$compressed   = gzdeflate('Compress me', 9);
$uncompressed = gzinflate($compressed);
echo $uncompressed;
?>

See Also

  • gzdeflate() - Deflate a string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

gzgetss
gzopen
Zlib Functions


Open gz-file

gzinflate
gzpassthru
Zlib Functions
PHP Manual

gzopen

(PHP 4, PHP 5)

gzopen — Open gz-file

Description

resource gzopen ( string $filename , string $mode [, int $use_include_path = 0 ] )

Opens a gzip (.gz) file for reading or writing.

gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.

Parameters

filename

The file name.

mode

As in fopen() (rb or wb) but can also include a compression level (wb9) or a strategy: f for filtered data as in wb6f, h for Huffman only compression as in wb1h. (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Return Values

Returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.

If the open fails, the function returns FALSE.

Examples

Example #1 gzopen() Example

<?php
$fp = gzopen("/tmp/file.gz", "r");
?>

See Also

  • gzclose() - Close an open gz-file pointer

gzinflate
gzpassthru
Zlib Functions


Output all remaining data on a gz-file pointer

gzopen
gzputs
Zlib Functions
PHP Manual

gzpassthru

(PHP 4, PHP 5)

gzpassthru — Output all remaining data on a gz-file pointer

Description

int gzpassthru ( resource $zp )

Reads to EOF on the given gz-file pointer from the current position and writes the (uncompressed) results to standard output.

Note: You may need to call gzrewind() to reset the file pointer to the beginning of the file if you have already written data to it.

Tip

If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readgzfile() function, which saves you the gzopen() call.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

The number of uncompressed characters read from gz and passed through to the input, or FALSE on error.

Examples

Example #1 gzpassthru() example

<?php
$fp = gzopen('file.gz', 'r');
gzpassthru($fp);
gzclose($fp);
?>

gzopen
gzputs
Zlib Functions


Alias of gzwrite

gzpassthru
gzread
Zlib Functions
PHP Manual

gzputs

(PHP 4, PHP 5)

gzputs — Alias of gzwrite()

Description

This function is an alias of: gzwrite().

gzpassthru
gzread
Zlib Functions


Binary-safe gz-file read

gzputs
gzrewind
Zlib Functions
PHP Manual

gzread

(PHP 4, PHP 5)

gzread — Binary-safe gz-file read

Description

string gzread ( resource $zp , int $length )

gzread() reads up to length bytes from the given gz-file pointer. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The number of bytes to read.

Return Values

The data that have been read.

Examples

Example #1 gzread() example

<?php
// get contents of a gz-file into a string
$filename = "/usr/local/something.txt.gz";
$zd = gzopen($filename, "r");
$contents = gzread($zd, 10000);
gzclose($zd);
?>

See Also

  • gzwrite() - Binary-safe gz-file write
  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer
  • gzgetss() - Get line from gz-file pointer and strip HTML tags
  • gzfile() - Read entire gz-file into an array
  • gzpassthru() - Output all remaining data on a gz-file pointer

gzputs
gzrewind
Zlib Functions


Rewind the position of a gz-file pointer

gzread
gzseek
Zlib Functions
PHP Manual

gzrewind

(PHP 4, PHP 5)

gzrewind — Rewind the position of a gz-file pointer

Description

bool gzrewind ( resource $zp )

Sets the file position indicator of the given gz-file pointer to the beginning of the file stream.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gzseek() - Seek on a gz-file pointer
  • gztell() - Tell gz-file pointer read/write position

gzread
gzseek
Zlib Functions


Seek on a gz-file pointer

gzrewind
gztell
Zlib Functions
PHP Manual

gzseek

(PHP 4, PHP 5)

gzseek — Seek on a gz-file pointer

Description

int gzseek ( resource $zp , int $offset [, int $whence = SEEK_SET ] )

Sets the file position indicator for the given file pointer to the given offset byte into the file stream. Equivalent to calling (in C) gzseek(zp, offset, SEEK_SET).

If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek() then compresses a sequence of zeroes up to the new starting position.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

offset

The seeked offset.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset .

If whence is not specified, it is assumed to be SEEK_SET.

Return Values

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

Examples

Example #1 gzseek() example

<?php
$gz = gzopen('somefile.gz', 'r');
gzseek($gz,2);
echo gzgetc($gz);
gzclose($gz);
?>

See Also

  • gztell() - Tell gz-file pointer read/write position
  • gzrewind() - Rewind the position of a gz-file pointer

gzrewind
gztell
Zlib Functions


Tell gz-file pointer read/write position

gzseek
gzuncompress
Zlib Functions
PHP Manual

gztell

(PHP 4, PHP 5)

gztell — Tell gz-file pointer read/write position

Description

int gztell ( resource $zp )

Gets the position of the given file pointer; i.e., its offset into the uncompressed file stream.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Return Values

The position of the file pointer or FALSE if an error occurs.

See Also

  • gzopen() - Open gz-file
  • gzseek() - Seek on a gz-file pointer
  • gzrewind() - Rewind the position of a gz-file pointer

gzseek
gzuncompress
Zlib Functions


Uncompress a compressed string

gztell
gzwrite
Zlib Functions
PHP Manual

gzuncompress

(PHP 4 >= 4.0.1, PHP 5)

gzuncompress — Uncompress a compressed string

Description

string gzuncompress ( string $data [, int $length = 0 ] )

This function uncompress a compressed string.

Parameters

data

The data compressed by gzcompress().

length

The maximum length of data to decode.

Return Values

The original uncompressed data or FALSE on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length .

Examples

Example #1 gzuncompress() example

<?php
$compressed   = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?>

See Also

  • gzcompress() - Compress a string
  • gzinflate() - Inflate a deflated string
  • gzdeflate() - Deflate a string
  • gzencode() - Create a gzip compressed string

gztell
gzwrite
Zlib Functions


Binary-safe gz-file write

gzuncompress
readgzfile
Zlib Functions
PHP Manual

gzwrite

(PHP 4, PHP 5)

gzwrite — Binary-safe gz-file write

Description

int gzwrite ( resource $zp , string $string [, int $length ] )

gzwrite() writes the contents of string to the given gz-file.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

string

The string to write.

length

The number of uncompressed bytes to write. If supplied, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.

Note: Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string .

Return Values

Returns the number of (uncompressed) bytes written to the given gz-file stream.

Examples

Example #1 gzwrite() example

<?php
$string = 'Some information to compress';
$gz = gzopen('somefile.gz','w9');
gzwrite($gz, $string);
gzclose($gz);
?>

See Also

  • gzread() - Binary-safe gz-file read
  • gzopen() - Open gz-file

gzuncompress
readgzfile
Zlib Functions


Halts the compiler execution

get_browser
highlight_file
Misc. Functions
PHP Manual

__halt_compiler

(PHP 5 >= 5.1.0)

__halt_compiler — Halts the compiler execution

Description

void __halt_compiler ( void )

Halts the execution of the compiler. This can be useful to embed data in PHP scripts, like the installation files.

Byte position of the data start can be determined by the __COMPILER_HALT_OFFSET__ constant which is defined only if there is a __halt_compiler() presented in the file.

Return Values

No value is returned.

Examples

Example #1 A __halt_compiler() example

<?php

// open this file
$fp = fopen(__FILE__, 'r');

// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);

// and output it
var_dump(stream_get_contents($fp));

// the end of the script execution
__halt_compiler(); the installation data (eg. tar, gz, PHP, etc.)

Notes

Note: __halt_compiler() can only be used from the outermost scope.

get_browser
highlight_file
Misc. Functions


Set the border style of the annotation

HaruAnnotation
HaruAnnotation::setHighlightMode
HaruAnnotation
PHP Manual

HaruAnnotation::setBorderStyle

(PECL haru >= 0.0.1)

HaruAnnotation::setBorderStyle — Set the border style of the annotation

Description

bool HaruAnnotation::setBorderStyle ( float $width , int $dash_on , int $dash_off )

Defines the style of the border of the annotation. This function may be used with link annotations only.

Parameters

width

The width of the border line.

dash_on

The dash style.

dash_off

The dash style.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruAnnotation
HaruAnnotation::setHighlightMode
HaruAnnotation


Set the highlighting mode of the annotation

HaruAnnotation::setBorderStyle
HaruAnnotation::setIcon
HaruAnnotation
PHP Manual

HaruAnnotation::setHighlightMode

(PECL haru >= 0.0.1)

HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation

Description

bool HaruAnnotation::setHighlightMode ( int $mode )

Defines the appearance of the annotation when clicked. This function may be used with link annotations only.

Parameters

mode

The highlighting mode of the annotation. Can take only these values:

  • HaruAnnotation::NO_HIGHLIGHT - no highlighting.
  • HaruAnnotation::INVERT_BOX - invert the contents of the annotation.
  • HaruAnnotation::INVERT_BORDER - invert the border of the annotation.
  • HaruAnnotation::DOWN_APPEARANCE - dent the annotation.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruAnnotation::setBorderStyle
HaruAnnotation::setIcon
HaruAnnotation


Set the icon style of the annotation

HaruAnnotation::setHighlightMode
HaruAnnotation::setOpened
HaruAnnotation
PHP Manual

HaruAnnotation::setIcon

(PECL haru >= 0.0.1)

HaruAnnotation::setIcon — Set the icon style of the annotation

Description

bool HaruAnnotation::setIcon ( int $icon )

Defines the style of the annotation icon. This function may be used with text annotations only.

Parameters

icon

The style of the icon. Can take only these values:

  • HaruAnnotation::ICON_COMMENT
  • HaruAnnotation::ICON_KEY
  • HaruAnnotation::ICON_NOTE
  • HaruAnnotation::ICON_HELP
  • HaruAnnotation::ICON_NEW_PARAGRAPH
  • HaruAnnotation::ICON_PARAGRAPH
  • HaruAnnotation::ICON_INSERT

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruAnnotation::setHighlightMode
HaruAnnotation::setOpened
HaruAnnotation


Set the initial state of the annotation

HaruAnnotation::setIcon
HaruDestination
HaruAnnotation
PHP Manual

HaruAnnotation::setOpened

(PECL haru >= 0.0.1)

HaruAnnotation::setOpened — Set the initial state of the annotation

Description

bool HaruAnnotation::setOpened ( bool $opened )

Defines whether the annotation is initially displayed open. This function may be used with text annotations only.

Parameters

opened

TRUE means the annotation is initially displayed open, FALSE - means it's closed.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruAnnotation::setIcon
HaruDestination
HaruAnnotation


Set the appearance of the page to fit the window

HaruDestination
HaruDestination::setFitB
HaruDestination
PHP Manual

HaruDestination::setFit

(PECL haru >= 0.0.1)

HaruDestination::setFit — Set the appearance of the page to fit the window

Description

bool HaruDestination::setFit ( void )

Defines the appearance of the page to fit the window.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDestination
HaruDestination::setFitB
HaruDestination


Set the appearance of the page to fit the bounding box of the page within the window

HaruDestination::setFit
HaruDestination::setFitBH
HaruDestination
PHP Manual

HaruDestination::setFitB

(PECL haru >= 0.0.1)

HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window

Description

bool HaruDestination::setFitB ( void )

Defines the appearance of the page to fit the bounding box of the page within the window.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDestination::setFit
HaruDestination::setFitBH
HaruDestination


Set the appearance of the page to fit the width of the bounding box

HaruDestination::setFitB
HaruDestination::setFitBV
HaruDestination
PHP Manual

HaruDestination::setFitBH

(PECL haru >= 0.0.1)

HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box

Description

bool HaruDestination::setFitBH ( float $top )

Defines the appearance of the page to magnifying to fit the width of the bounding box and setting the top position of the page to the value of top .

Parameters

top

The top coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDestination::setFitB
HaruDestination::setFitBV
HaruDestination


Set the appearance of the page to fit the height of the boudning box

HaruDestination::setFitBH
HaruDestination::setFitH
HaruDestination
PHP Manual

HaruDestination::setFitBV

(PECL haru >= 0.0.1)

HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box

Description

bool HaruDestination::setFitBV ( float $left )

Defines the appearance of the page to magnifying to fit the height of the bounding box and setting the left position of the page to the value of left .

Parameters

left

The left coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDestination::setFitBH
HaruDestination::setFitH
HaruDestination


Set the appearance of the page to fit the window width

HaruDestination::setFitBV
HaruDestination::setFitR
HaruDestination
PHP Manual

HaruDestination::setFitH

(PECL haru >= 0.0.1)

HaruDestination::setFitH — Set the appearance of the page to fit the window width

Description

bool HaruDestination::setFitH ( float $top )

Defines the appearance of the page to fit the window width and sets the top position of the page to the value of top .

Parameters

top

The top position of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDestination::setFitBV
HaruDestination::setFitR
HaruDestination


Set the appearance of the page to fit the specified rectangle

HaruDestination::setFitH
HaruDestination::setFitV
HaruDestination
PHP Manual

HaruDestination::setFitR

(PECL haru >= 0.0.1)

HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle

Description

bool HaruDestination::setFitR ( float $left , float $bottom , float $right , float $top )

Defines the appearance of the page to fit the rectangle by the parameters.

Parameters

left

The left coordinates of the page.

bottom

The bottom coordinates of the page.

right

The right coordinates of the page.

top

The top coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDestination::setFitH
HaruDestination::setFitV
HaruDestination


Set the appearance of the page to fit the window height

HaruDestination::setFitR
HaruDestination::setXYZ
HaruDestination
PHP Manual

HaruDestination::setFitV

(PECL haru >= 0.0.1)

HaruDestination::setFitV — Set the appearance of the page to fit the window height

Description

bool HaruDestination::setFitV ( float $left )

Defines the appearance of the page to fit the window height.

Parameters

left

The left position of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDestination::setFitR
HaruDestination::setXYZ
HaruDestination


Set the appearance of the page

HaruDestination::setFitV
Ming
HaruDestination
PHP Manual

HaruDestination::setXYZ

(PECL haru >= 0.0.1)

HaruDestination::setXYZ — Set the appearance of the page

Description

bool HaruDestination::setXYZ ( float $left , float $top , float $zoom )

Defines the appearance of the page using three parameters: left , top and zoom .

Parameters

left

The left position of the page.

top

The top position of the page.

zoom

The magnification factor. The value must be between 0.08 (8%) and 32 (3200%).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDestination::setFitV
Ming
HaruDestination


Add new page to the document

HaruDoc
HaruDoc::addPageLabel
HaruDoc
PHP Manual

HaruDoc::addPage

(PECL haru >= 0.0.1)

HaruDoc::addPage — Add new page to the document

Description

object HaruDoc::addPage ( void )

Adds a new page to the document.

Parameters

This function has no parameters.

Return Values

Returns a new HaruPage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::insertPage - Insert new page just before the specified page

HaruDoc
HaruDoc::addPageLabel
HaruDoc


Set the numbering style for the specified range of pages

HaruDoc::addPage
HaruDoc::__construct
HaruDoc
PHP Manual

HaruDoc::addPageLabel

(PECL haru >= 0.0.1)

HaruDoc::addPageLabel — Set the numbering style for the specified range of pages

Description

bool HaruDoc::addPageLabel ( int $first_page , int $style , int $first_num [, string $prefix = "" ] )

Set the numbering style for the specified range of pages.

Parameters

first_page

The first page included into the labeling range.

style

The numbering style. The following values are allowed:

  • HaruPage::NUM_STYLE_DECIMAL - page label is displayed using decimal numerals.
  • HaruPage::NUM_STYLE_UPPER_ROMAN - page label is displayed using uppercase Roman numerals.
  • HaruPage::NUM_STYLE_LOWER_ROMAN - page label is displayed using lowercase Roman numerals.
  • HaruPage::NUM_STYLE_UPPER_LETTER - page label is displayed using uppercase letters (from A to Z).
  • HaruPage::NUM_STYLE_LOWER_LETTERS - page label is displayed using lowercase letters (from a to z).

first_num

The first page number in this range.

prefix

The prefix for the page label.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDoc::addPage
HaruDoc::__construct
HaruDoc


Construct new HaruDoc instance

HaruDoc::addPageLabel
HaruDoc::createOutline
HaruDoc
PHP Manual

HaruDoc::__construct

(PECL haru >= 0.0.1)

HaruDoc::__construct — Construct new HaruDoc instance

Description

void HaruDoc::__construct ( void )

Constructs new HaruDoc instance.

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

Throws a HaruException on error.

HaruDoc::addPageLabel
HaruDoc::createOutline
HaruDoc


Create a HaruOutline instance

HaruDoc::__construct
HaruDoc::getCurrentEncoder
HaruDoc
PHP Manual

HaruDoc::createOutline

(PECL haru >= 0.0.1)

HaruDoc::createOutline — Create a HaruOutline instance

Description

object HaruDoc::createOutline ( string $title [, object $parent_outline [, object $encoder ]] )

Create a HaruOutline instance.

Parameters

title

The caption of new outline object.

parent_outline

A valid HaruOutline instance or NULL.

encoder

A valid HaruEncoder instance or NULL.

Return Values

Returns a new HaruOutline instance.

Errors/Exceptions

Throws a HaruException on error.

HaruDoc::__construct
HaruDoc::getCurrentEncoder
HaruDoc


Get HaruEncoder currently used in the document

HaruDoc::createOutline
HaruDoc::getCurrentPage
HaruDoc
PHP Manual

HaruDoc::getCurrentEncoder

(PECL haru >= 0.0.1)

HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document

Description

object HaruDoc::getCurrentEncoder ( void )

Get the HaruEncoder currently used in the document.

Parameters

This function has no parameters.

Return Values

Returns HaruEncoder currently used in the document or FALSE if encoder is not set.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setCurrentEncoder - Set the current encoder for the document

HaruDoc::createOutline
HaruDoc::getCurrentPage
HaruDoc


Return current page of the document

HaruDoc::getCurrentEncoder
HaruDoc::getEncoder
HaruDoc
PHP Manual

HaruDoc::getCurrentPage

(PECL haru >= 0.0.1)

HaruDoc::getCurrentPage — Return current page of the document

Description

object HaruDoc::getCurrentPage ( void )

Get current page of the document.

Parameters

This function has no parameters.

Return Values

Returns HaruPage instance on success or FALSE if there is no current page at the moment.

Errors/Exceptions

Throws a HaruException on error.

HaruDoc::getCurrentEncoder
HaruDoc::getEncoder
HaruDoc


Get HaruEncoder instance for the specified encoding

HaruDoc::getCurrentPage
HaruDoc::getFont
HaruDoc
PHP Manual

HaruDoc::getEncoder

(PECL haru >= 0.0.1)

HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding

Description

object HaruDoc::getEncoder ( string $encoding )

Get the HaruEncoder instance for the specified encoding.

Parameters

encoding

The encoding name. See Builtin Encodings for the list of allowed values.

Return Values

Returns a HaruEncoder instance for the specified encoding.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setCurrentEncoder - Set the current encoder for the document
  • HaruDoc::getCurrentEncoder - Get HaruEncoder currently used in the document

HaruDoc::getCurrentPage
HaruDoc::getFont
HaruDoc


Get HaruFont instance

HaruDoc::getEncoder
HaruDoc::getInfoAttr
HaruDoc
PHP Manual

HaruDoc::getFont

(PECL haru >= 0.0.1)

HaruDoc::getFont — Get HaruFont instance

Description

object HaruDoc::getFont ( string $fontname [, string $encoding ] )

Get a HaruFont instance.

Parameters

fontname

The name of the font. See Builtin Fonts for the list of builtin fonts. You can also use the name of a font loaded via HaruDoc::loadTTF, HaruDoc::loadTTC and HaruDoc::loadType1.

encoding

The encoding to use. See Builtin Encodings for the list of supported encodings.

Return Values

Returns a HaruFont instance with the specified fontname and encoding .

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setFontAndSize - Set font and fontsize for the page
  • HaruPage::setCurrentFont

HaruDoc::getEncoder
HaruDoc::getInfoAttr
HaruDoc


Get current value of the specified document attribute

HaruDoc::getFont
HaruDoc::getPageLayout
HaruDoc
PHP Manual

HaruDoc::getInfoAttr

(PECL haru >= 0.0.1)

HaruDoc::getInfoAttr — Get current value of the specified document attribute

Description

string HaruDoc::getInfoAttr ( int $type )

Get the current value of the specified document attribute.

Parameters

type

The type of the attribute. The following values are available:

  • HaruDoc::INFO_AUTHOR
  • HaruDoc::INFO_CREATOR
  • HaruDoc::INFO_TITLE
  • HaruDoc::INFO_SUBJECT
  • HaruDoc::INFO_KEYWORDS
  • HaruDoc::INFO_CREATION_DATE
  • HaruDoc::INFO_MOD_DATE

Return Values

Returns the string value of the specified document attribute.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setInfoAttr - Set the info attribute of the document
  • HaruDoc::setInfoDateAttr - Set the datetime info attributes of the document

HaruDoc::getFont
HaruDoc::getPageLayout
HaruDoc


Get current page layout

HaruDoc::getInfoAttr
HaruDoc::getPageMode
HaruDoc
PHP Manual

HaruDoc::getPageLayout

(PECL haru >= 0.0.1)

HaruDoc::getPageLayout — Get current page layout

Description

int HaruDoc::getPageLayout ( void )

Get the current page layout. See HaruDoc::setPageLayout for the list of possible values.

Parameters

This function has no parameters.

Return Values

Returns the page layout currently set in the document or FALSE if page layout was not set. See HaruDoc::setPageLayout for the list of possible values.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPageLayout - Set how pages should be displayed

HaruDoc::getInfoAttr
HaruDoc::getPageMode
HaruDoc


Get current page mode

HaruDoc::getPageLayout
HaruDoc::getStreamSize
HaruDoc
PHP Manual

HaruDoc::getPageMode

(PECL haru >= 0.0.1)

HaruDoc::getPageMode — Get current page mode

Description

int HaruDoc::getPageMode ( void )

Get the current page mode. See HaruDoc::setPageMode for the list of possible values.

Parameters

This function has no parameters.

Return Values

Returns the page mode currently set in the document. See HaruDoc::setPageMode for the list of possible values.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPageMode - Set how the document should be displayed

HaruDoc::getPageLayout
HaruDoc::getStreamSize
HaruDoc


Get the size of the temporary stream

HaruDoc::getPageMode
HaruDoc::insertPage
HaruDoc
PHP Manual

HaruDoc::getStreamSize

(PECL haru >= 0.0.1)

HaruDoc::getStreamSize — Get the size of the temporary stream

Description

int HaruDoc::getStreamSize ( void )

Get the size of the temporary stream.

Parameters

This function has no parameters.

Return Values

Returns the size of the data in the temporary stream of the document. The size is zero if the document was not saved to the temporary stream.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::saveToStream - Save the document into a temporary stream
  • HaruDoc::resetStream - Rewind the temporary stream
  • HaruDoc::readFromStream - Read data from the temporary stream

HaruDoc::getPageMode
HaruDoc::insertPage
HaruDoc


Insert new page just before the specified page

HaruDoc::getStreamSize
HaruDoc::loadJPEG
HaruDoc
PHP Manual

HaruDoc::insertPage

(PECL haru >= 0.0.1)

HaruDoc::insertPage — Insert new page just before the specified page

Description

object HaruDoc::insertPage ( object $page )

Creates a new page and inserts just before the specified page.

Parameters

page

A valid HaruPage instance.

Return Values

Returns a new HaruPage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::addPage - Add new page to the document

HaruDoc::getStreamSize
HaruDoc::loadJPEG
HaruDoc


Load a JPEG image

HaruDoc::insertPage
HaruDoc::loadPNG
HaruDoc
PHP Manual

HaruDoc::loadJPEG

(PECL haru >= 0.0.1)

HaruDoc::loadJPEG — Load a JPEG image

Description

object HaruDoc::loadJPEG ( string $filename )

Loads the specified JPEG image.

Parameters

filename

A valid JPEG image file.

Return Values

Returns a new HaruImage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadPNG - Load PNG image and return HaruImage instance
  • HaruDoc::loadRAW - Load a RAW image

HaruDoc::insertPage
HaruDoc::loadPNG
HaruDoc


Load PNG image and return HaruImage instance

HaruDoc::loadJPEG
HaruDoc::loadRaw
HaruDoc
PHP Manual

HaruDoc::loadPNG

(PECL haru >= 0.0.1)

HaruDoc::loadPNG — Load PNG image and return HaruImage instance

Description

object HaruDoc::loadPNG ( string $filename [, bool $deferred = false ] )

Loads a PNG image.

Libharu might be built without libpng support, in this case each call to this function would result in exception.

Parameters

filename

The name of a PNG image file.

deferred

Do not load data immediately. You can set deferred parameter to TRUE for deferred data loading, in this case only size and color are loaded immediately.

Return Values

Returns a HaruImage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadJPEG - Load a JPEG image
  • HaruDoc::loadRAW - Load a RAW image

HaruDoc::loadJPEG
HaruDoc::loadRaw
HaruDoc


Load a RAW image

HaruDoc::loadPNG
HaruDoc::loadTTC
HaruDoc
PHP Manual

HaruDoc::loadRaw

(PECL haru >= 0.0.1)

HaruDoc::loadRaw — Load a RAW image

Description

object HaruDoc::loadRaw ( string $filename , int $width , int $height , int $color_space )

Loads a RAW image.

Parameters

filename

The name of a RAW image file.

width

The width of the image.

height

The height of the image.

color_space

The color space of the image. Can be one of the following values:

  • HaruDoc::CS_DEVICE_GRAY
  • HaruDoc::CS_DEVICE_RGB
  • HaruDoc::CS_DEVICE_CMYK

Return Values

Returns a HaruImage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadJPEG - Load a JPEG image
  • HaruDoc::loadPNG - Load PNG image and return HaruImage instance

HaruDoc::loadPNG
HaruDoc::loadTTC
HaruDoc


Load the font with the specified index from TTC file

HaruDoc::loadRaw
HaruDoc::loadTTF
HaruDoc
PHP Manual

HaruDoc::loadTTC

(PECL haru >= 0.0.1)

HaruDoc::loadTTC — Load the font with the specified index from TTC file

Description

string HaruDoc::loadTTC ( string $fontfile , int $index [, bool $embed = false ] )

Loads the TrueType font with the specified index from a TrueType collection file.

Parameters

fontfile

The TrueType collection file.

index

The index of the font in the collection file.

embed

When set to TRUE, the glyph data of the font is embedded into the PDF file, otherwise only the matrix data is included.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadTTF - Load TTF font file
  • HaruDoc::loadType1 - Load Type1 font

HaruDoc::loadRaw
HaruDoc::loadTTF
HaruDoc


Load TTF font file

HaruDoc::loadTTC
HaruDoc::loadType1
HaruDoc
PHP Manual

HaruDoc::loadTTF

(PECL haru >= 0.0.1)

HaruDoc::loadTTF — Load TTF font file

Description

string HaruDoc::loadTTF ( string $fontfile [, bool $embed = false ] )

Loads the given TTF file and (optionally) embed its data into the document.

Parameters

fontfile

The TTF file to load.

embed

When set to TRUE, the glyph data of the font is embedded into the PDF file, otherwise only the matrix data is included.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadTTC - Load the font with the specified index from TTC file
  • HaruDoc::loadType1 - Load Type1 font

HaruDoc::loadTTC
HaruDoc::loadType1
HaruDoc


Load Type1 font

HaruDoc::loadTTF
HaruDoc::output
HaruDoc
PHP Manual

HaruDoc::loadType1

(PECL haru >= 0.0.1)

HaruDoc::loadType1 — Load Type1 font

Description

string HaruDoc::loadType1 ( string $afmfile [, string $pfmfile ] )

Loads Type1 font from the given file and registers it in the PDF document.

Parameters

afmfile

Path to an AFM file.

pfmfile

Path to a PFA/PFB file, optional. If it's not set only the glyph data of the font is embedded into the PDF document.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadTTC - Load the font with the specified index from TTC file
  • HaruDoc::loadTTF - Load TTF font file

HaruDoc::loadTTF
HaruDoc::output
HaruDoc


Write the document data to the output buffer

HaruDoc::loadType1
HaruDoc::readFromStream
HaruDoc
PHP Manual

HaruDoc::output

(PECL haru >= 0.0.1)

HaruDoc::output — Write the document data to the output buffer

Description

bool HaruDoc::output ( void )

Writes the document data into standard output.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::save - Save the document into the specified file

HaruDoc::loadType1
HaruDoc::readFromStream
HaruDoc


Read data from the temporary stream

HaruDoc::output
HaruDoc::resetError
HaruDoc
PHP Manual

HaruDoc::readFromStream

(PECL haru >= 0.0.1)

HaruDoc::readFromStream — Read data from the temporary stream

Description

string HaruDoc::readFromStream ( int $bytes )

Read data from the temporary stream.

Parameters

bytes

The bytes parameter specifies how many bytes to read, though the stream may contain less bytes than requested.

Return Values

Returns data from the temporary stream.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::saveToStream - Save the document into a temporary stream
  • HaruDoc::resetStream - Rewind the temporary stream
  • HaruDoc::getStreamSize - Get the size of the temporary stream

HaruDoc::output
HaruDoc::resetError
HaruDoc


Reset error state of the document handle

HaruDoc::readFromStream
HaruDoc::resetStream
HaruDoc
PHP Manual

HaruDoc::resetError

(PECL haru >= 0.0.1)

HaruDoc::resetError — Reset error state of the document handle

Description

bool HaruDoc::resetError ( void )

Once an error code is set, most of the operations, including I/O processing functions cannot be performed. In case if you want to continue after the cause of the error has been fixed, you have to invoke this function in order to reset the document error state.

Parameters

This function has no parameters.

Return Values

Always succeeds and returns TRUE.

HaruDoc::readFromStream
HaruDoc::resetStream
HaruDoc


Rewind the temporary stream

HaruDoc::resetError
HaruDoc::save
HaruDoc
PHP Manual

HaruDoc::resetStream

(PECL haru >= 0.0.1)

HaruDoc::resetStream — Rewind the temporary stream

Description

bool HaruDoc::resetStream ( void )

Rewinds the temporary stream of the document.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::saveToStream - Save the document into a temporary stream
  • HaruDoc::getStreamSize - Get the size of the temporary stream
  • HaruDoc::readFromStream - Read data from the temporary stream

HaruDoc::resetError
HaruDoc::save
HaruDoc


Save the document into the specified file

HaruDoc::resetStream
HaruDoc::saveToStream
HaruDoc
PHP Manual

HaruDoc::save

(PECL haru >= 0.0.1)

HaruDoc::save — Save the document into the specified file

Description

bool HaruDoc::save ( string $file )

Saves the document into the specified file.

Parameters

file

The file to save the document to.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::output - Write the document data to the output buffer

HaruDoc::resetStream
HaruDoc::saveToStream
HaruDoc


Save the document into a temporary stream

HaruDoc::save
HaruDoc::setCompressionMode
HaruDoc
PHP Manual

HaruDoc::saveToStream

(PECL haru >= 0.0.1)

HaruDoc::saveToStream — Save the document into a temporary stream

Description

bool HaruDoc::saveToStream ( void )

Saves the document data into a temporary stream.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::resetStream - Rewind the temporary stream
  • HaruDoc::getStreamSize - Get the size of the temporary stream
  • HaruDoc::readFromStream - Read data from the temporary stream

HaruDoc::save
HaruDoc::setCompressionMode
HaruDoc


Set compression mode for the document

HaruDoc::saveToStream
HaruDoc::setCurrentEncoder
HaruDoc
PHP Manual

HaruDoc::setCompressionMode

(PECL haru >= 0.0.1)

HaruDoc::setCompressionMode — Set compression mode for the document

Description

bool HaruDoc::setCompressionMode ( int $mode )

Defines compression mode for the document. In case when libharu was compiled without Zlib support this function will always throw HaruException.

Parameters

mode

The compression mode to use. The value is a combination of the following flags:

  • HaruDoc::COMP_NONE - all contents is not compressed.
  • HaruDoc::COMP_TEXT - compress the text data.
  • HaruDoc::COMP_IMAGE - compress the image data.
  • HaruDoc::COMP_METADATA - compress other data (fonts, cmaps).
  • HaruDoc::COMP_ALL - compress all data.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDoc::saveToStream
HaruDoc::setCurrentEncoder
HaruDoc


Set the current encoder for the document

HaruDoc::setCompressionMode
HaruDoc::setEncryptionMode
HaruDoc
PHP Manual

HaruDoc::setCurrentEncoder

(PECL haru >= 0.0.1)

HaruDoc::setCurrentEncoder — Set the current encoder for the document

Description

bool HaruDoc::setCurrentEncoder ( string $encoding )

Defines the encoder currently used in the document.

Parameters

encoding

The name of the encoding to use. See Builtin Encodings for the list of allowed values.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDoc::setCompressionMode
HaruDoc::setEncryptionMode
HaruDoc


Set encryption mode for the document

HaruDoc::setCurrentEncoder
HaruDoc::setInfoAttr
HaruDoc
PHP Manual

HaruDoc::setEncryptionMode

(PECL haru >= 0.0.1)

HaruDoc::setEncryptionMode — Set encryption mode for the document

Description

bool HaruDoc::setEncryptionMode ( int $mode [, int $key_len = 5 ] )

Defines encryption mode for the document. The encryption mode cannot be set before setting the password.

Parameters

mode

The encryption mode to use. Can be one of the following:

  • HaruDoc::ENCRYPT_R2 - use "revision2" algorithm.
  • HaruDoc::ENCRYPT_R3 - use "revision3" algorithm. Using this value bumps the version of PDF to 1.4.

key_len

The encryption key length in bytes. This parameter is optional and used only when mode is HaruDoc::ENCRYPT_R3. The default value is 5 (40bit).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPassword - Set owner and user passwords for the document
  • HaruDoc::setPermission - Set permissions for the document

HaruDoc::setCurrentEncoder
HaruDoc::setInfoAttr
HaruDoc


Set the info attribute of the document

HaruDoc::setEncryptionMode
HaruDoc::setInfoDateAttr
HaruDoc
PHP Manual

HaruDoc::setInfoAttr

(PECL haru >= 0.0.1)

HaruDoc::setInfoAttr — Set the info attribute of the document

Description

bool HaruDoc::setInfoAttr ( int $type , string $info )

Defines an info attribute. Uses the current encoding of the document.

Parameters

type

The type of the attribute. Can be one of the following:

  • HaruDoc::INFO_AUTHOR
  • HaruDoc::INFO_CREATOR
  • HaruDoc::INFO_TITLE
  • HaruDoc::INFO_SUBJECT
  • HaruDoc::INFO_KEYWORDS

info

The value of the attribute.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setInfoDateAttr - Set the datetime info attributes of the document

HaruDoc::setEncryptionMode
HaruDoc::setInfoDateAttr
HaruDoc


Set the datetime info attributes of the document

HaruDoc::setInfoAttr
HaruDoc::setOpenAction
HaruDoc
PHP Manual

HaruDoc::setInfoDateAttr

(PECL haru >= 0.0.1)

HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document

Description

bool HaruDoc::setInfoDateAttr ( int $type , int $year , int $month , int $day , int $hour , int $min , int $sec , string $ind , int $off_hour , int $off_min )

Sets the datetime info attributes of the document.

Parameters

type

The type of the attribute. Can be one of the following:

  • HaruDoc::INFO_CREATION_DATE
  • HaruDoc::INFO_MOD_DATE

year

month

Between 1 and 12.

day

Between 1 and 31, 30, 29 or 28 (different for each month).

hour

Between 0 and 23.

min

Between 0 and 59.

sec

Between 0 and 59.

ind

The timezone relation to UTC, can be "", " ", "+", "-" and "Z".

off_hour

If ind is not " " or "", values between 0 and 23 are valid. Otherwise, this parameter is ignored.

off_min

If ind is not " " or "", values between 0 and 59 are valid. Otherwise, this parameter is ignored.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setInfoAttr - Set the info attribute of the document

HaruDoc::setInfoAttr
HaruDoc::setOpenAction
HaruDoc


Define which page is shown when the document is opened

HaruDoc::setInfoDateAttr
HaruDoc::setPageLayout
HaruDoc
PHP Manual

HaruDoc::setOpenAction

(PECL haru >= 0.0.1)

HaruDoc::setOpenAction — Define which page is shown when the document is opened

Description

bool HaruDoc::setOpenAction ( object $destination )

Defines which page should be shown when the document is opened.

Parameters

destination

A valid HaruDestination instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDoc::setInfoDateAttr
HaruDoc::setPageLayout
HaruDoc


Set how pages should be displayed

HaruDoc::setOpenAction
HaruDoc::setPageMode
HaruDoc
PHP Manual

HaruDoc::setPageLayout

(PECL haru >= 0.0.1)

HaruDoc::setPageLayout — Set how pages should be displayed

Description

bool HaruDoc::setPageLayout ( int $layout )

Defines how pages should be displayed.

Parameters

layout

The following values are accepted:

  • HaruDoc::PAGE_LAYOUT_SINGLE - only one page is displayed.
  • HaruDoc::PAGE_LAYOUT_ONE_COLUMN - display the pages in one column.
  • HaruDoc::PAGE_LAYOUT_TWO_COLUMN_LEFT - display pages in two columns, first page left.
  • HaruDoc::PAGE_LAYOUT_TWO_COLUMN_RIGHT - display pages in two columns, first page right.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::getPageLayout - Get current page layout

HaruDoc::setOpenAction
HaruDoc::setPageMode
HaruDoc


Set how the document should be displayed

HaruDoc::setPageLayout
HaruDoc::setPagesConfiguration
HaruDoc
PHP Manual

HaruDoc::setPageMode

(PECL haru >= 0.0.1)

HaruDoc::setPageMode — Set how the document should be displayed

Description

bool HaruDoc::setPageMode ( int $mode )

Defines how the document should be displayed.

Parameters

mode

The following values are accepted:

  • HaruDoc::PAGE_MODE_USE_NONE - display the document with neither outline nor thumbnail.
  • HaruDoc::PAGE_MODE_USE_OUTLINE - display the document with outline pane.
  • HaruDoc::PAGE_MODE_USE_THUMBS - display the document with thumbnail pane.
  • HaruDoc::PAGE_MODE_FULL_SCREEN - display the document with full screen mode.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::getPageMode - Get current page mode

HaruDoc::setPageLayout
HaruDoc::setPagesConfiguration
HaruDoc


Set the number of pages per set of pages

HaruDoc::setPageMode
HaruDoc::setPassword
HaruDoc
PHP Manual

HaruDoc::setPagesConfiguration

(PECL haru >= 0.0.1)

HaruDoc::setPagesConfiguration — Set the number of pages per set of pages

Description

bool HaruDoc::setPagesConfiguration ( int $page_per_pages )

By default the document has one pages object as a root for all pages. All page objects are create as branches of this object. One pages object can contain only 8191, therefore the maximum number of pages per document is 8191. But you can change that fact by setting page_per_pages parameter, so that the root pages object contains 8191 more pages (not page) objects, which in turn contain 8191 pages each. So the maximum number of pages in the document becomes 8191*page_per_pages .

Parameters

page_per_pages

The numbers of pages that a pages object can contain.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruDoc::setPageMode
HaruDoc::setPassword
HaruDoc


Set owner and user passwords for the document

HaruDoc::setPagesConfiguration
HaruDoc::setPermission
HaruDoc
PHP Manual

HaruDoc::setPassword

(PECL haru >= 0.0.1)

HaruDoc::setPassword — Set owner and user passwords for the document

Description

bool HaruDoc::setPassword ( string $owner_password , string $user_password )

Defines owner and user passwords for the document. Setting the passwords makes the document contents encrypted.

Parameters

owner_password

The password of the owner, which can change permissions of the document. Empty password is not accepted. Owner's password cannot be the same as the user's password.

user_password

The password of the user. Can be empty.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setEncryptionMode - Set encryption mode for the document
  • HaruDoc::setPermission - Set permissions for the document

HaruDoc::setPagesConfiguration
HaruDoc::setPermission
HaruDoc


Set permissions for the document

HaruDoc::setPassword
HaruDoc::useCNSEncodings
HaruDoc
PHP Manual

HaruDoc::setPermission

(PECL haru >= 0.0.1)

HaruDoc::setPermission — Set permissions for the document

Description

bool HaruDoc::setPermission ( int $permission )

Defines permissions for the document.

Parameters

permission

The values is a combination of these flags:

  • HaruDoc::ENABLE_READ - user can read the document.
  • HaruDoc::ENABLE_PRINT - user can print the document.
  • HaruDoc::ENABLE_EDIT_ALL - user can edit the contents of the document other than annotations and form fields.
  • HaruDoc::ENABLE_COPY - user can copy the text and the graphics of the document.
  • HaruDoc::ENABLE_EDIT - user can add or modify the annotations and form fields of the document.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPassword - Set owner and user passwords for the document
  • HaruDoc::setEncryptionMode - Set encryption mode for the document

HaruDoc::setPassword
HaruDoc::useCNSEncodings
HaruDoc


Enable Chinese simplified encodings

HaruDoc::setPermission
HaruDoc::useCNSFonts
HaruDoc
PHP Manual

HaruDoc::useCNSEncodings

(PECL haru >= 0.0.1)

HaruDoc::useCNSEncodings — Enable Chinese simplified encodings

Description

bool HaruDoc::useCNSEncodings ( void )

Enables Chinese simplified encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNSFonts - Enable builtin Chinese simplified fonts

HaruDoc::setPermission
HaruDoc::useCNSFonts
HaruDoc


Enable builtin Chinese simplified fonts

HaruDoc::useCNSEncodings
HaruDoc::useCNTEncodings
HaruDoc
PHP Manual

HaruDoc::useCNSFonts

(PECL haru >= 0.0.1)

HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts

Description

bool HaruDoc::useCNSFonts ( void )

Enables builtin Chinese simplified fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNSEncodings - Enable Chinese simplified encodings

HaruDoc::useCNSEncodings
HaruDoc::useCNTEncodings
HaruDoc


Enable Chinese traditional encodings

HaruDoc::useCNSFonts
HaruDoc::useCNTFonts
HaruDoc
PHP Manual

HaruDoc::useCNTEncodings

(PECL haru >= 0.0.1)

HaruDoc::useCNTEncodings — Enable Chinese traditional encodings

Description

bool HaruDoc::useCNTEncodings ( void )

Enables Chinese traditional encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNTFonts - Enable builtin Chinese traditional fonts

HaruDoc::useCNSFonts
HaruDoc::useCNTFonts
HaruDoc


Enable builtin Chinese traditional fonts

HaruDoc::useCNTEncodings
HaruDoc::useJPEncodings
HaruDoc
PHP Manual

HaruDoc::useCNTFonts

(PECL haru >= 0.0.1)

HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts

Description

bool HaruDoc::useCNTFonts ( void )

Enables builtin Chinese traditional fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNTEncodings - Enable Chinese traditional encodings

HaruDoc::useCNTEncodings
HaruDoc::useJPEncodings
HaruDoc


Enable Japanese encodings

HaruDoc::useCNTFonts
HaruDoc::useJPFonts
HaruDoc
PHP Manual

HaruDoc::useJPEncodings

(PECL haru >= 0.0.1)

HaruDoc::useJPEncodings — Enable Japanese encodings

Description

bool HaruDoc::useJPEncodings ( void )

Enables Japanese encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useJPFonts - Enable builtin Japanese fonts

HaruDoc::useCNTFonts
HaruDoc::useJPFonts
HaruDoc


Enable builtin Japanese fonts

HaruDoc::useJPEncodings
HaruDoc::useKREncodings
HaruDoc
PHP Manual

HaruDoc::useJPFonts

(PECL haru >= 0.0.1)

HaruDoc::useJPFonts — Enable builtin Japanese fonts

Description

bool HaruDoc::useJPFonts ( void )

Enables builtin Japanese fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useJPEncodings - Enable Japanese encodings

HaruDoc::useJPEncodings
HaruDoc::useKREncodings
HaruDoc


Enable Korean encodings

HaruDoc::useJPFonts
HaruDoc::useKRFonts
HaruDoc
PHP Manual

HaruDoc::useKREncodings

(PECL haru >= 0.0.1)

HaruDoc::useKREncodings — Enable Korean encodings

Description

bool HaruDoc::useKREncodings ( void )

Enables Korean encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useKRFonts - Enable builtin Korean fonts

HaruDoc::useJPFonts
HaruDoc::useKRFonts
HaruDoc


Enable builtin Korean fonts

HaruDoc::useKREncodings
HaruPage
HaruDoc
PHP Manual

HaruDoc::useKRFonts

(PECL haru >= 0.0.1)

HaruDoc::useKRFonts — Enable builtin Korean fonts

Description

bool HaruDoc::useKRFonts ( void )

Enables builtin Korean fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useKREncodings - Enable Korean encodings

HaruDoc::useKREncodings
HaruPage
HaruDoc


Get the type of the byte in the text

HaruEncoder
HaruEncoder::getType
HaruEncoder
PHP Manual

HaruEncoder::getByteType

(PECL haru >= 0.0.1)

HaruEncoder::getByteType — Get the type of the byte in the text

Description

int HaruEncoder::getByteType ( string $text , int $index )

Get the type of the byte in the text.

Parameters

text

The text.

index

The position in the text.

Return Values

Returns the type of the byte in the text on the specified position. The result is one of the following values:

  • HaruEncoder::BYTE_TYPE_SINGLE - single byte character.
  • HaruEncoder::BYTE_TYPE_LEAD - lead byte of a double-byte character.
  • HaruEncoder::BYTE_TYPE_TRAIL - trailing byte of a double-byte character.
  • HaruEncoder::BYTE_TYPE_UNKNOWN - invalid encoder or cannot detect the byte type.

Errors/Exceptions

Throws a HaruException on error.

HaruEncoder
HaruEncoder::getType
HaruEncoder


Get the type of the encoder

HaruEncoder::getByteType
HaruEncoder::getUnicode
HaruEncoder
PHP Manual

HaruEncoder::getType

(PECL haru >= 0.0.1)

HaruEncoder::getType — Get the type of the encoder

Description

int HaruEncoder::getType ( void )

Get the type of the encoder.

Parameters

This function has no parameters.

Return Values

Returns the type of the encoder. The result is one of the following values:

  • HaruEncoder::TYPE_SINGLE_BYTE - the encoder is for single byte characters.
  • HaruEncoder::TYPE_DOUBLE_BYTE - the encoder is for multibyte characters.
  • HaruEncoder::TYPE_UNINITIALIZED - the encoder is not initialized.
  • HaruEncoder::UNKNOWN - the encoder is invalid.

Errors/Exceptions

Throws a HaruException on error.

HaruEncoder::getByteType
HaruEncoder::getUnicode
HaruEncoder


Convert the specified character to unicode

HaruEncoder::getType
HaruEncoder::getWritingMode
HaruEncoder
PHP Manual

HaruEncoder::getUnicode

(PECL haru >= 0.0.1)

HaruEncoder::getUnicode — Convert the specified character to unicode

Description

int HaruEncoder::getUnicode ( int $character )

Converts the specified character to unicode.

Parameters

character

The character code to convert.

Return Values

Errors/Exceptions

Throws a HaruException on error.

HaruEncoder::getType
HaruEncoder::getWritingMode
HaruEncoder


Get the writing mode of the encoder

HaruEncoder::getUnicode
HaruOutline
HaruEncoder
PHP Manual

HaruEncoder::getWritingMode

(PECL haru >= 0.0.1)

HaruEncoder::getWritingMode — Get the writing mode of the encoder

Description

int HaruEncoder::getWritingMode ( void )

Get the writing mode of the encoder.

Parameters

This function has no parameters.

Return Values

Returns the writing mode of the encoder. The result value is on of the following:

  • HaruEncoder::WMODE_HORIZONTAL - horizontal writing mode.
  • HaruEncoder::WMODE_VERTICAL - vertical writing mode.

Errors/Exceptions

Throws a HaruException on error.

HaruEncoder::getUnicode
HaruOutline
HaruEncoder


Get the vertical ascent of the font

HaruFont
HaruFont::getCapHeight
HaruFont
PHP Manual

HaruFont::getAscent

(PECL haru >= 0.0.1)

HaruFont::getAscent — Get the vertical ascent of the font

Description

int HaruFont::getAscent ( void )

Get the vertical ascent of the font.

Parameters

This function has no parameters.

Return Values

Returns the vertical ascent of the font.

Errors/Exceptions

Throws a HaruException on error.

HaruFont
HaruFont::getCapHeight
HaruFont


Get the distance from the baseline of uppercase letters

HaruFont::getAscent
HaruFont::getDescent
HaruFont
PHP Manual

HaruFont::getCapHeight

(PECL haru >= 0.0.1)

HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters

Description

int HaruFont::getCapHeight ( void )

Get the distance from the baseline of uppercase letters.

Parameters

This function has no parameters.

Return Values

Returns the distance from the baseline of uppercase letters.

Errors/Exceptions

Throws a HaruException on error.

HaruFont::getAscent
HaruFont::getDescent
HaruFont


Get the vertical descent of the font

HaruFont::getCapHeight
HaruFont::getEncodingName
HaruFont
PHP Manual

HaruFont::getDescent

(PECL haru >= 0.0.1)

HaruFont::getDescent — Get the vertical descent of the font

Description

int HaruFont::getDescent ( void )

Get the vertical descent of the font.

Parameters

This function has no parameters.

Return Values

Return the vertical descent of the font.

Errors/Exceptions

Throws a HaruException on error.

HaruFont::getCapHeight
HaruFont::getEncodingName
HaruFont


Get the name of the encoding

HaruFont::getDescent
HaruFont::getFontName
HaruFont
PHP Manual

HaruFont::getEncodingName

(PECL haru >= 0.0.1)

HaruFont::getEncodingName — Get the name of the encoding

Description

string HaruFont::getEncodingName ( void )

Get the name of the font encoding.

Parameters

This function has no parameters.

Return Values

Returns the name of the font encoding.

Errors/Exceptions

Throws a HaruException on error.

HaruFont::getDescent
HaruFont::getFontName
HaruFont


Get the name of the font

HaruFont::getEncodingName
HaruFont::getTextWidth
HaruFont
PHP Manual

HaruFont::getFontName

(PECL haru >= 0.0.1)

HaruFont::getFontName — Get the name of the font

Description

string HaruFont::getFontName ( void )

Get the name of the font.

Parameters

This function has no parameters.

Return Values

Returns the name of the font.

Errors/Exceptions

Throws a HaruException on error.

HaruFont::getEncodingName
HaruFont::getTextWidth
HaruFont


Get the total width of the text, number of characters, number of words and number of spaces

HaruFont::getFontName
HaruFont::getUnicodeWidth
HaruFont
PHP Manual

HaruFont::getTextWidth

(PECL haru >= 0.0.1)

HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces

Description

array HaruFont::getTextWidth ( string $text )

Get the total width of the text, number of characters, number of words and number of spaces.

Parameters

text

The text to measure.

Return Values

Returns the total width of the text, number of characters, number of words and number of spaces in the given text.

Errors/Exceptions

Throws a HaruException on error.

HaruFont::getFontName
HaruFont::getUnicodeWidth
HaruFont


Get the width of the character in the font

HaruFont::getTextWidth
HaruFont::getXHeight
HaruFont
PHP Manual

HaruFont::getUnicodeWidth

(PECL haru >= 0.0.1)

HaruFont::getUnicodeWidth — Get the width of the character in the font

Description

int HaruFont::getUnicodeWidth ( int $character )

Get the width of the character in the font.

Parameters

character

The code of the character.

Return Values

Returns the width of the character in the font.

Errors/Exceptions

Throws a HaruException on error.

HaruFont::getTextWidth
HaruFont::getXHeight
HaruFont


Get the distance from the baseline of lowercase letters

HaruFont::getUnicodeWidth
HaruFont::measureText
HaruFont
PHP Manual

HaruFont::getXHeight

(PECL haru >= 0.0.1)

HaruFont::getXHeight — Get the distance from the baseline of lowercase letters

Description

int HaruFont::getXHeight ( void )

Gets the distance from the baseline of lowercase letters.

Parameters

This function has no parameters.

Return Values

Returns the distance from the baseline of lowercase letters.

Errors/Exceptions

Throws a HaruException on error.

HaruFont::getUnicodeWidth
HaruFont::measureText
HaruFont


Calculate the number of characters which can be included within the specified width

HaruFont::getXHeight
HaruImage
HaruFont
PHP Manual

HaruFont::measureText

(PECL haru >= 0.0.1)

HaruFont::measureText — Calculate the number of characters which can be included within the specified width

Description

int HaruFont::measureText ( string $text , float $width , float $font_size , float $char_space , float $word_space [, bool $word_wrap = false ] )

Calculate the number of characters which can be included within the specified width.

Parameters

text

The text to fit the width.

width

The width of the area to put the text to.

font_size

The size of the font.

char_space

The character spacing.

word_space

The word spacing.

word_wrap

When this parameter is set to TRUE the function "emulates" word wrapping and doesn't include the part of the current word if reached the end of the area.

Return Values

Returns the number of characters which can be included within the specified width.

Errors/Exceptions

Throws a HaruException on error.

HaruFont::getXHeight
HaruImage
HaruFont


Get the number of bits used to describe each color component of the image

HaruImage
HaruImage::getColorSpace
HaruImage
PHP Manual

HaruImage::getBitsPerComponent

(PECL haru >= 0.0.1)

HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image

Description

int HaruImage::getBitsPerComponent ( void )

Gets the number of bits used to describe each color component of the image.

Parameters

This function has no parameters.

Return Values

Returns the number of bits used to describe each color component of the image.

Errors/Exceptions

Throws a HaruException on error.

HaruImage
HaruImage::getColorSpace
HaruImage


Get the name of the color space

HaruImage::getBitsPerComponent
HaruImage::getHeight
HaruImage
PHP Manual

HaruImage::getColorSpace

(PECL haru >= 0.0.1)

HaruImage::getColorSpace — Get the name of the color space

Description

string HaruImage::getColorSpace ( void )

Get the name of the color space.

Parameters

This function has no parameters.

Return Values

Returns the name of the color space of the image. The name is one of the following values:

  • "DeviceGray"
  • "DeviceRGB"
  • "DeviceCMYK"
  • "Indexed"

Errors/Exceptions

Throws a HaruException on error.

HaruImage::getBitsPerComponent
HaruImage::getHeight
HaruImage


Get the height of the image

HaruImage::getColorSpace
HaruImage::getSize
HaruImage
PHP Manual

HaruImage::getHeight

(PECL haru >= 0.0.1)

HaruImage::getHeight — Get the height of the image

Description

int HaruImage::getHeight ( void )

Get the height of the image.

Parameters

This function has no parameters.

Return Values

Returns the height of the image.

Errors/Exceptions

Throws a HaruException on error.

HaruImage::getColorSpace
HaruImage::getSize
HaruImage


Get size of the image

HaruImage::getHeight
HaruImage::getWidth
HaruImage
PHP Manual

HaruImage::getSize

(PECL haru >= 0.0.1)

HaruImage::getSize — Get size of the image

Description

array HaruImage::getSize ( void )

Get the size of the image.

Parameters

This function has no parameters.

Return Values

Returns an array with two elements: width and height, which contain appropriate dimensions of the image.

Errors/Exceptions

Throws a HaruException on error.

HaruImage::getHeight
HaruImage::getWidth
HaruImage


Get the width of the image

HaruImage::getSize
HaruImage::setColorMask
HaruImage
PHP Manual

HaruImage::getWidth

(PECL haru >= 0.0.1)

HaruImage::getWidth — Get the width of the image

Description

int HaruImage::getWidth ( void )

Get the width of the image.

Parameters

This function has no parameters.

Return Values

Returns the width of the image.

Errors/Exceptions

Throws a HaruException on error.

HaruImage::getSize
HaruImage::setColorMask
HaruImage


Set the color mask of the image

HaruImage::getWidth
HaruImage::setMaskImage
HaruImage
PHP Manual

HaruImage::setColorMask

(PECL haru >= 0.0.1)

HaruImage::setColorMask — Set the color mask of the image

Description

bool HaruImage::setColorMask ( int $rmin , int $rmax , int $gmin , int $gmax , int $bmin , int $bmax )

Defines the transparent color of the image using the RGB range values. The color within the range is displayed as a transparent color. The color space of the image must be RGB.

Parameters

rmin

The lower limit of red. Must be between 0 and 255.

rmax

The upper limit of red. Must be between 0 and 255.

gmin

The lower limit of green. Must be between 0 and 255.

gmax

The upper limit of green. Must be between 0 and 255.

bmin

The lower limit of blue. Must be between 0 and 255.

bmax

The upper limit of blue. Must be between 0 and 255.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruImage::getWidth
HaruImage::setMaskImage
HaruImage


Set the image mask

HaruImage::setColorMask
HaruEncoder
HaruImage
PHP Manual

HaruImage::setMaskImage

(PECL haru >= 0.0.1)

HaruImage::setMaskImage — Set the image mask

Description

bool HaruImage::setMaskImage ( object $mask_image )

Sets the image used as image-mask. It must be 1bit gray-scale color image.

Parameters

mask_image

A valid HaruImage instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruImage::setColorMask
HaruEncoder
HaruImage


Set the destination for the outline

HaruOutline
HaruOutline::setOpened
HaruOutline
PHP Manual

HaruOutline::setDestination

(PECL haru >= 0.0.1)

HaruOutline::setDestination — Set the destination for the outline

Description

bool HaruOutline::setDestination ( object $destination )

Sets a destination object which becomes a target to jump to when the outline is clicked.

Parameters

destination

A valid HaruDestination instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruOutline
HaruOutline::setOpened
HaruOutline


Set the initial state of the outline

HaruOutline::setDestination
HaruAnnotation
HaruOutline
PHP Manual

HaruOutline::setOpened

(PECL haru >= 0.0.1)

HaruOutline::setOpened — Set the initial state of the outline

Description

bool HaruOutline::setOpened ( bool $opened )

Defines whether this node is opened or not when the outline is displayed for the first time.

Parameters

opened

TRUE means open, FALSE - closed.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruOutline::setDestination
HaruAnnotation
HaruOutline


Append an arc to the current path

HaruPage
HaruPage::beginText
HaruPage
PHP Manual

HaruPage::arc

(PECL haru >= 0.0.1)

HaruPage::arc — Append an arc to the current path

Description

bool HaruPage::arc ( float $x , float $y , float $ray , float $ang1 , float $ang2 )

Appends an arc to the current path.

Parameters

x

Horizontal coordinate of the center.

y

Vertical coordinate of the center.

ray

The ray of the arc.

ang1

The angle of the beginning.

ang2

The angle of the end. Must be greater than ang1 .

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage
HaruPage::beginText
HaruPage


Begin a text object and set the current text position to (0,0)

HaruPage::arc
HaruPage::circle
HaruPage
PHP Manual

HaruPage::beginText

(PECL haru >= 0.0.1)

HaruPage::beginText — Begin a text object and set the current text position to (0,0)

Description

bool HaruPage::beginText ( void )

Begins new text object and sets the current text position to (0,0).

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::arc
HaruPage::circle
HaruPage


Append a circle to the current path

HaruPage::beginText
HaruPage::closePath
HaruPage
PHP Manual

HaruPage::circle

(PECL haru >= 0.0.1)

HaruPage::circle — Append a circle to the current path

Description

bool HaruPage::circle ( float $x , float $y , float $ray )

Appends a circle to the current path.

Parameters

x

Horizontal coordinate of the center point.

y

Vertical coordinate of the center point.

ray

The ray of the circle.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::beginText
HaruPage::closePath
HaruPage


Append a straight line from the current point to the start point of the path

HaruPage::circle
HaruPage::concat
HaruPage
PHP Manual

HaruPage::closePath

(PECL haru >= 0.0.1)

HaruPage::closePath — Append a straight line from the current point to the start point of the path

Description

bool HaruPage::closePath ( void )

Appends a straight line from the current point to the start point of the path.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::circle
HaruPage::concat
HaruPage


Concatenate current transformation matrix of the page and the specified matrix

HaruPage::closePath
HaruPage::createDestination
HaruPage
PHP Manual

HaruPage::concat

(PECL haru >= 0.0.1)

HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix

Description

bool HaruPage::concat ( float $a , float $b , float $c , float $d , float $x , float $y )

Concatenates current transformation matrix of the page and the specified matrix.

Parameters

a

b

c

d

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::closePath
HaruPage::createDestination
HaruPage


Create new HaruDestination instance

HaruPage::concat
HaruPage::createLinkAnnotation
HaruPage
PHP Manual

HaruPage::createDestination

(PECL haru >= 0.0.1)

HaruPage::createDestination — Create new HaruDestination instance

Description

object HaruPage::createDestination ( void )

Create a new HaruDestination instance.

Parameters

This function has no parameters.

Return Values

Returns a new HaruDestination instance.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::concat
HaruPage::createLinkAnnotation
HaruPage


Create new HaruAnnotation instance

HaruPage::createDestination
HaruPage::createTextAnnotation
HaruPage
PHP Manual

HaruPage::createLinkAnnotation

(PECL haru >= 0.0.1)

HaruPage::createLinkAnnotation — Create new HaruAnnotation instance

Description

object HaruPage::createLinkAnnotation ( array $rectangle , object $destination )

Creates a new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the clickable area.

destination

Valid HaruDestination instance.

Return Values

Returns a new HaruAnnotation instance.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::createDestination
HaruPage::createTextAnnotation
HaruPage


Create new HaruAnnotation instance

HaruPage::createLinkAnnotation
HaruPage::createURLAnnotation
HaruPage
PHP Manual

HaruPage::createTextAnnotation

(PECL haru >= 0.0.1)

HaruPage::createTextAnnotation — Create new HaruAnnotation instance

Description

object HaruPage::createTextAnnotation ( array $rectangle , string $text [, object $encoder ] )

Creates a new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the annotation area.

text

The text to be displayed.

encoder

Optional HaruEncoder instance.

Return Values

Returns a new HaruAnnotation instance.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::createLinkAnnotation
HaruPage::createURLAnnotation
HaruPage


Create and return new HaruAnnotation instance

HaruPage::createTextAnnotation
HaruPage::curveTo2
HaruPage
PHP Manual

HaruPage::createURLAnnotation

(PECL haru >= 0.0.1)

HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance

Description

object HaruPage::createURLAnnotation ( array $rectangle , string $url )

Creates a new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the clickable area.

url

The URL to open.

Return Values

Returns a new HaruAnnotation instance.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::createTextAnnotation
HaruPage::curveTo2
HaruPage


Append a Bezier curve to the current path

HaruPage::curveTo3
HaruPage::drawImage
HaruPage
PHP Manual

HaruPage::curveTo

(PECL haru >= 0.0.1)

HaruPage::curveTo — Append a Bezier curve to the current path

Description

bool HaruPage::curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Append a Bezier curve to the current path. The point (x1, y1) and the point (x2, y2) are used as the control points for a Bezier curve and current point is moved to the point (x3, y3).

Parameters

x1

A Bezier curve control point.

y1

A Bezier curve control point.

x2

A Bezier curve control point.

y2

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::curveTo3
HaruPage::drawImage
HaruPage


Append a Bezier curve to the current path

HaruPage::createURLAnnotation
HaruPage::curveTo3
HaruPage
PHP Manual

HaruPage::curveTo2

(PECL haru >= 0.0.1)

HaruPage::curveTo2 — Append a Bezier curve to the current path

Description

bool HaruPage::curveTo2 ( float $x2 , float $y2 , float $x3 , float $y3 )

Appends a Bezier curve to the current path. The current point and the point (x2, y2) are used as the control points for the Bezier curve and current point is moved to the point (x3, y3).

Parameters

x2

A Bezier curve control point.

y2

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::createURLAnnotation
HaruPage::curveTo3
HaruPage


Append a Bezier curve to the current path

HaruPage::curveTo2
HaruPage::curveTo
HaruPage
PHP Manual

HaruPage::curveTo3

(PECL haru >= 0.0.1)

HaruPage::curveTo3 — Append a Bezier curve to the current path

Description

bool HaruPage::curveTo3 ( float $x1 , float $y1 , float $x3 , float $y3 )

Appends a Bezier curve to the current path. The point (x1, y1) and the point (x3, y3) are used as the control points for a Bezier curve and current point is moved to the point (x3, y3).

Parameters

x1

A Bezier curve control point.

y1

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::curveTo2
HaruPage::curveTo
HaruPage


Show image at the page

HaruPage::curveTo
HaruPage::ellipse
HaruPage
PHP Manual

HaruPage::drawImage

(PECL haru >= 0.0.1)

HaruPage::drawImage — Show image at the page

Description

bool HaruPage::drawImage ( object $image , float $x , float $y , float $width , float $height )

Show image at the page.

Parameters

image

Valid HaruImage instance.

x

The left border of the area where the image is displayed.

y

The lower border of the area where the image is displayed.

width

The width of the image area.

height

The height of the image area.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::curveTo
HaruPage::ellipse
HaruPage


Append an ellipse to the current path

HaruPage::drawImage
HaruPage::endPath
HaruPage
PHP Manual

HaruPage::ellipse

(PECL haru >= 0.0.1)

HaruPage::ellipse — Append an ellipse to the current path

Description

bool HaruPage::ellipse ( float $x , float $y , float $xray , float $yray )

Appends an ellipse to the current path.

Parameters

x

Horizontal coordinate of the center.

y

Vertical coordinate of the center.

xray

The ray of the ellipse in the x direction.

yray

The ray of the ellipse in the y direction.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::drawImage
HaruPage::endPath
HaruPage


End current path object without filling and painting operations

HaruPage::ellipse
HaruPage::endText
HaruPage
PHP Manual

HaruPage::endPath

(PECL haru >= 0.0.1)

HaruPage::endPath — End current path object without filling and painting operations

Description

bool HaruPage::endPath ( void )

Ends current path object without performing filling and painting operations.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::ellipse
HaruPage::endText
HaruPage


End current text object

HaruPage::endPath
HaruPage::eofill
HaruPage
PHP Manual

HaruPage::endText

(PECL haru >= 0.0.1)

HaruPage::endText — End current text object

Description

bool HaruPage::endText ( void )

Finalizes current text object.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::endPath
HaruPage::eofill
HaruPage


Fill current path using even-odd rule

HaruPage::endText
HaruPage::eoFillStroke
HaruPage
PHP Manual

HaruPage::eofill

(PECL haru >= 0.0.1)

HaruPage::eofill — Fill current path using even-odd rule

Description

bool HaruPage::eofill ( void )

Fills current path using even-odd rule.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::endText
HaruPage::eoFillStroke
HaruPage


Fill current path using even-odd rule, then paint the path

HaruPage::eofill
HaruPage::fill
HaruPage
PHP Manual

HaruPage::eoFillStroke

(PECL haru >= 0.0.1)

HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path

Description

bool HaruPage::eoFillStroke ([ bool $close_path = false ] )

Fills current path using even-odd rule, then paints the path.

Parameters

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::eofill
HaruPage::fill
HaruPage


Fill current path using nonzero winding number rule

HaruPage::eoFillStroke
HaruPage::fillStroke
HaruPage
PHP Manual

HaruPage::fill

(PECL haru >= 0.0.1)

HaruPage::fill — Fill current path using nonzero winding number rule

Description

bool HaruPage::fill ( void )

Fills current path using nonzero winding number rule.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::eoFillStroke
HaruPage::fillStroke
HaruPage


Fill current path using nonzero winding number rule, then paint the path

HaruPage::fill
HaruPage::getCharSpace
HaruPage
PHP Manual

HaruPage::fillStroke

(PECL haru >= 0.0.1)

HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path

Description

bool HaruPage::fillStroke ([ bool $close_path = false ] )

Fills current path using nonzero winding number rule, then paints the path.

Parameters

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::fill
HaruPage::getCharSpace
HaruPage


Get the current value of character spacing

HaruPage::fillStroke
HaruPage::getCMYKFill
HaruPage
PHP Manual

HaruPage::getCharSpace

(PECL haru >= 0.0.1)

HaruPage::getCharSpace — Get the current value of character spacing

Description

float HaruPage::getCharSpace ( void )

Get the current value of character spacing.

Parameters

This function has no parameters.

Return Values

Returns the current value of character spacing.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::fillStroke
HaruPage::getCMYKFill
HaruPage


Get the current filling color

HaruPage::getCharSpace
HaruPage::getCMYKStroke
HaruPage
PHP Manual

HaruPage::getCMYKFill

(PECL haru >= 0.0.1)

HaruPage::getCMYKFill — Get the current filling color

Description

array HaruPage::getCMYKFill ( void )

Returns the current filling color.

Parameters

This function has no parameters.

Return Values

Returns the current filling color as an array with 4 elements ("c", "m", "y" and "k").

Errors/Exceptions

Throws a HaruException on error.

HaruPage::getCharSpace
HaruPage::getCMYKStroke
HaruPage


Get the current stroking color

HaruPage::getCMYKFill
HaruPage::getCurrentFont
HaruPage
PHP Manual

HaruPage::getCMYKStroke

(PECL haru >= 0.0.1)

HaruPage::getCMYKStroke — Get the current stroking color

Description

array HaruPage::getCMYKStroke ( void )

Get the current stroking color.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color as an array with 4 elements ("c", "m", "y" and "k").

Errors/Exceptions

Throws a HaruException on error.

HaruPage::getCMYKFill
HaruPage::getCurrentFont
HaruPage


Get the currently used font

HaruPage::getCMYKStroke
HaruPage::getCurrentFontSize
HaruPage
PHP Manual

HaruPage::getCurrentFont

(PECL haru >= 0.0.1)

HaruPage::getCurrentFont — Get the currently used font

Description

object HaruPage::getCurrentFont ( void )

Get the currently used font.

Parameters

This function has no parameters.

Return Values

Returns the currently used font as an instance of HaruFont.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::getCMYKStroke
HaruPage::getCurrentFontSize
HaruPage


Get the current font size

HaruPage::getCurrentFont
HaruPage::getCurrentPos
HaruPage
PHP Manual

HaruPage::getCurrentFontSize

(PECL haru >= 0.0.1)

HaruPage::getCurrentFontSize — Get the current font size

Description

float HaruPage::getCurrentFontSize ( void )

Get the current font size.

Parameters

This function has no parameters.

Return Values

Returns the current font size.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::getCurrentFont
HaruPage::getCurrentPos
HaruPage


Get the current position for path painting

HaruPage::getCurrentFontSize
HaruPage::getCurrentTextPos
HaruPage
PHP Manual

HaruPage::getCurrentPos

(PECL haru >= 0.0.1)

HaruPage::getCurrentPos — Get the current position for path painting

Description

array HaruPage::getCurrentPos ( void )

Get the current position for path painting.

Parameters

This function has no parameters.

Return Values

Returns the current position for path painting as an array of with two elements - "x" and "y".

Errors/Exceptions

Throws a HaruException on error.

HaruPage::getCurrentFontSize
HaruPage::getCurrentTextPos
HaruPage


Get the current position for text printing

HaruPage::getCurrentPos
HaruPage::getDash
HaruPage
PHP Manual

HaruPage::getCurrentTextPos

(PECL haru >= 0.0.1)

HaruPage::getCurrentTextPos — Get the current position for text printing

Description

array HaruPage::getCurrentTextPos ( void )

Get the current position for text printing.

Parameters

This function has no parameters.

Return Values

Returns the current position for text printing as an array with 2 elements - "x" and "y".

Errors/Exceptions

Throws a HaruException on error.

HaruPage::getCurrentPos
HaruPage::getDash
HaruPage


Get the current dash pattern

HaruPage::getCurrentTextPos
HaruPage::getFillingColorSpace
HaruPage
PHP Manual

HaruPage::getDash

(PECL haru >= 0.0.1)

HaruPage::getDash — Get the current dash pattern

Description

array HaruPage::getDash ( void )

Get the current dash pattern. See HaruPage::setDash for more information on dash patterns.

Parameters

This function has no parameters.

Return Values

Returns the current dash pattern as an array of two elements - "pattern" and "phase" or FALSE if dash pattern was not set.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setDash - Set the dash pattern for the page

HaruPage::getCurrentTextPos
HaruPage::getFillingColorSpace
HaruPage


Get the current filling color space

HaruPage::getDash
HaruPage::getFlatness
HaruPage
PHP Manual

HaruPage::getFillingColorSpace

(PECL haru >= 0.0.1)

HaruPage::getFillingColorSpace — Get the current filling color space

Description

int HaruPage::getFillingColorSpace ( void )

Get the current filling color space.

Parameters

This function has no parameters.

Return Values

Returns the current filling color space. The result value is one of the following:

  • HaruDoc::CS_DEVICE_GRAY
  • HaruDoc::CS_DEVICE_RGB
  • HaruDoc::CS_DEVICE_CMYK
  • HaruDoc::CS_CAL_GRAY
  • HaruDoc::CS_CAL_RGB
  • HaruDoc::CS_LAB
  • HaruDoc::CS_ICC_BASED
  • HaruDoc::CS_SEPARATION
  • HaruDoc::CS_DEVICE_N
  • HaruDoc::CS_INDEXED
  • HaruDoc::CS_PATTERN

Errors/Exceptions

Throws a HaruException on error.

HaruPage::getDash
HaruPage::getFlatness
HaruPage


Get the flatness of the page

HaruPage::getFillingColorSpace
HaruPage::getGMode
HaruPage
PHP Manual

HaruPage::getFlatness

(PECL haru >= 0.0.1)

HaruPage::getFlatness — Get the flatness of the page

Description

float HaruPage::getFlatness ( void )

Get the flatness of the page.

Parameters

This function has no parameters.

Return Values

Returns the flatness of the page.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setFlatness - Set flatness for the page

HaruPage::getFillingColorSpace
HaruPage::getGMode
HaruPage


Get the current graphics mode

HaruPage::getFlatness
HaruPage::getGrayFill
HaruPage
PHP Manual

HaruPage::getGMode

(PECL haru >= 0.0.1)

HaruPage::getGMode — Get the current graphics mode

Description

int HaruPage::getGMode ( void )

Get the current graphics mode.

Parameters

This function has no parameters.

Return Values

Returns the current graphics mode. The result value is one of the following:

  • HaruPage::GMODE_PAGE_DESCRIPTION
  • HaruPage::GMODE_TEXT_OBJECT
  • HaruPage::GMODE_PATH_OBJECT
  • HaruPage::GMODE_CLIPPING_PATH
  • HaruPage::GMODE_SHADING
  • HaruPage::GMODE_INLINE_IMAGE
  • HaruPage::GMODE_EXTERNAL_OBJECT

Errors/Exceptions

Throws a HaruException on error.

HaruPage::getFlatness
HaruPage::getGrayFill
HaruPage


Get the current filling color

HaruPage::getGMode
HaruPage::getGrayStroke
HaruPage
PHP Manual

HaruPage::getGrayFill

(PECL haru >= 0.0.1)

HaruPage::getGrayFill — Get the current filling color

Description

float HaruPage::getGrayFill ( void )

Get the current filling color.

Parameters

This function has no parameters.

Return Values

Returns the current filling color.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setGrayFill - Set filling color for the page

HaruPage::getGMode
HaruPage::getGrayStroke
HaruPage


Get the current stroking color

HaruPage::getGrayFill
HaruPage::getHeight
HaruPage
PHP Manual

HaruPage::getGrayStroke

(PECL haru >= 0.0.1)

HaruPage::getGrayStroke — Get the current stroking color

Description

float HaruPage::getGrayStroke ( void )

Get the current stroking color.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setGrayStroke - Sets stroking color for the page

HaruPage::getGrayFill
HaruPage::getHeight
HaruPage


Get the height of the page

HaruPage::getGrayStroke
HaruPage::getHorizontalScaling
HaruPage
PHP Manual

HaruPage::getHeight

(PECL haru >= 0.0.1)

HaruPage::getHeight — Get the height of the page

Description

float HaruPage::getHeight ( void )

Get the height of the page.

Parameters

This function has no parameters.

Return Values

Returns the height of the page.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setHeight - Set height of the page

HaruPage::getGrayStroke
HaruPage::getHorizontalScaling
HaruPage


Get the current value of horizontal scaling

HaruPage::getHeight
HaruPage::getLineCap
HaruPage
PHP Manual

HaruPage::getHorizontalScaling

(PECL haru >= 0.0.1)

HaruPage::getHorizontalScaling — Get the current value of horizontal scaling

Description

float HaruPage::getHorizontalScaling ( void )

Get the current value of the horizontal scaling.

Parameters

This function has no parameters.

Return Values

Returns the current value of horizontal scaling.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setHorizontalScaling - Set horizontal scaling for the page

HaruPage::getHeight
HaruPage::getLineCap
HaruPage


Get the current line cap style

HaruPage::getHorizontalScaling
HaruPage::getLineJoin
HaruPage
PHP Manual

HaruPage::getLineCap

(PECL haru >= 0.0.1)

HaruPage::getLineCap — Get the current line cap style

Description

int HaruPage::getLineCap ( void )

Get the current line cap style.

Parameters

This function has no parameters.

Return Values

Returns the current line cap style. The result value is one of the following:

  • HaruPage::BUTT_END - the line is squared off at the endpoint of the path.
  • HaruPage::ROUND_END - the end of the line becomes a semicircle with center in the end point of the path.
  • HaruPage::PROJECTING_SCUARE_END - the line continues to the point that exceeds half of the stroke width the end point.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setLineCap - Set the shape to be used at the ends of lines

HaruPage::getHorizontalScaling
HaruPage::getLineJoin
HaruPage


Get the current line join style

HaruPage::getLineCap
HaruPage::getLineWidth
HaruPage
PHP Manual

HaruPage::getLineJoin

(PECL haru >= 0.0.1)

HaruPage::getLineJoin — Get the current line join style

Description

int HaruPage::getLineJoin ( void )

Get the current line join style.

Parameters

This function has no parameters.

Return Values

Returns the current line join style. The result value is one of the following:

  • HaruPage::MITER_JOIN
  • HaruPage::ROUND_JOIN
  • HaruPage::BEVEL_JOIN

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setLineJoin - Set line join style for the page

HaruPage::getLineCap
HaruPage::getLineWidth
HaruPage


Get the current line width

HaruPage::getLineJoin
HaruPage::getMiterLimit
HaruPage
PHP Manual

HaruPage::getLineWidth

(PECL haru >= 0.0.1)

HaruPage::getLineWidth — Get the current line width

Description

float HaruPage::getLineWidth ( void )

Get the current line width.

Parameters

This function has no parameters.

Return Values

Returns the current line width.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setLineWidth - Set line width for the page

HaruPage::getLineJoin
HaruPage::getMiterLimit
HaruPage


Get the value of miter limit

HaruPage::getLineWidth
HaruPage::getRGBFill
HaruPage
PHP Manual

HaruPage::getMiterLimit

(PECL haru >= 0.0.1)

HaruPage::getMiterLimit — Get the value of miter limit

Description

float HaruPage::getMiterLimit ( void )

Get the value of the miter limit.

Parameters

This function has no parameters.

Return Values

Returns the value of the miter limit.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setMiterLimit - Set the current value of the miter limit of the page

HaruPage::getLineWidth
HaruPage::getRGBFill
HaruPage


Get the current filling color

HaruPage::getMiterLimit
HaruPage::getRGBStroke
HaruPage
PHP Manual

HaruPage::getRGBFill

(PECL haru >= 0.0.1)

HaruPage::getRGBFill — Get the current filling color

Description

array HaruPage::getRGBFill ( void )

Get the current filling color.

Parameters

This function has no parameters.

Return Values

Returns the current filling color as an array with 3 elements: "r", "g" and "b".

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setRGBFill - Set filling color for the page

HaruPage::getMiterLimit
HaruPage::getRGBStroke
HaruPage


Get the current stroking color

HaruPage::getRGBFill
HaruPage::getStrokingColorSpace
HaruPage
PHP Manual

HaruPage::getRGBStroke

(PECL haru >= 0.0.1)

HaruPage::getRGBStroke — Get the current stroking color

Description

array HaruPage::getRGBStroke ( void )

Get the current stroking color.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setRGBStroke - Set stroking color for the page

HaruPage::getRGBFill
HaruPage::getStrokingColorSpace
HaruPage


Get the current stroking color space

HaruPage::getRGBStroke
HaruPage::getTextLeading
HaruPage
PHP Manual

HaruPage::getStrokingColorSpace

(PECL haru >= 0.0.1)

HaruPage::getStrokingColorSpace — Get the current stroking color space

Description

int HaruPage::getStrokingColorSpace ( void )

Get the current stroking color space.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color space. The list of return values is the same as for HaruPage::getFillingColorSpace

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getFillingColorSpace - Get the current filling color space

HaruPage::getRGBStroke
HaruPage::getTextLeading
HaruPage


Get the current value of line spacing

HaruPage::getStrokingColorSpace
HaruPage::getTextMatrix
HaruPage
PHP Manual

HaruPage::getTextLeading

(PECL haru >= 0.0.1)

HaruPage::getTextLeading — Get the current value of line spacing

Description

float HaruPage::getTextLeading ( void )

Get the current value of line spacing.

Parameters

This function has no parameters.

Return Values

Returns the current value of line spacing.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextLeading - Set text leading (line spacing) for the page

HaruPage::getStrokingColorSpace
HaruPage::getTextMatrix
HaruPage


Get the current text transformation matrix of the page

HaruPage::getTextLeading
HaruPage::getTextRenderingMode
HaruPage
PHP Manual

HaruPage::getTextMatrix

(PECL haru >= 0.0.1)

HaruPage::getTextMatrix — Get the current text transformation matrix of the page

Description

array HaruPage::getTextMatrix ( void )

Get the current text transformation matrix of the page.

Return Values

Returns the current text transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextMatrix - Set the current text transformation matrix of the page

HaruPage::getTextLeading
HaruPage::getTextRenderingMode
HaruPage


Get the current text rendering mode

HaruPage::getTextMatrix
HaruPage::getTextRise
HaruPage
PHP Manual

HaruPage::getTextRenderingMode

(PECL haru >= 0.0.1)

HaruPage::getTextRenderingMode — Get the current text rendering mode

Description

int HaruPage::getTextRenderingMode ( void )

Get the current text rendering mode.

Parameters

This function has no parameters.

Return Values

Returns the current text rendering mode. The result value is one of the following:

  • HaruPage::FILL
  • HaruPage::STROKE
  • HaruPage::FILL_THEN_STROKE
  • HaruPage::INVISIBLE
  • HaruPage::FILL_CLIPPING
  • HaruPage::STROKE_CLIPPING
  • HaruPage::FILL_STROKE_CLIPPING
  • HaruPage::CLIPPING

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextRenderingMode - Set text rendering mode for the page

HaruPage::getTextMatrix
HaruPage::getTextRise
HaruPage


Get the current value of text rising

HaruPage::getTextRenderingMode
HaruPage::getTextWidth
HaruPage
PHP Manual

HaruPage::getTextRise

(PECL haru >= 0.0.1)

HaruPage::getTextRise — Get the current value of text rising

Description

float HaruPage::getTextRise ( void )

Get the current value of text rising.

Parameters

This function has no parameters.

Return Values

Returns the current value of text rising.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextRise - Set the current value of text rising

HaruPage::getTextRenderingMode
HaruPage::getTextWidth
HaruPage


Get the width of the text using current fontsize, character spacing and word spacing

HaruPage::getTextRise
HaruPage::getTransMatrix
HaruPage
PHP Manual

HaruPage::getTextWidth

(PECL haru >= 0.0.1)

HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing

Description

float HaruPage::getTextWidth ( string $text )

Get the width of the text using current fontsize, character spacing and word spacing

Parameters

text

The text to measure.

Return Values

Returns the width of the text using current fontsize, character spacing and word spacing.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::measureText - Calculate the number of characters which can be included within the specified width

HaruPage::getTextRise
HaruPage::getTransMatrix
HaruPage


Get the current transformation matrix of the page

HaruPage::getTextWidth
HaruPage::getWidth
HaruPage
PHP Manual

HaruPage::getTransMatrix

(PECL haru >= 0.0.1)

HaruPage::getTransMatrix — Get the current transformation matrix of the page

Description

array HaruPage::getTransMatrix ( void )

Get the current transformation matrix of the page.

Parameters

This function has no parameters.

Return Values

Returns the current transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::concat - Concatenate current transformation matrix of the page and the specified matrix

HaruPage::getTextWidth
HaruPage::getWidth
HaruPage


Get the width of the page

HaruPage::getTransMatrix
HaruPage::getWordSpace
HaruPage
PHP Manual

HaruPage::getWidth

(PECL haru >= 0.0.1)

HaruPage::getWidth — Get the width of the page

Description

float HaruPage::getWidth ( void )

Get the width of the page.

Parameters

This function has no parameters.

Return Values

Returns the width of the page.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setWidth - Set width of the page

HaruPage::getTransMatrix
HaruPage::getWordSpace
HaruPage


Get the current value of word spacing

HaruPage::getWidth
HaruPage::lineTo
HaruPage
PHP Manual

HaruPage::getWordSpace

(PECL haru >= 0.0.1)

HaruPage::getWordSpace — Get the current value of word spacing

Description

float HaruPage::getWordSpace ( void )

Get the current value of word spacing.

Parameters

This function has no parameters.

Return Values

Returns the current value of word spacing.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setWordSpace - Set word spacing for the page

HaruPage::getWidth
HaruPage::lineTo
HaruPage


Draw a line from the current point to the specified point

HaruPage::getWordSpace
HaruPage::measureText
HaruPage
PHP Manual

HaruPage::lineTo

(PECL haru >= 0.0.1)

HaruPage::lineTo — Draw a line from the current point to the specified point

Description

bool HaruPage::lineTo ( float $x , float $y )

Draws a line from the current point to the specified point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::curveTo - Append a Bezier curve to the current path
  • HaruPage::curveTo2 - Append a Bezier curve to the current path
  • HaruPage::curveTo3 - Append a Bezier curve to the current path

HaruPage::getWordSpace
HaruPage::measureText
HaruPage


Calculate the number of characters which can be included within the specified width

HaruPage::lineTo
HaruPage::moveTextPos
HaruPage
PHP Manual

HaruPage::measureText

(PECL haru >= 0.0.1)

HaruPage::measureText — Calculate the number of characters which can be included within the specified width

Description

int HaruPage::measureText ( string $text , float $width [, bool $wordwrap = false ] )

Get the number of characters which can be included within the specified width.

Parameters

text

The text to measure.

width

The width of the area to put the text to.

wordwrap

When this parameter is set to TRUE the function "emulates" word wrapping and doesn't include the part of the current word if reached the end of the area.

Return Values

Returns the number of characters which can be included within the specified width.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruFont::measureText - Calculate the number of characters which can be included within the specified width

HaruPage::lineTo
HaruPage::moveTextPos
HaruPage


Move text position to the specified offset

HaruPage::measureText
HaruPage::moveTo
HaruPage
PHP Manual

HaruPage::moveTextPos

(PECL haru >= 0.0.1)

HaruPage::moveTextPos — Move text position to the specified offset

Description

bool HaruPage::moveTextPos ( float $x , float $y [, bool $set_leading = false ] )

Moves text position to the specified offset. If the start position of the current line is (x1, y1), the start of the next line is (x1 + x , y1 + y ).

Parameters

x

The specified text position offset.

y

The specified text position offset.

set_leading

If set to TRUE, the function sets the text leading to -y .

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::moveToNextLine - Move text position to the start of the next line

HaruPage::measureText
HaruPage::moveTo
HaruPage


Set starting point for new drawing path

HaruPage::moveTextPos
HaruPage::moveToNextLine
HaruPage
PHP Manual

HaruPage::moveTo

(PECL haru >= 0.0.1)

HaruPage::moveTo — Set starting point for new drawing path

Description

bool HaruPage::moveTo ( float $x , float $y )

Defines starting point for new drawing path.

Parameters

x

A new starting point coordinate.

y

A new starting point coordinate.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::moveTextPos
HaruPage::moveToNextLine
HaruPage


Move text position to the start of the next line

HaruPage::moveTo
HaruPage::rectangle
HaruPage
PHP Manual

HaruPage::moveToNextLine

(PECL haru >= 0.0.1)

HaruPage::moveToNextLine — Move text position to the start of the next line

Description

bool HaruPage::moveToNextLine ( void )

Moves text position to the start of the next line.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::moveTextPos - Move text position to the specified offset

HaruPage::moveTo
HaruPage::rectangle
HaruPage


Append a rectangle to the current path

HaruPage::moveToNextLine
HaruPage::setCharSpace
HaruPage
PHP Manual

HaruPage::rectangle

(PECL haru >= 0.0.1)

HaruPage::rectangle — Append a rectangle to the current path

Description

bool HaruPage::rectangle ( float $x , float $y , float $width , float $height )

Appends a rectangle to the current drawing path.

Parameters

x

The left border of the rectangle.

y

The lower border of the rectangle.

width

The width of the rectangle.

height

The height of the rectangle.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::moveToNextLine
HaruPage::setCharSpace
HaruPage


Set character spacing for the page

HaruPage::rectangle
HaruPage::setCMYKFill
HaruPage
PHP Manual

HaruPage::setCharSpace

(PECL haru >= 0.0.1)

HaruPage::setCharSpace — Set character spacing for the page

Description

bool HaruPage::setCharSpace ( float $char_space )

Defines character spacing for the page.

Parameters

char_space

The new character spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getCharSpace - Get the current value of character spacing

HaruPage::rectangle
HaruPage::setCMYKFill
HaruPage


Set filling color for the page

HaruPage::setCharSpace
HaruPage::setCMYKStroke
HaruPage
PHP Manual

HaruPage::setCMYKFill

(PECL haru >= 0.0.1)

HaruPage::setCMYKFill — Set filling color for the page

Description

bool HaruPage::setCMYKFill ( float $c , float $m , float $y , float $k )

Defines filling color for the page.

Parameters

c

m

y

k

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getCMYKFill - Get the current filling color

HaruPage::setCharSpace
HaruPage::setCMYKStroke
HaruPage


Set stroking color for the page

HaruPage::setCMYKFill
HaruPage::setDash
HaruPage
PHP Manual

HaruPage::setCMYKStroke

(PECL haru >= 0.0.1)

HaruPage::setCMYKStroke — Set stroking color for the page

Description

bool HaruPage::setCMYKStroke ( float $c , float $m , float $y , float $k )

Defines stroking color for the page.

Parameters

c

m

y

k

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getCMYKStroke - Get the current stroking color

HaruPage::setCMYKFill
HaruPage::setDash
HaruPage


Set the dash pattern for the page

HaruPage::setCMYKStroke
HaruPage::setFlatness
HaruPage
PHP Manual

HaruPage::setDash

(PECL haru >= 0.0.1)

HaruPage::setDash — Set the dash pattern for the page

Description

bool HaruPage::setDash ( array $pattern , int $phase )

Defines the dash pattern for the page.

Parameters

pattern

An array (8 elements max) which contains a pattern of dashes and gaps used for lines on the page.

phase

The phase on which the pattern begins.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getDash - Get the current dash pattern

HaruPage::setCMYKStroke
HaruPage::setFlatness
HaruPage


Set flatness for the page

HaruPage::setDash
HaruPage::setFontAndSize
HaruPage
PHP Manual

HaruPage::setFlatness

(PECL haru >= 0.0.1)

HaruPage::setFlatness — Set flatness for the page

Description

bool HaruPage::setFlatness ( float $flatness )

Defines flatness for the page.

Parameters

flatness

The defined flatness for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getFlatness - Get the flatness of the page

HaruPage::setDash
HaruPage::setFontAndSize
HaruPage


Set font and fontsize for the page

HaruPage::setFlatness
HaruPage::setGrayFill
HaruPage
PHP Manual

HaruPage::setFontAndSize

(PECL haru >= 0.0.1)

HaruPage::setFontAndSize — Set font and fontsize for the page

Description

bool HaruPage::setFontAndSize ( object $font , float $size )

Defines current font and its size for the page.

Parameters

font

A valid HaruFont instance.

size

The size of the font.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::getFont - Get HaruFont instance

HaruPage::setFlatness
HaruPage::setGrayFill
HaruPage


Set filling color for the page

HaruPage::setFontAndSize
HaruPage::setGrayStroke
HaruPage
PHP Manual

HaruPage::setGrayFill

(PECL haru >= 0.0.1)

HaruPage::setGrayFill — Set filling color for the page

Description

bool HaruPage::setGrayFill ( float $value )

Defines filling color for the page.

Parameters

value

The value of gray level between 0 and 1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getGrayFill - Get the current filling color

HaruPage::setFontAndSize
HaruPage::setGrayStroke
HaruPage


Sets stroking color for the page

HaruPage::setGrayFill
HaruPage::setHeight
HaruPage
PHP Manual

HaruPage::setGrayStroke

(PECL haru >= 0.0.1)

HaruPage::setGrayStroke — Sets stroking color for the page

Description

bool HaruPage::setGrayStroke ( float $value )

Defines stroking color for the page.

Parameters

value

The value of gray level between 0 and 1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getGrayStroke - Get the current stroking color

HaruPage::setGrayFill
HaruPage::setHeight
HaruPage


Set height of the page

HaruPage::setGrayStroke
HaruPage::setHorizontalScaling
HaruPage
PHP Manual

HaruPage::setHeight

(PECL haru >= 0.0.1)

HaruPage::setHeight — Set height of the page

Description

bool HaruPage::setHeight ( float $height )

Defines height of the page.

Parameters

height

The defined height for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getHeight - Get the height of the page

HaruPage::setGrayStroke
HaruPage::setHorizontalScaling
HaruPage


Set horizontal scaling for the page

HaruPage::setHeight
HaruPage::setLineCap
HaruPage
PHP Manual

HaruPage::setHorizontalScaling

(PECL haru >= 0.0.1)

HaruPage::setHorizontalScaling — Set horizontal scaling for the page

Description

bool HaruPage::setHorizontalScaling ( float $scaling )

Set the horizontal scaling for the page.

Parameters

scaling

The horizontal scaling for text showing on the page. The initial value is 100.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getHorizontalScaling - Get the current value of horizontal scaling

HaruPage::setHeight
HaruPage::setLineCap
HaruPage


Set the shape to be used at the ends of lines

HaruPage::setHorizontalScaling
HaruPage::setLineJoin
HaruPage
PHP Manual

HaruPage::setLineCap

(PECL haru >= 0.0.1)

HaruPage::setLineCap — Set the shape to be used at the ends of lines

Description

bool HaruPage::setLineCap ( int $cap )

Defines the shape to be used at the ends of lines.

Parameters

cap

Must be one of the following values:

  • HaruPage::BUTT_END - the line is squared off at the endpoint of the path.
  • HaruPage::ROUND_END - the end of the line becomes a semicircle with center in the end point of the path.
  • HaruPage::PROJECTING_SCUARE_END - the line continues to the point that exceeds half of the stroke width the end point.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getLineCap - Get the current line cap style

HaruPage::setHorizontalScaling
HaruPage::setLineJoin
HaruPage


Set line join style for the page

HaruPage::setLineCap
HaruPage::setLineWidth
HaruPage
PHP Manual

HaruPage::setLineJoin

(PECL haru >= 0.0.1)

HaruPage::setLineJoin — Set line join style for the page

Description

bool HaruPage::setLineJoin ( int $join )

Defines line join style for the page.

Parameters

join

Must be one of the following values:

  • HaruPage::MITER_JOIN
  • HaruPage::ROUND_JOIN
  • HaruPage::BEVEL_JOIN

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getLineJoin - Get the current line join style

HaruPage::setLineCap
HaruPage::setLineWidth
HaruPage


Set line width for the page

HaruPage::setLineJoin
HaruPage::setMiterLimit
HaruPage
PHP Manual

HaruPage::setLineWidth

(PECL haru >= 0.0.1)

HaruPage::setLineWidth — Set line width for the page

Description

bool HaruPage::setLineWidth ( float $width )

Defines line width for the page.

Parameters

width

The defined line width for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getLineWidth - Get the current line width

HaruPage::setLineJoin
HaruPage::setMiterLimit
HaruPage


Set the current value of the miter limit of the page

HaruPage::setLineWidth
HaruPage::setRGBFill
HaruPage
PHP Manual

HaruPage::setMiterLimit

(PECL haru >= 0.0.1)

HaruPage::setMiterLimit — Set the current value of the miter limit of the page

Description

bool HaruPage::setMiterLimit ( float $limit )

Set the current value of the miter limit of the page.

Parameters

limit

Defines the current value of the miter limit of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getMiterLimit - Get the value of miter limit

HaruPage::setLineWidth
HaruPage::setRGBFill
HaruPage


Set filling color for the page

HaruPage::setMiterLimit
HaruPage::setRGBStroke
HaruPage
PHP Manual

HaruPage::setRGBFill

(PECL haru >= 0.0.1)

HaruPage::setRGBFill — Set filling color for the page

Description

bool HaruPage::setRGBFill ( float $r , float $g , float $b )

Defines filling color for the page. All values must be between 0 and 1.

Parameters

r

g

b

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getRGBFill - Get the current filling color

HaruPage::setMiterLimit
HaruPage::setRGBStroke
HaruPage


Set stroking color for the page

HaruPage::setRGBFill
HaruPage::setRotate
HaruPage
PHP Manual

HaruPage::setRGBStroke

(PECL haru >= 0.0.1)

HaruPage::setRGBStroke — Set stroking color for the page

Description

bool HaruPage::setRGBStroke ( float $r , float $g , float $b )

Defines stroking color for the page. All values must be between 0 and 1.

Parameters

r

g

b

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getRGBStroke - Get the current stroking color

HaruPage::setRGBFill
HaruPage::setRotate
HaruPage


Set rotation angle of the page

HaruPage::setRGBStroke
HaruPage::setSize
HaruPage
PHP Manual

HaruPage::setRotate

(PECL haru >= 0.0.1)

HaruPage::setRotate — Set rotation angle of the page

Description

bool HaruPage::setRotate ( int $angle )

Defines rotation angle of the page.

Parameters

angle

Must be a multiple of 90 degrees.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::setRGBStroke
HaruPage::setSize
HaruPage


Set size and direction of the page

HaruPage::setRotate
HaruPage::setSlideShow
HaruPage
PHP Manual

HaruPage::setSize

(PECL haru >= 0.0.1)

HaruPage::setSize — Set size and direction of the page

Description

bool HaruPage::setSize ( int $size , int $direction )

Changes size and direction of the page to a predefined format.

Parameters

size

Must be one of the following values:

  • HaruPage::SIZE_LETTER
  • HaruPage::SIZE_LEGAL
  • HaruPage::SIZE_A3
  • HaruPage::SIZE_A4
  • HaruPage::SIZE_A5
  • HaruPage::SIZE_B4
  • HaruPage::SIZE_B5
  • HaruPage::SIZE_EXECUTIVE
  • HaruPage::SIZE_US4x6
  • HaruPage::SIZE_US4x8
  • HaruPage::SIZE_US5x7
  • HaruPage::SIZE_COMM10

direction

Must be one of the following values:

  • HaruPage::PORTRAIT
  • HaruPage::LANDSCAPE

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setWidth - Set width of the page
  • HaruPage::setHeight - Set height of the page

HaruPage::setRotate
HaruPage::setSlideShow
HaruPage


Set transition style for the page

HaruPage::setSize
HaruPage::setTextLeading
HaruPage
PHP Manual

HaruPage::setSlideShow

(PECL haru >= 0.0.1)

HaruPage::setSlideShow — Set transition style for the page

Description

bool HaruPage::setSlideShow ( int $type , float $disp_time , float $trans_time )

Defines transition style for the page.

Parameters

type

Must be one of the following values:

  • HaruPage::TS_WIPE_RIGHT
  • HaruPage::TS_WIPE_LEFT
  • HaruPage::TS_WIPE_UP
  • HaruPage::TS_WIPE_DOWN
  • HaruPage::TS_BARN_DOORS_HORIZONTAL_OUT
  • HaruPage::TS_BARN_DOORS_HORIZONTAL_IN
  • HaruPage::TS_BARN_DOORS_VERTICAL_OUT
  • HaruPage::TS_BARN_DOORS_VERTICAL_IN
  • HaruPage::TS_BOX_OUT
  • HaruPage::TS_BOX_IN
  • HaruPage::TS_BLINDS_HORIZONTAL
  • HaruPage::TS_BLINDS_VERTICAL
  • HaruPage::TS_DISSOLVE
  • HaruPage::TS_GLITTER_RIGHT
  • HaruPage::TS_GLITTER_DOWN
  • HaruPage::TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT
  • HaruPage::TS_REPLACE

disp_time

The display duration of the page in seconds.

trans_time

The duration of the transition effect in seconds.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::setSize
HaruPage::setTextLeading
HaruPage


Set text leading (line spacing) for the page

HaruPage::setSlideShow
HaruPage::setTextMatrix
HaruPage
PHP Manual

HaruPage::setTextLeading

(PECL haru >= 0.0.1)

HaruPage::setTextLeading — Set text leading (line spacing) for the page

Description

bool HaruPage::setTextLeading ( float $text_leading )

Set the text leading (line spacing) for the page.

Parameters

text_leading

Defines line spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextLeading - Get the current value of line spacing

HaruPage::setSlideShow
HaruPage::setTextMatrix
HaruPage


Set the current text transformation matrix of the page

HaruPage::setTextLeading
HaruPage::setTextRenderingMode
HaruPage
PHP Manual

HaruPage::setTextMatrix

(PECL haru >= 0.0.1)

HaruPage::setTextMatrix — Set the current text transformation matrix of the page

Description

bool HaruPage::setTextMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )

Defines the text transformation matrix of the page.

Parameters

a

Width multiplier.

b

Vertical skew in radians.

c

Horizontal skew in radians.

d

Height multiplier.

x

Horizontal position for text.

y

Vertical position for text.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextMatrix - Get the current text transformation matrix of the page

HaruPage::setTextLeading
HaruPage::setTextRenderingMode
HaruPage


Set text rendering mode for the page

HaruPage::setTextMatrix
HaruPage::setTextRise
HaruPage
PHP Manual

HaruPage::setTextRenderingMode

(PECL haru >= 0.0.1)

HaruPage::setTextRenderingMode — Set text rendering mode for the page

Description

bool HaruPage::setTextRenderingMode ( int $mode )

Defines text rendering mode for the page.

Parameters

mode

Must be one of the following values:

  • HaruPage::FILL
  • HaruPage::STROKE
  • HaruPage::FILL_THEN_STROKE
  • HaruPage::INVISIBLE
  • HaruPage::FILL_CLIPPING
  • HaruPage::STROKE_CLIPPING
  • HaruPage::FILL_STROKE_CLIPPING
  • HaruPage::CLIPPING

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextRenderingMode - Get the current text rendering mode

HaruPage::setTextMatrix
HaruPage::setTextRise
HaruPage


Set the current value of text rising

HaruPage::setTextRenderingMode
HaruPage::setWidth
HaruPage
PHP Manual

HaruPage::setTextRise

(PECL haru >= 0.0.1)

HaruPage::setTextRise — Set the current value of text rising

Description

bool HaruPage::setTextRise ( float $rise )

Set the current value of text rising.

Parameters

rise

Defines the current value of text rising.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextRise - Get the current value of text rising

HaruPage::setTextRenderingMode
HaruPage::setWidth
HaruPage


Set width of the page

HaruPage::setTextRise
HaruPage::setWordSpace
HaruPage
PHP Manual

HaruPage::setWidth

(PECL haru >= 0.0.1)

HaruPage::setWidth — Set width of the page

Description

bool HaruPage::setWidth ( float $width )

Set the width of the page.

Parameters

width

Defines width of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getWidth - Get the width of the page

HaruPage::setTextRise
HaruPage::setWordSpace
HaruPage


Set word spacing for the page

HaruPage::setWidth
HaruPage::showText
HaruPage
PHP Manual

HaruPage::setWordSpace

(PECL haru >= 0.0.1)

HaruPage::setWordSpace — Set word spacing for the page

Description

bool HaruPage::setWordSpace ( float $word_space )

Set the word spacing for the page.

Parameters

word_space

Defines word spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getWordSpace - Get the current value of word spacing

HaruPage::setWidth
HaruPage::showText
HaruPage


Print text at the current position of the page

HaruPage::setWordSpace
HaruPage::showTextNextLine
HaruPage
PHP Manual

HaruPage::showText

(PECL haru >= 0.0.1)

HaruPage::showText — Print text at the current position of the page

Description

bool HaruPage::showText ( string $text )

Prints out the text at the current position of the page.

Parameters

text

The text to show.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showTextNextLine - Move the current position to the start of the next line and print the text
  • HaruPage::textOut - Print the text on the specified position

HaruPage::setWordSpace
HaruPage::showTextNextLine
HaruPage


Move the current position to the start of the next line and print the text

HaruPage::showText
HaruPage::stroke
HaruPage
PHP Manual

HaruPage::showTextNextLine

(PECL haru >= 0.0.1)

HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text

Description

bool HaruPage::showTextNextLine ( string $text [, float $word_space [, float $char_space ]] )

Moves the current position to the start of the next line and print out the text.

Parameters

text

The text to show.

word_space

The word spacing.

char_space

The character spacing.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showText - Print text at the current position of the page
  • HaruPage::textOut - Print the text on the specified position

HaruPage::showText
HaruPage::stroke
HaruPage


Paint current path

HaruPage::showTextNextLine
HaruPage::textOut
HaruPage
PHP Manual

HaruPage::stroke

(PECL haru >= 0.0.1)

HaruPage::stroke — Paint current path

Description

bool HaruPage::stroke ([ bool $close_path = false ] )

Paints the current path.

Parameters

close_path

Closes the current path if set to TRUE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

HaruPage::showTextNextLine
HaruPage::textOut
HaruPage


Print the text on the specified position

HaruPage::stroke
HaruPage::textRect
HaruPage
PHP Manual

HaruPage::textOut

(PECL haru >= 0.0.1)

HaruPage::textOut — Print the text on the specified position

Description

bool HaruPage::textOut ( float $x , float $y , string $text )

Prints the text on the specified position.

Parameters

x

y

text

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showTextNextLine - Move the current position to the start of the next line and print the text
  • HaruPage::showText - Print text at the current position of the page

HaruPage::stroke
HaruPage::textRect
HaruPage


Print the text inside the specified region

HaruPage::textOut
HaruFont
HaruPage
PHP Manual

HaruPage::textRect

(PECL haru >= 0.0.1)

HaruPage::textRect — Print the text inside the specified region

Description

bool HaruPage::textRect ( float $left , float $top , float $right , float $bottom , string $text [, int $align = HaruPage::TALIGN_LEFT ] )

Prints the text inside the specified region.

Parameters

left

Left border of the text area.

top

Top border of the text area.

right

Right border of the text area.

bottom

Lower border of the text area.

text

The text to print.

align

Text alignment. Must be one of the following values:

  • HaruPage::TALIGN_LEFT
  • HaruPage::TALIGN_RIGHT
  • HaruPage::TALIGN_CENTER
  • HaruPage::TALIGN_JUSTIFY

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showTextNextLine - Move the current position to the start of the next line and print the text
  • HaruPage::showText - Print text at the current position of the page
  • HaruPage::textOut - Print the text on the specified position

HaruPage::textOut
HaruFont
HaruPage


Generate a hash value (message digest)

hash_update
Mcrypt
Hash Functions
PHP Manual

hash

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash — Generate a hash value (message digest)

Description

string hash ( string $algo , string $data [, bool $raw_output = false ] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

data

Message to be hashed.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example #1 A hash() example

<?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
?>

The above example will output:

ec457d0a974c48d5685a7efa03d137dc8bbde7e3

See Also

  • hash_file() - Generate a hash value using the contents of a given file
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_init() - Initialize an incremental hashing context
  • md5() - Calculate the md5 hash of a string
  • sha1() - Calculate the sha1 hash of a string

hash_update
Mcrypt
Hash Functions


Return a list of registered hashing algorithms

Hash Functions
hash_copy
Hash Functions
PHP Manual

hash_algos

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_algos — Return a list of registered hashing algorithms

Description

array hash_algos ( void )

Return Values

Returns a numerically indexed array containing the list of supported hashing algorithms.

Examples

Example #1 hash_algos() example

As of PHP 5.1.2, hash_algos() will return the following list of algorithm names.

<?php
print_r(hash_algos());
?>

The above example will output:

Array
(
    [0] => md4
    [1] => md5
    [2] => sha1
    [3] => sha256
    [4] => sha384
    [5] => sha512
    [6] => ripemd128
    [7] => ripemd160
    [8] => whirlpool
    [9] => tiger128,3
    [10] => tiger160,3
    [11] => tiger192,3
    [12] => tiger128,4
    [13] => tiger160,4
    [14] => tiger192,4
    [15] => snefru
    [16] => gost
    [17] => adler32
    [18] => crc32
    [19] => crc32b
    [20] => haval128,3
    [21] => haval160,3
    [22] => haval192,3
    [23] => haval224,3
    [24] => haval256,3
    [25] => haval128,4
    [26] => haval160,4
    [27] => haval192,4
    [28] => haval224,4
    [29] => haval256,4
    [30] => haval128,5
    [31] => haval160,5
    [32] => haval192,5
    [33] => haval224,5
    [34] => haval256,5
)

Hash Functions
hash_copy
Hash Functions


Copy hashing context

hash_algos
hash_file
Hash Functions
PHP Manual

hash_copy

(PHP 5 >= 5.3.0)

hash_copy — Copy hashing context

Description

resource hash_copy ( resource $context )

Parameters

context

Hashing context returned by hash_init().

Return Values

Returns a copy of Hashing Context resource.

Examples

Example #1 hash_copy() example

<?php
$context = hash_init("md5");
hash_update($context, "data");

/* copy context to be able to continue using it */
$copy_context = hash_copy($context);

echo hash_final($context), "\n";

hash_update($copy_context, "data");
echo hash_final($copy_context), "\n";
?>

The above example will output:

8d777f385d3dfec8815d20f7496026dc
511ae0b1c13f95e5f08f1a0dd3da3d93

hash_algos
hash_file
Hash Functions


Generate a hash value using the contents of a given file

hash_copy
hash_final
Hash Functions
PHP Manual

hash_file

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_file — Generate a hash value using the contents of a given file

Description

string hash_file ( string $algo , string $filename [, bool $raw_output = false ] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

filename

URL describing location of file to be hashed; Supports fopen wrappers.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example #1 Using hash_file()

<?php
/* Create a file to calculate hash of */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');

echo hash_file('md5', 'example.txt');
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

  • hash() - Generate a hash value (message digest)
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file
  • hash_update_file() - Pump data into an active hashing context from a file
  • md5_file() - Calculates the md5 hash of a given file
  • sha1_file() - Calculate the sha1 hash of a file

hash_copy
hash_final
Hash Functions


Finalize an incremental hash and return resulting digest

hash_file
hash_hmac_file
Hash Functions
PHP Manual

hash_final

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_final — Finalize an incremental hash and return resulting digest

Description

string hash_final ( resource $context [, bool $raw_output = false ] )

Parameters

context

Hashing context returned by hash_init().

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example #1 hash_final() example

<?php
$ctx = hash_init('sha1');
hash_update($ctx, 'The quick brown fox jumped over the lazy dog.');
echo hash_final($ctx);
?>

The above example will output:

c0854fb9fb03c41cce3802cb0d220529e6eef94e

See Also

  • hash_init() - Initialize an incremental hashing context
  • hash_update() - Pump data into an active hashing context
  • hash_update_stream() - Pump data into an active hashing context from an open stream
  • hash_update_file() - Pump data into an active hashing context from a file

hash_file
hash_hmac_file
Hash Functions


Generate a keyed hash value using the HMAC method

hash_hmac_file
hash_init
Hash Functions
PHP Manual

hash_hmac

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_hmac — Generate a keyed hash value using the HMAC method

Description

string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See hash_algos() for a list of supported algorithms.

data

Message to be hashed.

key

Shared secret key used for generating the HMAC variant of the message digest.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example #1 hash_hmac() example

<?php
echo hash_hmac('ripemd160', 'The quick brown fox jumped over the lazy dog.', 'secret');
?>

The above example will output:

b8e7ae12510bdfb1812e463a7f086122cf37e4f7

See Also

  • hash() - Generate a hash value (message digest)
  • hash_algos() - Return a list of registered hashing algorithms
  • hash_init() - Initialize an incremental hashing context
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file

hash_hmac_file
hash_init
Hash Functions


Generate a keyed hash value using the HMAC method and the contents of a given file

hash_final
hash_hmac
Hash Functions
PHP Manual

hash_hmac_file

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file

Description

string hash_hmac_file ( string $algo , string $filename , string $key [, bool $raw_output = false ] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See hash_algos() for a list of supported algorithms.

filename

URL describing location of file to be hashed; Supports fopen wrappers.

key

Shared secret key used for generating the HMAC variant of the message digest.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Examples

Example #1 hash_hmac_file() example

<?php
/* Create a file to calculate hash of */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');

echo hash_hmac_file('md5', 'example.txt', 'secret');
?>

The above example will output:

7eb2b5c37443418fc77c136dd20e859c

See Also

  • hash_algos() - Return a list of registered hashing algorithms
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_file() - Generate a hash value using the contents of a given file

hash_final
hash_hmac
Hash Functions


Initialize an incremental hashing context

hash_hmac
hash_update_file
Hash Functions
PHP Manual

hash_init

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_init — Initialize an incremental hashing context

Description

resource hash_init ( string $algo [, int $options = 0 [, string $key = NULL ]] )

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

options

Optional settings for hash generation, currently supports only one option: HASH_HMAC. When specified, the key must be specified.

key

When HASH_HMAC is specified for options , a shared secret key to be used with the HMAC hashing method must be supplied in this parameter.

Return Values

Returns a Hashing Context resource for use with hash_update(), hash_update_stream(), hash_update_file(), and hash_final().

Examples

Example #1 Incremental hashing example

<?php
$ctx = hash_init('md5');
hash_update($ctx, 'The quick brown fox ');
hash_update($ctx, 'jumped over the lazy dog.');
echo hash_final($ctx);
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

  • hash() - Generate a hash value (message digest)
  • hash_file() - Generate a hash value using the contents of a given file
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file

hash_hmac
hash_update_file
Hash Functions


Pump data into an active hashing context

hash_update_stream
hash
Hash Functions
PHP Manual

hash_update

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_update — Pump data into an active hashing context

Description

bool hash_update ( resource $context , string $data )

Parameters

context

Hashing context returned by hash_init().

data

Message to be included in the hash digest.

Return Values

Returns TRUE.

See Also

  • hash_init() - Initialize an incremental hashing context
  • hash_update_file() - Pump data into an active hashing context from a file
  • hash_update_stream() - Pump data into an active hashing context from an open stream
  • hash_final() - Finalize an incremental hash and return resulting digest

hash_update_stream
hash
Hash Functions


Pump data into an active hashing context from a file

hash_init
hash_update_stream
Hash Functions
PHP Manual

hash_update_file

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_update_file — Pump data into an active hashing context from a file

Description

bool hash_update_file ( resource $context , string $filename [, resource $context = NULL ] )

Parameters

context

Hashing context returned by hash_init().

filename

URL describing location of file to be hashed; Supports fopen wrappers.

context

Stream context as returned by stream_context_create().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hash_init() - Initialize an incremental hashing context
  • hash_update() - Pump data into an active hashing context
  • hash_update_stream() - Pump data into an active hashing context from an open stream
  • hash_final() - Finalize an incremental hash and return resulting digest
  • hash() - Generate a hash value (message digest)
  • hash_file() - Generate a hash value using the contents of a given file

hash_init
hash_update_stream
Hash Functions


Pump data into an active hashing context from an open stream

hash_update_file
hash_update
Hash Functions
PHP Manual

hash_update_stream

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_update_stream — Pump data into an active hashing context from an open stream

Description

int hash_update_stream ( resource $context , resource $handle [, int $length = -1 ] )

Parameters

context

Hashing context returned by hash_init().

handle

Open file handle as returned by any stream creation function.

length

Maximum number of characters to copy from handle into the hashing context.

Return Values

Actual number of bytes added to the hashing context from handle .

Examples

Example #1 hash_update_stream() example

<?php
$fp = tmpfile();
fwrite($fp, 'The quick brown fox jumped over the lazy dog.');
rewind($fp);

$ctx = hash_init('md5');
hash_update_stream($ctx, $fp);
echo hash_final($ctx);
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

  • hash_init() - Initialize an incremental hashing context
  • hash_update() - Pump data into an active hashing context
  • hash_final() - Finalize an incremental hash and return resulting digest
  • hash() - Generate a hash value (message digest)
  • hash_file() - Generate a hash value using the contents of a given file

hash_update_file
hash_update
Hash Functions


Hexadecimal to decimal

getrandmax
hypot
Math Functions
PHP Manual

hexdec

(PHP 4, PHP 5)

hexdec — Hexadecimal to decimal

Description

number hexdec ( string $hex_string )

Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. hexdec() converts a hexadecimal string to a decimal number.

hexdec() will ignore any non-hexadecimal characters it encounters.

Parameters

hex_string

The hexadecimal string to convert

Return Values

The decimal representation of hex_string

Changelog

Version | Description
Since 4.1.0 | The function can now convert values that are too big for the platforms integer type, it will return the value as float instead in that case.

Examples

Example #1 hexdec() example

<?php
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both print "int(238)"

var_dump(hexdec("that")); // print "int(10)"
var_dump(hexdec("a0")); // print "int(160)"
?>

See Also

  • dechex() - Decimal to hexadecimal
  • bindec() - Binary to decimal
  • octdec() - Octal to decimal
  • base_convert() - Convert a number between arbitrary bases

getrandmax
hypot
Math Functions


Syntax highlighting of a file

__halt_compiler
highlight_string
Misc. Functions
PHP Manual

highlight_file

(PHP 4, PHP 5)

highlight_file — Syntax highlighting of a file

Description

mixed highlight_file ( string $filename [, bool $return = false ] )

Prints out or returns a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.

Many servers are configured to automatically highlight files with a phps extension. For example, example.phps when viewed will show the syntax highlighted source of the file. To enable this, add this line to the httpd.conf:

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

Parameters

filename

Path to the PHP file to be highlighted.

return

Set this parameter to TRUE to make this function return the highlighted code.

Return Values

If return is set to TRUE, returns the highlighted code as a string instead of printing it out. Otherwise, it will return TRUE on success, FALSE on failure.

Changelog

Version | Description
4.2.1 | This function is now also affected by safe_mode and open_basedir.
4.2.0 | The return parameter was added.

Notes

Caution

Care should be taken when using the highlight_file() function to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.

Note: This function uses internal output buffering with this parameter so it can not be used inside an ob_start() callback function.

See Also

  • highlight_string() - Syntax highlighting of a string

__halt_compiler
highlight_string
Misc. Functions


Syntax highlighting of a string

highlight_file
ignore_user_abort
Misc. Functions
PHP Manual

highlight_string

(PHP 4, PHP 5)

highlight_string — Syntax highlighting of a string

Description

mixed highlight_string ( string $str [, bool $return = false ] )

Outputs or returns a syntax highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP.

Parameters

str

The PHP code to be highlighted. This should include the opening tag.

return

Set this parameter to TRUE to make this function return the highlighted code.

Return Values

If return is set to TRUE, returns the highlighted code as a string instead of printing it out. Otherwise, it will return TRUE on success, FALSE on failure.

Changelog

Version | Description
4.2.0 | The return parameter was added.

Examples

Example #1 highlight_string() example

<?php
highlight_string('<?php phpinfo(); ?>');
?>

The above example will output (in PHP 4):

<code><font color="#000000">
<font color="#0000BB">&lt;?php phpinfo</font><font color="#007700">(); </font><font color="#0000BB">?&gt;</font>
</font>
</code>

The above example will output (in PHP 5):

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?&gt;</span>
</span>
</code>

Notes

Note: This function uses internal output buffering with this parameter so it can not be used inside an ob_start() callback function.

See Also

  • highlight_file() - Syntax highlighting of a file

highlight_file
ignore_user_abort
Misc. Functions


Calculate the length of the hypotenuse of a right-angle triangle

hexdec
is_finite
Math Functions
PHP Manual

hypot

(PHP 4 >= 4.1.0, PHP 5)

hypot — Calculate the length of the hypotenuse of a right-angle triangle

Description

float hypot ( float $x , float $y )

hypot() returns the length of the hypotenuse of a right-angle triangle with sides of length x and y , or the distance of the point (x , y ) from the origin. This is equivalent to sqrt(x*x + y*y).

Parameters

x

Length of first side

y

Length of second side

Return Values

Calculated length of the hypotenuse

hexdec
is_finite
Math Functions


Add a user to a security database (only for IB6 or later)

Firebird/InterBase Functions
ibase_affected_rows
Firebird/InterBase Functions
PHP Manual

ibase_add_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_add_user — Add a user to a security database (only for IB6 or later)

Description

bool ibase_add_user ( resource $service_handle , string $user_name , string $password [, string $first_name [, string $middle_name [, string $last_name ]]] )

PHP 4 uses server , dba_user_name and dba_user_password instead of service_handle parameter.

Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_modify_user() - Modify a user to a security database (only for IB6 or later)
  • ibase_delete_user() - Delete a user from a security database (only for IB6 or later)

Firebird/InterBase Functions
ibase_affected_rows
Firebird/InterBase Functions


Return the number of rows that were affected by the previous query

ibase_add_user
ibase_backup
Firebird/InterBase Functions
PHP Manual

ibase_affected_rows

(PHP 5)

ibase_affected_rows — Return the number of rows that were affected by the previous query

Description

int ibase_affected_rows ([ resource $link_identifier ] )

This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the specified transaction context.

Parameters

link_identifier

A transaction context. If link_identifier is a connection resource, its default transaction is used.

Return Values

Returns the number of rows as an integer.

See Also

  • ibase_query() - Execute a query on an InterBase database
  • ibase_execute() - Execute a previously prepared query

ibase_add_user
ibase_backup
Firebird/InterBase Functions


Initiates a backup task in the service manager and returns immediately

ibase_affected_rows
ibase_blob_add
Firebird/InterBase Functions
PHP Manual

ibase_backup

(PHP 5)

ibase_backup — Initiates a backup task in the service manager and returns immediately

Description

mixed ibase_backup ( resource $service_handle , string $source_db , string $dest_file [, int $options = 0 [, bool $verbose = false ]] )
Warning

This function is currently not documented; only its argument list is available.

ibase_affected_rows
ibase_blob_add
Firebird/InterBase Functions


Add data into a newly created blob

ibase_backup
ibase_blob_cancel
Firebird/InterBase Functions
PHP Manual

ibase_blob_add

(PHP 4, PHP 5)

ibase_blob_add — Add data into a newly created blob

Description

void ibase_blob_add ( resource $blob_handle , string $data )

ibase_blob_add() adds data into a blob created with ibase_blob_create().

Parameters

blob_handle

A blob handle opened with ibase_blob_create().

data

The data to be added.

Return Values

No value is returned.

See Also

  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data
  • ibase_blob_import() - Create blob, copy file in it, and close it

ibase_backup
ibase_blob_cancel
Firebird/InterBase Functions


Cancel creating blob

ibase_blob_add
ibase_blob_close
Firebird/InterBase Functions
PHP Manual

ibase_blob_cancel

(PHP 4, PHP 5)

ibase_blob_cancel — Cancel creating blob

Description

bool ibase_blob_cancel ( resource $blob_handle )

This function will discard a BLOB if it has not yet been closed by ibase_blob_close().

Parameters

blob_handle

A BLOB handle opened with ibase_blob_create().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data
  • ibase_blob_import() - Create blob, copy file in it, and close it

ibase_blob_add
ibase_blob_close
Firebird/InterBase Functions


Close blob

ibase_blob_cancel
ibase_blob_create
Firebird/InterBase Functions
PHP Manual

ibase_blob_close

(PHP 4, PHP 5)

ibase_blob_close — Close blob

Description

mixed ibase_blob_close ( resource $blob_handle )

This function closes a BLOB that has either been opened for reading by ibase_blob_open() or has been opened for writing by ibase_blob_create().

Parameters

blob_handle

A BLOB handle opened with ibase_blob_create() or ibase_blob_open().

Return Values

If the BLOB was being read, this function returns TRUE on success, if the BLOB was being written to, this function returns a string containing the BLOB id that has been assigned to it by the database. On failure, this function returns FALSE.

See Also

  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_open() - Open blob for retrieving data parts

ibase_blob_cancel
ibase_blob_create
Firebird/InterBase Functions


Create a new blob for adding data

ibase_blob_close
ibase_blob_echo
Firebird/InterBase Functions
PHP Manual

ibase_blob_create

(PHP 4, PHP 5)

ibase_blob_create — Create a new blob for adding data

Description

resource ibase_blob_create ([ resource $link_identifier = NULL ] )

ibase_blob_create() creates a new BLOB for filling with data.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

Return Values

Returns a BLOB handle for later use with ibase_blob_add() or FALSE on failure.

See Also

  • ibase_blob_add() - Add data into a newly created blob
  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_import() - Create blob, copy file in it, and close it

ibase_blob_close
ibase_blob_echo
Firebird/InterBase Functions


Output blob contents to browser

ibase_blob_create
ibase_blob_get
Firebird/InterBase Functions
PHP Manual

ibase_blob_echo

(PHP 4, PHP 5)

ibase_blob_echo — Output blob contents to browser

Description

bool ibase_blob_echo ( string $blob_id )
bool ibase_blob_echo ( resource $link_identifier , string $blob_id )

This function opens a BLOB for reading and sends its contents directly to standard output (the browser, in most cases).

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_blob_open() - Open blob for retrieving data parts
  • ibase_blob_close() - Close blob
  • ibase_blob_get() - Get len bytes data from open blob

ibase_blob_create
ibase_blob_get
Firebird/InterBase Functions


Get len bytes data from open blob

ibase_blob_echo
ibase_blob_import
Firebird/InterBase Functions
PHP Manual

ibase_blob_get

(PHP 4, PHP 5)

ibase_blob_get — Get len bytes data from open blob

Description

string ibase_blob_get ( resource $blob_handle , int $len )

This function returns at most len bytes from a BLOB that has been opened for reading by ibase_blob_open().

Note: It is not possible to read from a BLOB that has been opened for writing by ibase_blob_create().

Parameters

blob_handle

A BLOB handle opened with ibase_blob_open().

len

Size of returned data.

Return Values

Returns at most len bytes from the BLOB, or FALSE on failure.

Examples

Example #1 ibase_blob_get() example

<?php
$result    = ibase_query("SELECT blob_value FROM table");
$data      = ibase_fetch_object($result);
$blob_data = ibase_blob_info($data->BLOB_VALUE);
$blob_hndl = ibase_blob_open($data->BLOB_VALUE);
echo         ibase_blob_get($blob_hndl, $blob_data[0]);
?>

Whilst this example doesn't do much more than a 'ibase_blob_echo($data->BLOB_VALUE)' would do, it does show you how to get information into a $variable to manipulate as you please.

See Also

  • ibase_blob_open() - Open blob for retrieving data parts
  • ibase_blob_close() - Close blob
  • ibase_blob_echo() - Output blob contents to browser

ibase_blob_echo
ibase_blob_import
Firebird/InterBase Functions


Create blob, copy file in it, and close it

ibase_blob_get
ibase_blob_info
Firebird/InterBase Functions
PHP Manual

ibase_blob_import

(PHP 4, PHP 5)

ibase_blob_import — Create blob, copy file in it, and close it

Description

string ibase_blob_import ( resource $link_identifier , resource $file_handle )
string ibase_blob_import ( resource $file_handle )

This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

file_handle

The file handle is a handle returned by fopen().

Return Values

Returns the BLOB id on success, or FALSE on error.

Examples

Example #1 ibase_blob_import() example

<?php
$dbh = ibase_connect($host, $username, $password);
$filename = '/tmp/bar';

$fd = fopen($filename, 'r');
if ($fd) {

    $blob = ibase_blob_import($dbh, $fd);
    fclose($fd);

    if (!is_string($blob)) {
        // import failed
    } else {
        $query = "INSERT INTO foo (name, data) VALUES ('$filename', ?)";
        $prepared = ibase_prepare($dbh, $query);
        if (!ibase_execute($prepared, $blob)) {
            // record insertion failed
        }
    }
} else {
    // unable to open the data file
}
?>

See Also

  • ibase_blob_add() - Add data into a newly created blob
  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data

ibase_blob_get
ibase_blob_info
Firebird/InterBase Functions


Return blob length and other useful info

ibase_blob_import
ibase_blob_open
Firebird/InterBase Functions
PHP Manual

ibase_blob_info

(PHP 4, PHP 5)

ibase_blob_info — Return blob length and other useful info

Description

array ibase_blob_info ( resource $link_identifier , string $blob_id )
array ibase_blob_info ( string $blob_id )

Returns the BLOB length and other useful information.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

Return Values

Returns an array containing information about a BLOB. The information returned consists of the length of the BLOB, the number of segments it contains, the size of the largest segment, and whether it is a stream BLOB or a segmented BLOB.

ibase_blob_import
ibase_blob_open
Firebird/InterBase Functions


Open blob for retrieving data parts

ibase_blob_info
ibase_close
Firebird/InterBase Functions
PHP Manual

ibase_blob_open

(PHP 4, PHP 5)

ibase_blob_open — Open blob for retrieving data parts

Description

resource ibase_blob_open ( resource $link_identifier , string $blob_id )
resource ibase_blob_open ( string $blob_id )

Opens an existing BLOB for reading.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

Return Values

Returns a BLOB handle for later use with ibase_blob_get() or FALSE on failure.

See Also

  • ibase_blob_close() - Close blob
  • ibase_blob_echo() - Output blob contents to browser
  • ibase_blob_get() - Get len bytes data from open blob

ibase_blob_info
ibase_close
Firebird/InterBase Functions


Close a connection to an InterBase database

ibase_blob_open
ibase_commit_ret
Firebird/InterBase Functions
PHP Manual

ibase_close

(PHP 4, PHP 5)

ibase_close — Close a connection to an InterBase database

Description

bool ibase_close ([ resource $connection_id = NULL ] )

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). Default transaction on link is committed, other transactions are rolled back.

Parameters

connection_id

An InterBase link identifier returned from ibase_connect(). If omitted, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_connect() - Open a connection to an InterBase database
  • ibase_pconnect() - Open a persistent connection to an InterBase database

ibase_blob_open
ibase_commit_ret
Firebird/InterBase Functions


Commit a transaction

ibase_commit_ret
ibase_connect
Firebird/InterBase Functions
PHP Manual

ibase_commit

(PHP 4, PHP 5)

ibase_commit — Commit a transaction

Description

bool ibase_commit ([ resource $link_or_trans_identifier = NULL ] )

Commits a transaction.

Parameters

link_or_trans_identifier

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_commit_ret
ibase_connect
Firebird/InterBase Functions


Commit a transaction without closing it

ibase_close
ibase_commit
Firebird/InterBase Functions
PHP Manual

ibase_commit_ret

(PHP 5)

ibase_commit_ret — Commit a transaction without closing it

Description

bool ibase_commit_ret ([ resource $link_or_trans_identifier = NULL ] )

Commits a transaction without closing it.

Parameters

link_or_trans_identifier

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. The transaction context will be retained, so statements executed from within this transaction will not be invalidated.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_close
ibase_commit
Firebird/InterBase Functions


Open a connection to an InterBase database

ibase_commit
ibase_db_info
Firebird/InterBase Functions
PHP Manual

ibase_connect

(PHP 4, PHP 5)

ibase_connect — Open a connection to an InterBase database

Description

resource ibase_connect ([ string $database [, string $username [, string $password [, string $charset [, int $buffers [, int $dialect [, string $role [, int $sync ]]]]]]]] )

Establishes a connection to an InterBase server.

In case a second call is made to ibase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ibase_close().

Parameters

database

The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used.

username

The user name. Can be set with the ibase.default_user php.ini directive.

password

The password for username . Can be set with the ibase.default_password php.ini directive.

charset

charset is the default character set for a database.

buffers

buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.

dialect

dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries. Functional only with InterBase 6 and up.

role

Functional only with InterBase 5 and up.

sync

Return Values

Returns an InterBase link identifier on success, or FALSE on error.

Errors/Exceptions

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

Examples

Example #1 ibase_connect() example

<?php
$host = 'localhost:/path/to/your.gdb';

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    echo $row->email, "\n";
}
ibase_free_result($sth);
ibase_close($dbh);
?>

See Also

  • ibase_pconnect() - Open a persistent connection to an InterBase database
  • ibase_close() - Close a connection to an InterBase database

ibase_commit
ibase_db_info
Firebird/InterBase Functions


Request statistics about a database

ibase_connect
ibase_delete_user
Firebird/InterBase Functions
PHP Manual

ibase_db_info

(PHP 5)

ibase_db_info — Request statistics about a database

Description

string ibase_db_info ( resource $service_handle , string $db , int $action [, int $argument = 0 ] )
Warning

This function is currently not documented; only its argument list is available.

ibase_connect
ibase_delete_user
Firebird/InterBase Functions


Delete a user from a security database (only for IB6 or later)

ibase_db_info
ibase_drop_db
Firebird/InterBase Functions
PHP Manual

ibase_delete_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_delete_user — Delete a user from a security database (only for IB6 or later)

Description

bool ibase_delete_user ( resource $service_handle , string $user_name )

PHP 4 uses server , dba_user_name and dba_user_password instead of service_handle parameter.

Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_add_user() - Add a user to a security database (only for IB6 or later)
  • ibase_modify_user() - Modify a user to a security database (only for IB6 or later)

ibase_db_info
ibase_drop_db
Firebird/InterBase Functions


Drops a database

ibase_delete_user
ibase_errcode
Firebird/InterBase Functions
PHP Manual

ibase_drop_db

(PHP 5)

ibase_drop_db — Drops a database

Description

bool ibase_drop_db ([ resource $connection = NULL ] )

This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server.

Parameters

connection

An InterBase link identifier. If omitted, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_connect() - Open a connection to an InterBase database
  • ibase_pconnect() - Open a persistent connection to an InterBase database

ibase_delete_user
ibase_errcode
Firebird/InterBase Functions


Return an error code

ibase_drop_db
ibase_errmsg
Firebird/InterBase Functions
PHP Manual

ibase_errcode

(PHP 5)

ibase_errcode — Return an error code

Description

int ibase_errcode ( void )

Returns the error code that resulted from the most recent InterBase function call.

Return Values

Returns the error code as an integer, or FALSE if no error occurred.

See Also

  • ibase_errmsg() - Return error messages

ibase_drop_db
ibase_errmsg
Firebird/InterBase Functions


Return error messages

ibase_errcode
ibase_execute
Firebird/InterBase Functions
PHP Manual

ibase_errmsg

(PHP 4, PHP 5)

ibase_errmsg — Return error messages

Description

string ibase_errmsg ( void )

Returns the error message that resulted from the most recent InterBase function call.

Return Values

Returns the error message as a string, or FALSE if no error occurred.

See Also

  • ibase_errcode() - Return an error code

ibase_errcode
ibase_execute
Firebird/InterBase Functions


Execute a previously prepared query

ibase_errmsg
ibase_fetch_assoc
Firebird/InterBase Functions
PHP Manual

ibase_execute

(PHP 4, PHP 5)

ibase_execute — Execute a previously prepared query

Description

resource ibase_execute ( resource $query [, mixed $bind_arg [, mixed $... ]] )

Execute a query prepared by ibase_prepare().

This is a lot more effective than using ibase_query() if you are repeating a same kind of query several times with only some parameters changing.

Parameters

query

An InterBase query prepared by ibase_prepare().

bind_arg

...

Return Values

If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

Note: In PHP 5.0.0 and up, this function returns the number of rows affected by the query (if > 0 and applicable to the statement type). A query that succeeded, but did not affect any rows (e.g. an UPDATE of a non-existent record) will return TRUE.

Examples

Example #1 ibase_execute() example

<?php

$dbh = ibase_connect($host, $username, $password);

$updates = array(
    1 => 'Eric',
    5 => 'Filip',
    7 => 'Larry'
);

$query = ibase_prepare($dbh, "UPDATE FOO SET BAR = ? WHERE BAZ = ?");

foreach ($updates as $baz => $bar) {
    ibase_execute($query, $bar, $baz);
}

?>

See Also

  • ibase_query() - Execute a query on an InterBase database

ibase_errmsg
ibase_fetch_assoc
Firebird/InterBase Functions


Fetch a result row from a query as an associative array

ibase_execute
ibase_fetch_object
Firebird/InterBase Functions
PHP Manual

ibase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

ibase_fetch_assoc — Fetch a result row from a query as an associative array

Description

array ibase_fetch_assoc ( resource $result [, int $fetch_flag = 0 ] )

Fetch a result row from a query as an associative array.

ibase_fetch_assoc() fetches one row of data from the result . If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using ibase_fetch_row() or use alias names in your query.

Parameters

result

The result handle.

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

Return Values

Returns an associative array that corresponds to the fetched row. Subsequent calls will return the next row in the result set, or FALSE if there are no more rows.

See Also

  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_object() - Get an object from a InterBase database

ibase_execute
ibase_fetch_object
Firebird/InterBase Functions


Get an object from a InterBase database

ibase_fetch_assoc
ibase_fetch_row
Firebird/InterBase Functions
PHP Manual

ibase_fetch_object

(PHP 4, PHP 5)

ibase_fetch_object — Get an object from a InterBase database

Description

object ibase_fetch_object ( resource $result_id [, int $fetch_flag = 0 ] )

Fetches a row as a pseudo-object from a given result identifier.

Subsequent calls to ibase_fetch_object() return the next row in the result set.

Parameters

result_id

An InterBase result identifier obtained either by ibase_query() or ibase_execute().

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

Return Values

Returns an object with the next row information, or FALSE if there are no more rows.

Examples

Example #1 ibase_fetch_object() example

<?php
$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    echo $row->email . "\n";
}
ibase_close($dbh);
?>

See Also

  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_assoc() - Fetch a result row from a query as an associative array

ibase_fetch_assoc
ibase_fetch_row
Firebird/InterBase Functions


Fetch a row from an InterBase database

ibase_fetch_object
ibase_field_info
Firebird/InterBase Functions
PHP Manual

ibase_fetch_row

(PHP 4, PHP 5)

ibase_fetch_row — Fetch a row from an InterBase database

Description

array ibase_fetch_row ( resource $result_identifier [, int $fetch_flag = 0 ] )

ibase_fetch_row() fetches one row of data from the given result set.

Subsequent calls to ibase_fetch_row() return the next row in the result set, or FALSE if there are no more rows.

Parameters

result_identifier

An InterBase result identifier.

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 0.

See Also

  • ibase_fetch_assoc() - Fetch a result row from a query as an associative array
  • ibase_fetch_object() - Get an object from a InterBase database

ibase_fetch_object
ibase_field_info
Firebird/InterBase Functions


Get information about a field

ibase_fetch_row
ibase_free_event_handler
Firebird/InterBase Functions
PHP Manual

ibase_field_info

(PHP 4, PHP 5)

ibase_field_info — Get information about a field

Description

array ibase_field_info ( resource $result , int $field_number )

Returns an array with information about a field after a select query has been run.

Parameters

result

An InterBase result identifier.

field_number

Field offset.

Return Values

Returns an array with the following keys: name, alias, relation, length and type.

Examples

Example #1 ibase_field_info() example

<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i);
    echo "name: ". $col_info['name']. "\n";
    echo "alias: ". $col_info['alias']. "\n";
    echo "relation: ". $col_info['relation']. "\n";
    echo "length: ". $col_info['length']. "\n";
    echo "type: ". $col_info['type']. "\n";
}
?>

See Also

  • ibase_num_fields() - Get the number of fields in a result set

ibase_fetch_row
ibase_free_event_handler
Firebird/InterBase Functions


Cancels a registered event handler

ibase_field_info
ibase_free_query
Firebird/InterBase Functions
PHP Manual

ibase_free_event_handler

(PHP 5)

ibase_free_event_handler — Cancels a registered event handler

Description

bool ibase_free_event_handler ( resource $event )

This function causes the registered event handler specified by event to be cancelled. The callback function will no longer be called for the events it was registered to handle.

Parameters

event

An event resource, created by ibase_set_event_handler().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_set_event_handler() - Register a callback function to be called when events are posted

ibase_field_info
ibase_free_query
Firebird/InterBase Functions


Free memory allocated by a prepared query

ibase_free_event_handler
ibase_free_result
Firebird/InterBase Functions
PHP Manual

ibase_free_query

(PHP 4, PHP 5)

ibase_free_query — Free memory allocated by a prepared query

Description

bool ibase_free_query ( resource $query )

Frees a prepared query.

Parameters

query

A query prepared with ibase_prepare().

Return Values

Returns TRUE on success or FALSE on failure.

ibase_free_event_handler
ibase_free_result
Firebird/InterBase Functions


Free a result set

ibase_free_query
ibase_gen_id
Firebird/InterBase Functions
PHP Manual

ibase_free_result

(PHP 4, PHP 5)

ibase_free_result — Free a result set

Description

bool ibase_free_result ( resource $result_identifier )

Frees a result set.

Parameters

result_identifier

A result set created by ibase_query() or ibase_execute().

Return Values

Returns TRUE on success or FALSE on failure.

ibase_free_query
ibase_gen_id
Firebird/InterBase Functions


Increments the named generator and returns its new value

ibase_free_result
ibase_maintain_db
Firebird/InterBase Functions
PHP Manual

ibase_gen_id

(PHP 5)

ibase_gen_id — Increments the named generator and returns its new value

Description

mixed ibase_gen_id ( string $generator [, int $increment = 1 [, resource $link_identifier = NULL ]] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns new generator value as integer, or as string if the value is too big.

ibase_free_result
ibase_maintain_db
Firebird/InterBase Functions


Execute a maintenance command on the database server

ibase_gen_id
ibase_modify_user
Firebird/InterBase Functions
PHP Manual

ibase_maintain_db

(PHP 5)

ibase_maintain_db — Execute a maintenance command on the database server

Description

bool ibase_maintain_db ( resource $service_handle , string $db , int $action [, int $argument = 0 ] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_gen_id
ibase_modify_user
Firebird/InterBase Functions


Modify a user to a security database (only for IB6 or later)

ibase_maintain_db
ibase_name_result
Firebird/InterBase Functions
PHP Manual

ibase_modify_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_modify_user — Modify a user to a security database (only for IB6 or later)

Description

bool ibase_modify_user ( resource $service_handle , string $user_name , string $password [, string $first_name [, string $middle_name [, string $last_name ]]] )
Warning

This function is currently not documented; only its argument list is available.

PHP 4 uses server , dba_user_name and dba_user_password instead of service_handle parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_add_user() - Add a user to a security database (only for IB6 or later)
  • ibase_delete_user() - Delete a user from a security database (only for IB6 or later)

ibase_maintain_db
ibase_name_result
Firebird/InterBase Functions


Assigns a name to a result set

ibase_modify_user
ibase_num_fields
Firebird/InterBase Functions
PHP Manual

ibase_name_result

(PHP 5)

ibase_name_result — Assigns a name to a result set

Description

bool ibase_name_result ( resource $result , string $name )

This function assigns a name to a result set. This name can be used later in UPDATE|DELETE ... WHERE CURRENT OF name statements.

Parameters

result

An InterBase result set.

name

The name to be assigned.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ibase_name_result() example

<?php
$result = ibase_query("SELECT field1,field2 FROM table FOR UPDATE");
ibase_name_result($result, "my_cursor");

$updateqry = ibase_prepare("UPDATE table SET field2 = ? WHERE CURRENT OF my_cursor");

for ($i = 0; ibase_fetch_row($result); ++$i) {
    ibase_execute($updateqry, $i);
}
?>

See Also

  • ibase_prepare() - Prepare a query for later binding of parameter placeholders and execution
  • ibase_execute() - Execute a previously prepared query

ibase_modify_user
ibase_num_fields
Firebird/InterBase Functions


Get the number of fields in a result set

ibase_name_result
ibase_num_params
Firebird/InterBase Functions
PHP Manual

ibase_num_fields

(PHP 4, PHP 5)

ibase_num_fields — Get the number of fields in a result set

Description

int ibase_num_fields ( resource $result_id )

Get the number of fields in a result set.

Parameters

result_id

An InterBase result identifier.

Return Values

Returns the number of fields as an integer.

Examples

Example #1 ibase_num_fields() example

<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i);
    echo "name: " . $col_info['name'] . "\n";
    echo "alias: " . $col_info['alias'] . "\n";
    echo "relation: " . $col_info['relation'] . "\n";
    echo "length: " . $col_info['length'] . "\n";
    echo "type: " . $col_info['type'] . "\n";
}
?>

See Also

  • ibase_field_info() - Get information about a field

ibase_name_result
ibase_num_params
Firebird/InterBase Functions


Return the number of parameters in a prepared query

ibase_num_fields
ibase_param_info
Firebird/InterBase Functions
PHP Manual

ibase_num_params

(PHP 5)

ibase_num_params — Return the number of parameters in a prepared query

Description

int ibase_num_params ( resource $query )

This function returns the number of parameters in the prepared query specified by query . This is the number of binding arguments that must be present when calling ibase_execute().

Parameters

query

The prepared query handle.

Return Values

Returns the number of parameters as an integer.

See Also

  • ibase_prepare() - Prepare a query for later binding of parameter placeholders and execution
  • ibase_param_info() - Return information about a parameter in a prepared query

ibase_num_fields
ibase_param_info
Firebird/InterBase Functions


Return information about a parameter in a prepared query

ibase_num_params
ibase_pconnect
Firebird/InterBase Functions
PHP Manual

ibase_param_info

(PHP 5)

ibase_param_info — Return information about a parameter in a prepared query

Description

array ibase_param_info ( resource $query , int $param_number )

Returns an array with information about a parameter after a query has been prepared.

Parameters

query

An InterBase prepared query handle.

param_number

Parameter offset.

Return Values

Returns an array with the following keys: name, alias, relation, length and type.

See Also

  • ibase_field_info() - Get information about a field
  • ibase_num_params() - Return the number of parameters in a prepared query

ibase_num_params
ibase_pconnect
Firebird/InterBase Functions


Open a persistent connection to an InterBase database

ibase_param_info
ibase_prepare
Firebird/InterBase Functions
PHP Manual

ibase_pconnect

(PHP 4, PHP 5)

ibase_pconnect — Open a persistent connection to an InterBase database

Description

resource ibase_pconnect ([ string $database [, string $username [, string $password [, string $charset [, int $buffers [, int $dialect [, string $role [, int $sync ]]]]]]]] )

Opens a persistent connection to an InterBase database.

ibase_pconnect() acts very much like ibase_connect() with two major differences.

First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.

Parameters

database

The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used.

username

The user name. Can be set with the ibase.default_user php.ini directive.

password

The password for username . Can be set with the ibase.default_password php.ini directive.

charset

charset is the default character set for a database.

buffers

buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.

dialect

dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries. Functional only with InterBase 6 and up.

role

Functional only with InterBase 5 and up.

sync

Return Values

Returns an InterBase link identifier on success, or FALSE on error.

See Also

  • ibase_close() - Close a connection to an InterBase database
  • ibase_connect() - Open a connection to an InterBase database

ibase_param_info
ibase_prepare
Firebird/InterBase Functions


Prepare a query for later binding of parameter placeholders and execution

ibase_pconnect
ibase_query
Firebird/InterBase Functions
PHP Manual

ibase_prepare

(PHP 4, PHP 5)

ibase_prepare — Prepare a query for later binding of parameter placeholders and execution

Description

resource ibase_prepare ( string $query )
resource ibase_prepare ( resource $link_identifier , string $query )
resource ibase_prepare ( resource $link_identifier , string $trans , string $query )

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

Parameters

query

An InterBase query.

Return Values

Returns a prepared query handle, or FALSE on error.

ibase_pconnect
ibase_query
Firebird/InterBase Functions


Execute a query on an InterBase database

ibase_prepare
ibase_restore
Firebird/InterBase Functions
PHP Manual

ibase_query

(PHP 4, PHP 5)

ibase_query — Execute a query on an InterBase database

Description

resource ibase_query ([ resource $link_identifier ], string $query [, int $bind_args ] )

Performs a query on an InterBase database.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

query

An InterBase query.

bind_args

Return Values

If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

Note: In PHP 5.0.0 and up, this function will return the number of rows affected by the query for INSERT, UPDATE and DELETE statements. In order to retain backward compatibility, it will return TRUE for these statements if the query succeeded without affecting any rows.

Errors/Exceptions

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

Changelog

Version | Description
5.3.1 | On success the function now returns TRUE if there were no affected rows, where it previously returned 0 (a zero followed by an empty space).

Examples

Example #1 ibase_query() example

<?php

$host = 'localhost:/path/to/your.gdb';

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';

$sth = ibase_query($dbh, $stmt) or die(ibase_errmsg());

?>

See Also

  • ibase_errmsg() - Return error messages
  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_object() - Get an object from a InterBase database
  • ibase_free_result() - Free a result set

ibase_prepare
ibase_restore
Firebird/InterBase Functions


Initiates a restore task in the service manager and returns immediately

ibase_query
ibase_rollback_ret
Firebird/InterBase Functions
PHP Manual

ibase_restore

(PHP 5)

ibase_restore — Initiates a restore task in the service manager and returns immediately

Description

mixed ibase_restore ( resource $service_handle , string $source_file , string $dest_db [, int $options = 0 [, bool $verbose = false ]] )
Warning

This function is currently not documented; only its argument list is available.

ibase_query
ibase_rollback_ret
Firebird/InterBase Functions


Roll back a transaction

ibase_rollback_ret
ibase_server_info
Firebird/InterBase Functions
PHP Manual

ibase_rollback

(PHP 4, PHP 5)

ibase_rollback — Roll back a transaction

Description

bool ibase_rollback ([ resource $link_or_trans_identifier = NULL ] )

Rolls back a transaction.

Parameters

link_or_trans_identifier

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_rollback_ret
ibase_server_info
Firebird/InterBase Functions


Roll back a transaction without closing it

ibase_restore
ibase_rollback
Firebird/InterBase Functions
PHP Manual

ibase_rollback_ret

(PHP 5)

ibase_rollback_ret — Roll back a transaction without closing it

Description

bool ibase_rollback_ret ([ resource $link_or_trans_identifier = NULL ] )

Rolls back a transaction without closing it.

Parameters

link_or_trans_identifier

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_restore
ibase_rollback
Firebird/InterBase Functions


Request information about a database server

ibase_rollback
ibase_service_attach
Firebird/InterBase Functions
PHP Manual

ibase_server_info

(PHP 5)

ibase_server_info — Request information about a database server

Description

string ibase_server_info ( resource $service_handle , int $action )
Warning

This function is currently not documented; only its argument list is available.

ibase_rollback
ibase_service_attach
Firebird/InterBase Functions


Connect to the service manager

ibase_server_info
ibase_service_detach
Firebird/InterBase Functions
PHP Manual

ibase_service_attach

(PHP 5)

ibase_service_attach — Connect to the service manager

Description

resource ibase_service_attach ( string $host , string $dba_username , string $dba_password )
Warning

This function is currently not documented; only its argument list is available.

ibase_server_info
ibase_service_detach
Firebird/InterBase Functions


Disconnect from the service manager

ibase_service_attach
ibase_set_event_handler
Firebird/InterBase Functions
PHP Manual

ibase_service_detach

(PHP 5)

ibase_service_detach — Disconnect from the service manager

Description

bool ibase_service_detach ( resource $service_handle )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

ibase_service_attach
ibase_set_event_handler
Firebird/InterBase Functions


Register a callback function to be called when events are posted

ibase_service_detach
ibase_timefmt
Firebird/InterBase Functions
PHP Manual

ibase_set_event_handler

(PHP 5)

ibase_set_event_handler — Register a callback function to be called when events are posted

Description

resource ibase_set_event_handler ( callback $event_handler , string $event_name1 [, string $event_name2 [, string $... ]] )
resource ibase_set_event_handler ( resource $connection , callback $event_handler , string $event_name1 [, string $event_name2 [, string $... ]] )

This function registers a PHP user function as event handler for the specified events.

Parameters

event_handler

The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database.

The callback must return FALSE if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.

event_name1

An event name.

event_name2

At most 15 events allowed.

Return Values

The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().

Examples

Example #1 ibase_set_event_handler() example

<?php

function event_handler($event_name, $link)
{
    if ($event_name == "NEW ORDER") {
        // process new order
        ibase_query($link, "UPDATE orders SET status='handled'");
    } else if ($event_name == "DB_SHUTDOWN") {
        // free event handler
        return false;
    }
}

ibase_set_event_handler($link, "event_handler", "NEW_ORDER", "DB_SHUTDOWN");
?>

See Also

  • ibase_free_event_handler() - Cancels a registered event handler
  • ibase_wait_event() - Wait for an event to be posted by the database

ibase_service_detach
ibase_timefmt
Firebird/InterBase Functions


Sets the format of timestamp, date and time type columns returned from queries

ibase_set_event_handler
ibase_trans
Firebird/InterBase Functions
PHP Manual

ibase_timefmt

(PHP 4)

ibase_timefmt — Sets the format of timestamp, date and time type columns returned from queries

Description

bool ibase_timefmt ( string $format [, int $columntype ] )

Sets the format of timestamp, date or time type columns returned from queries.

You can set defaults for these formats with the PHP configuration directives ibase.timestampformat, ibase.dateformat and ibase.timeformat.

Note: This function has been removed from PHP 5, use ini_set() instead.

Parameters

format

Internally, the columns are formatted by c-function strftime(), so refer to its documentation regarding to the format of the string.

columntype

columntype is one of the constants IBASE_TIMESTAMP, IBASE_DATE and IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards compatibility.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ibase_timefmt() example

<?php
/* InterBase 6 TIME-type columns will be returned in
 * the form '05 hours 37 minutes'. */
ibase_timefmt("%H hours %M minutes", IBASE_TIME);
?>

ibase_set_event_handler
ibase_trans
Firebird/InterBase Functions


Begin a transaction

ibase_timefmt
ibase_wait_event
Firebird/InterBase Functions
PHP Manual

ibase_trans

(PHP 4, PHP 5)

ibase_trans — Begin a transaction

Description

resource ibase_trans ([ int $trans_args [, resource $link_identifier ]] )
resource ibase_trans ([ resource $link_identifier [, int $trans_args ]] )

Begins a transaction.

Note: The behaviour of this function has been changed in PHP 5.0.0. The first call to ibase_trans() will not return the default transaction of a connection. All transactions started by ibase_trans() will be rolled back at the end of the script if they were not committed or rolled back by either ibase_commit() or ibase_rollback().

Note: In PHP 5.0.0. and up, this function will accept multiple trans_args and link_identifier arguments. This allows transactions over multiple database connections, which are committed using a 2-phase commit algorithm. This means you can rely on the updates to either succeed in every database, or fail in every database. It does NOT mean you can use tables from different databases in the same query!
If you use transactions over multiple databases, you will have to specify both the link_id and transaction_id in calls to ibase_query() and ibase_prepare().

Parameters

trans_args

trans_args can be a combination of IBASE_READ, IBASE_WRITE, IBASE_COMMITTED, IBASE_CONSISTENCY, IBASE_CONCURRENCY, IBASE_REC_VERSION, IBASE_REC_NO_VERSION, IBASE_WAIT and IBASE_NOWAIT.

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

Return Values

Returns a transaction handle, or FALSE on error.

ibase_timefmt
ibase_wait_event
Firebird/InterBase Functions


Wait for an event to be posted by the database

ibase_trans
Informix
Firebird/InterBase Functions
PHP Manual

ibase_wait_event

(PHP 5)

ibase_wait_event — Wait for an event to be posted by the database

Description

string ibase_wait_event ( string $event_name1 [, string $event_name2 [, string $... ]] )
string ibase_wait_event ( resource $connection , string $event_name1 [, string $event_name2 [, string $... ]] )

This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.

Parameters

event_name1

The event name.

event_name2

...

Return Values

Returns the name of the event that was posted.

See Also

  • ibase_set_event_handler() - Register a callback function to be called when events are posted
  • ibase_free_event_handler() - Cancels a registered event handler

ibase_trans
Informix
Firebird/InterBase Functions


Convert string to requested character encoding

iconv_substr
ob_iconv_handler
iconv Functions
PHP Manual

iconv

(PHP 4 >= 4.0.5, PHP 5)

iconv — Convert string to requested character encoding

Description

string iconv ( string $in_charset , string $out_charset , string $str )

Performs a character set conversion on the string str from in_charset to out_charset .

Parameters

in_charset

The input charset.

out_charset

The output charset.

If you append the string //TRANSLIT to out_charset transliteration is activated. This means that when a character can't be represented in the target charset, it can be approximated through one or several similarly looking characters. If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded. Otherwise, str is cut from the first illegal character and an E_NOTICE is generated.

str

The string to be converted.

Return Values

Returns the converted string or FALSE on failure.

Examples

Example #1 iconv() example

<?php
$text = "This is the Euro symbol '€'.";

echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE   : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
echo 'Plain    : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;

?>

The above example will output something similar to:

Original : This is the Euro symbol '€'.
TRANSLIT : This is the Euro symbol 'EUR'.
IGNORE   : This is the Euro symbol ''.
Plain    :
Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7
This is the Euro symbol '

iconv_substr
ob_iconv_handler
iconv Functions


Retrieve internal configuration variables of iconv extension

iconv Functions
iconv_mime_decode_headers
iconv Functions
PHP Manual

iconv_get_encoding

(PHP 4 >= 4.0.5, PHP 5)

iconv_get_encoding — Retrieve internal configuration variables of iconv extension

Description

mixed iconv_get_encoding ([ string $type = "all" ] )

Retrieve internal configuration variables of iconv extension.

Parameters

type

The value of the optional type can be:

  • all
  • input_encoding
  • output_encoding
  • internal_encoding

Return Values

Returns the current value of the internal configuration variable if successful or FALSE on failure.

If type is omitted or set to "all", iconv_get_encoding() returns an array that stores all these variables.

Examples

Example #1 iconv_get_encoding() example

<pre>
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?>
</pre>

The above example will output:

Array
(
    [input_encoding] => ISO-8859-1
    [output_encoding] => ISO-8859-1
    [internal_encoding] => UTF-8
)

See Also

  • iconv_set_encoding() - Set current setting for character encoding conversion
  • ob_iconv_handler() - Convert character encoding as output buffer handler

iconv Functions
iconv_mime_decode_headers
iconv Functions


Decodes a MIME header field

iconv_mime_decode_headers
iconv_mime_encode
iconv Functions
PHP Manual

iconv_mime_decode

(PHP 5)

iconv_mime_decode — Decodes a MIME header field

Description

string iconv_mime_decode ( string $encoded_header [, int $mode = 0 [, string $charset = ini_set("iconv.internal_encoding") ]] )

Decodes a MIME header field.

Parameters

encoded_header

The encoded header, as a string.

mode

mode determines the behaviour in the event iconv_mime_decode() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.

Bitmasks acceptable to iconv_mime_decode()
Value | Constant | Description
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in » RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers.
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

charset

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_encoding will be used.

Return Values

Returns a decoded MIME field on success, or FALSE if an error occurs during the decoding.

Examples

Example #1 iconv_mime_decode() example

<?php
// This yields "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
                       0, "ISO-8859-1");
?>

See Also

  • iconv_mime_decode_headers() - Decodes multiple MIME header fields at once
  • mb_decode_mimeheader() - Decode string in MIME header field
  • imap_mime_header_decode() - Decode MIME header elements
  • imap_base64() - Decode BASE64 encoded text
  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

iconv_mime_decode_headers
iconv_mime_encode
iconv Functions


Decodes multiple MIME header fields at once

iconv_get_encoding
iconv_mime_decode
iconv Functions
PHP Manual

iconv_mime_decode_headers

(PHP 5)

iconv_mime_decode_headers — Decodes multiple MIME header fields at once

Description

array iconv_mime_decode_headers ( string $encoded_headers [, int $mode = 0 [, string $charset = ini_set("iconv.internal_encoding") ]] )

Decodes multiple MIME header fields at once.

Parameters

encoded_headers

The encoded headers, as a string.

mode

mode determines the behaviour in the event iconv_mime_decode_headers() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.

Bitmasks acceptable to iconv_mime_decode_headers()
Value | Constant | Description
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in » RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers.
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

charset

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_encoding will be used.

Return Values

Returns an associative array that holds a whole set of MIME header fields specified by encoded_headers on success, or FALSE if an error occurs during the decoding.

Each key of the return value represents an individual field name and the corresponding element represents a field value. If more than one field of the same name are present, iconv_mime_decode_headers() automatically incorporates them into a numerically indexed array in the order of occurrence.

Examples

Example #1 iconv_mime_decode_headers() example

<?php
$headers_string = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
    with SMTP id example for <example@example.com>;
    Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
    (envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000

EOF;

$headers =  iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");
print_r($headers);
?>

The above example will output:

Array
(
    [Subject] => Prüfung Prüfung
    [To] => example@example.com
    [Date] => Thu, 1 Jan 1970 00:00:00 +0000
    [Message-Id] => <example@example.com>
    [Received] => Array
        (
            [0] => from localhost (localhost [127.0.0.1]) by localhost with SMTP id example for <example@example.com>; Thu, 1 Jan 1970 00:00:00 +0000 (UTC) (envelope-from example-return-0000-example=example.com@example.com)
            [1] => (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000
        )

)

See Also

  • iconv_mime_decode() - Decodes a MIME header field
  • mb_decode_mimeheader() - Decode string in MIME header field
  • imap_mime_header_decode() - Decode MIME header elements
  • imap_base64() - Decode BASE64 encoded text
  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

iconv_get_encoding
iconv_mime_decode
iconv Functions


Composes a MIME header field

iconv_mime_decode
iconv_set_encoding
iconv Functions
PHP Manual

iconv_mime_encode

(PHP 5)

iconv_mime_encode — Composes a MIME header field

Description

string iconv_mime_encode ( string $field_name , string $field_value [, array $preferences = NULL ] )

Composes and returns a string that represents a valid MIME header field, which looks like the following:

Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile
In the above example, "Subject" is the field name and the portion that begins with "=?ISO-8859-1?..." is the field value.

Parameters

field_name

The field name.

field_value

The field value.

preferences

You can control the behaviour of iconv_mime_encode() by specifying an associative array that contains configuration items to the optional third parameter preferences . The items supported by iconv_mime_encode() are listed below. Note that item names are treated case-sensitive.

Configuration items supported by iconv_mime_encode()
Item | Type | Description | Default value | Example
scheme | string | Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for base64 encoding scheme and "Q" stands for quoted-printable encoding scheme. | B | B
input-charset | string | Specifies the character set in which the first parameter field_name and the second parameter field_value are presented. If not given, iconv_mime_encode() assumes those parameters are presented to it in the iconv.internal_encoding ini setting. | iconv.internal_encoding | ISO-8859-1
output-charset | string | Specifies the character set to use to compose the MIME header. If not given, the same value as input-charset will be used. | iconv.internal_encoding | UTF-8
line-length | integer | Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to » RFC2822 - Internet Message Format. If not given, the length will be limited to 76 characters. | 76 | 996
line-break-chars | string | Specifies the sequence of characters to append to each line as an end-of-line sign when "folding" is performed on a long header field. If not given, this defaults to "\r\n" (CR LF). Note that this parameter is always treated as an ASCII string regardless of the value of input-charset. | \r\n | \n

Return Values

Returns an encoded MIME field on success, or FALSE if an error occurs during the encoding.

Examples

Example #1 iconv_mime_encode() example

<?php
$preferences = array(
    "input-charset" => "ISO-8859-1",
    "output-charset" => "UTF-8",
    "line-length" => 76,
    "line-break-chars" => "\n"
);
$preferences["scheme"] = "Q";
// This yields "Subject: =?UTF-8?Q?Pr=C3=BCfung_Pr=C3=BCfung?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);

$preferences["scheme"] = "B";
// This yields "Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);
?>

See Also

  • imap_binary() - Convert an 8bit string to a base64 string
  • mb_encode_mimeheader() - Encode string for MIME header
  • imap_8bit() - Convert an 8bit string to a quoted-printable string
  • quoted_printable_encode() - Convert a 8 bit string to a quoted-printable string

iconv_mime_decode
iconv_set_encoding
iconv Functions


Set current setting for character encoding conversion

iconv_mime_encode
iconv_strlen
iconv Functions
PHP Manual

iconv_set_encoding

(PHP 4 >= 4.0.5, PHP 5)

iconv_set_encoding — Set current setting for character encoding conversion

Description

bool iconv_set_encoding ( string $type , string $charset )

Changes the value of the internal configuration variable specified by type to charset .

Parameters

type

The value of type can be any one of those:

  • input_encoding
  • output_encoding
  • internal_encoding

charset

The character set.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 iconv_set_encoding() example

<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
?>

See Also

  • iconv_get_encoding() - Retrieve internal configuration variables of iconv extension
  • ob_iconv_handler() - Convert character encoding as output buffer handler

iconv_mime_encode
iconv_strlen
iconv Functions


Returns the character count of string

iconv_set_encoding
iconv_strpos
iconv Functions
PHP Manual

iconv_strlen

(PHP 5)

iconv_strlen — Returns the character count of string

Description

int iconv_strlen ( string $str [, string $charset = ini_set("iconv.internal_encoding") ] )

In contrast to strlen(), iconv_strlen() counts the occurrences of characters in the given byte sequence str on the basis of the specified character set, the result of which is not necessarily identical to the length of the string in byte.

Parameters

str

The string.

charset

If charset parameter is omitted, str is assumed to be encoded in iconv.internal_encoding.

Return Values

Returns the character count of str , as an integer.

See Also

  • strlen() - Get string length
  • mb_strlen() - Get string length

iconv_set_encoding
iconv_strpos
iconv Functions


Finds position of first occurrence of a needle within a haystack

iconv_strlen
iconv_strrpos
iconv Functions
PHP Manual

iconv_strpos

(PHP 5)

iconv_strpos — Finds position of first occurrence of a needle within a haystack

Description

int iconv_strpos ( string $haystack , string $needle [, int $offset = 0 [, string $charset = ini_set("iconv.internal_encoding") ]] )

Finds position of first occurrence of a needle within a haystack.

In contrast to strpos(), the return value of iconv_strpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset .

Parameters

haystack

The entire string.

needle

The searched substring.

offset

The optional offset parameter specifies the position from which the search should be performed.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_encoding.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

Return Values

Returns the numeric position of the first occurrence of needle in haystack .

If needle is not found, iconv_strpos() will return FALSE.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See Also

  • strpos() - Find position of first occurrence of a string
  • iconv_strrpos() - Finds the last occurrence of a needle within a haystack
  • mb_strpos() - Find position of first occurrence of string in a string

iconv_strlen
iconv_strrpos
iconv Functions


Finds the last occurrence of a needle within a haystack

iconv_strpos
iconv_substr
iconv Functions
PHP Manual

iconv_strrpos

(PHP 5)

iconv_strrpos — Finds the last occurrence of a needle within a haystack

Description

int iconv_strrpos ( string $haystack , string $needle [, string $charset = ini_set("iconv.internal_encoding") ] )

In contrast to strpos(), the return value of iconv_strrpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found.

Parameters

haystack

The entire string.

needle

The searched substring.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_encoding.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

Return Values

Returns the numeric position of the last occurrence of needle in haystack . The characters are counted on the basis of the specified character set charset .

If needle is not found, iconv_strrpos() will return FALSE.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See Also

  • strrpos() - Find position of last occurrence of a char in a string
  • iconv_strpos() - Finds position of first occurrence of a needle within a haystack
  • mb_strrpos() - Find position of last occurrence of a string in a string

iconv_strpos
iconv_substr
iconv Functions


Cut out part of a string

iconv_strrpos
iconv
iconv Functions
PHP Manual

iconv_substr

(PHP 5)

iconv_substr — Cut out part of a string

Description

string iconv_substr ( string $str , int $offset [, int $length = strlen($str) [, string $charset = ini_set("iconv.internal_encoding") ]] )

Cuts a portion of str specified by the offset and length parameters.

Parameters

str

The original string.

offset

If offset is non-negative, iconv_substr() cuts the portion out of str beginning at offset 'th character, counting from zero.

If offset is negative, iconv_substr() cuts out the portion beginning at the position, offset characters away from the end of str .

length

If length is given and is positive, the return value will contain at most length characters of the portion that begins at offset (depending on the length of string ).

If negative length is passed, iconv_substr() cuts the portion out of str from the offset 'th character up to the character that is length characters away from the end of the string. In case offset is also negative, the start position is calculated beforehand according to the rule explained above.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_encoding.

Note that offset and length parameters are always deemed to represent offsets that are calculated on the basis of the character set determined by charset , whilst the counterpart substr() always takes these for byte offsets.

Return Values

Returns the portion of str specified by the offset and length parameters.

If str is shorter than offset characters long, FALSE will be returned.

See Also

  • substr() - Return part of a string
  • mb_substr() - Get part of string
  • mb_strcut() - Get part of string

iconv_strrpos
iconv
iconv Functions


Get the long name of an ID3v2 frame

ID3 Functions
id3_get_frame_short_name
ID3 Functions
PHP Manual

id3_get_frame_long_name

(PECL id3 >= 0.2)

id3_get_frame_long_name — Get the long name of an ID3v2 frame

Description

string id3_get_frame_long_name ( string $frameId )

id3_get_frame_long_name() returns the long name for an ID3v2 frame.

Parameters

frameId

An ID3v2 frame

Return Values

Returns the frame long name or FALSE on errors.

Examples

Example #1 id3_get_frame_long_name() example

<?php
$longName = id3_get_frame_long_name("TOLY");
echo $longName;
?>

The above example will output:

Original lyricist(s)/text writer(s)

See Also

  • id3_get_frame_short_name() - Get the short name of an ID3v2 frame

ID3 Functions
id3_get_frame_short_name
ID3 Functions


Get the short name of an ID3v2 frame

id3_get_frame_long_name
id3_get_genre_id
ID3 Functions
PHP Manual

id3_get_frame_short_name

(PECL id3 >= 0.2)

id3_get_frame_short_name — Get the short name of an ID3v2 frame

Description

string id3_get_frame_short_name ( string $frameId )

id3_get_frame_short_name() returns the short name for an ID3v2 frame.

Parameters

frameId

An ID3v2 frame

Return Values

Returns the frame short name or FALSE on errors.

The values returned by id3_get_frame_short_name() are used in the array returned by id3_get_tag().

Examples

Example #1 id3_get_frame_short_name() example

<?php
$shortName = id3_get_frame_short_name("TOLY");
echo $shortName;
?>

The above example will output:

originalLyricist

See Also

  • id3_get_frame_long_name() - Get the long name of an ID3v2 frame

id3_get_frame_long_name
id3_get_genre_id
ID3 Functions


Get the id for a genre

id3_get_frame_short_name
id3_get_genre_list
ID3 Functions
PHP Manual

id3_get_genre_id

(PECL id3 >= 0.1)

id3_get_genre_id — Get the id for a genre

Description

int id3_get_genre_id ( string $genre )

id3_get_genre_id() returns the id for a genre.

Parameters

genre

An integer ranging from 0 to 147

Return Values

The genre id or FALSE on errors.

Examples

Example #1 id3_get_genre_id() example

<?php
$id = id3_get_genre_id("Alternative");
echo $id;
?>

The above example will output:

20

See Also

  • id3_get_genre_name() - Get the name for a genre id
  • id3_get_genre_list() - Get all possible genre values

id3_get_frame_short_name
id3_get_genre_list
ID3 Functions


Get all possible genre values

id3_get_genre_id
id3_get_genre_name
ID3 Functions
PHP Manual

id3_get_genre_list

(PECL id3 >= 0.1)

id3_get_genre_list — Get all possible genre values

Description

array id3_get_genre_list ( void )

id3_get_genre_list() returns an array containing all possible genres that may be stored in an ID3 tag. This list has been created by Eric Kemp and later extended by WinAmp.

This function is useful to provide you users a list of genres from which they may choose one. When updating the ID3 tag you will always have to specify the genre as an integer ranging from 0 to 147.

Return Values

Returns an array containing all possible genres that may be stored in an ID3 tag.

Examples

Example #1 id3_get_genre_list() example

<?php
$genres = id3_get_genre_list();
print_r($genres);
?>

The above example will output:

Array
(
    [0] => Blues
    [1] => Classic Rock
    [2] => Country
    [3] => Dance
    [4] => Disco
    [5] => Funk
    [6] => Grunge
    [7] => Hip-Hop
    [8] => Jazz
    [9] => Metal
    [10] => New Age
    [11] => Oldies
    [12] => Other
    [13] => Pop
    [14] => R&B
    [15] => Rap
    [16] => Reggae
    [17] => Rock
    [18] => Techno
    [19] => Industrial
    [20] => Alternative
    [21] => Ska
    [22] => Death Metal
    [23] => Pranks
    [24] => Soundtrack
    [25] => Euro-Techno
    [26] => Ambient
    [27] => Trip-Hop
    [28] => Vocal
    [29] => Jazz+Funk
    [30] => Fusion
    [31] => Trance
    [32] => Classical
    [33] => Instrumental
    [34] => Acid
    [35] => House
    [36] => Game
    [37] => Sound Clip
    [38] => Gospel
    [39] => Noise
    [40] => Alternative Rock
    [41] => Bass
    [42] => Soul
    [43] => Punk
    [44] => Space
    [45] => Meditative
    [46] => Instrumental Pop
    [47] => Instrumental Rock
    [48] => Ethnic
    [49] => Gothic
    [50] => Darkwave
    [51] => Techno-Industrial
    [52] => Electronic
    [53] => Pop-Folk
    [54] => Eurodance
    [55] => Dream
    [56] => Southern Rock
    [57] => Comedy
    [58] => Cult
    [59] => Gangsta
    [60] => Top 40
    [61] => Christian Rap
    [62] => Pop/Funk
    [63] => Jungle
    [64] => Native US
    [65] => Cabaret
    [66] => New Wave
    [67] => Psychadelic
    [68] => Rave
    [69] => Showtunes
    [70] => Trailer
    [71] => Lo-Fi
    [72] => Tribal
    [73] => Acid Punk
    [74] => Acid Jazz
    [75] => Polka
    [76] => Retro
    [77] => Musical
    [78] => Rock & Roll
    [79] => Hard Rock
    [80] => Folk
    [81] => Folk-Rock
    [82] => National Folk
    [83] => Swing
    [84] => Fast Fusion
    [85] => Bebob
    [86] => Latin
    [87] => Revival
    [88] => Celtic
    [89] => Bluegrass
    [90] => Avantgarde
    [91] => Gothic Rock
    [92] => Progressive Rock
    [93] => Psychedelic Rock
    [94] => Symphonic Rock
    [95] => Slow Rock
    [96] => Big Band
    [97] => Chorus
    [98] => Easy Listening
    [99] => Acoustic
    [100] => Humour
    [101] => Speech
    [102] => Chanson
    [103] => Opera
    [104] => Chamber Music
    [105] => Sonata
    [106] => Symphony
    [107] => Booty Bass
    [108] => Primus
    [109] => Porn Groove
    [110] => Satire
    [111] => Slow Jam
    [112] => Club
    [113] => Tango
    [114] => Samba
    [115] => Folklore
    [116] => Ballad
    [117] => Power Ballad
    [118] => Rhytmic Soul
    [119] => Freestyle
    [120] => Duet
    [121] => Punk Rock
    [122] => Drum Solo
    [123] => Acapella
    [124] => Euro-House
    [125] => Dance Hall
    [126] => Goa
    [127] => Drum & Bass
    [128] => Club-House
    [129] => Hardcore
    [130] => Terror
    [131] => Indie
    [132] => BritPop
    [133] => Negerpunk
    [134] => Polsk Punk
    [135] => Beat
    [136] => Christian Gangsta
    [137] => Heavy Metal
    [138] => Black Metal
    [139] => Crossover
    [140] => Contemporary C
    [141] => Christian Rock
    [142] => Merengue
    [143] => Salsa
    [144] => Thrash Metal
    [145] => Anime
    [146] => JPop
    [147] => SynthPop
)

See Also

  • id3_get_genre_name() - Get the name for a genre id
  • id3_get_genre_id() - Get the id for a genre

id3_get_genre_id
id3_get_genre_name
ID3 Functions


Get the name for a genre id

id3_get_genre_list
id3_get_tag
ID3 Functions
PHP Manual

id3_get_genre_name

(PECL id3 >= 0.1)

id3_get_genre_name — Get the name for a genre id

Description

string id3_get_genre_name ( int $genre_id )

id3_get_genre_name() returns the name for a genre id.

Parameters

genre_id

An integer ranging from 0 to 147

Return Values

Returns the name as a string.

Examples

Example #1 id3_get_genre_name() example

<?php
$genre = id3_get_genre_name(20);
echo $genre;
?>

The above example will output:

Alternative

See Also

  • id3_get_genre_list() - Get all possible genre values
  • id3_get_genre_id() - Get the id for a genre

id3_get_genre_list
id3_get_tag
ID3 Functions


Get all information stored in an ID3 tag

id3_get_genre_name
id3_get_version
ID3 Functions
PHP Manual

id3_get_tag

(PECL id3 >= 0.1)

id3_get_tag — Get all information stored in an ID3 tag

Description

array id3_get_tag ( string $filename [, int $version = ID3_BEST ] )

id3_get_tag() is used to get all information stored in the id3 tag of the specified file.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags

Since version 0.2 id3_get_tag() also supports ID3 tags of version 2.2, 2.3 and 2.4. To extract information from these tags, pass one of the constants ID3_V2_2, ID3_V2_3 or ID3_V2_4 as the second parameter. ID3 v2.x tags can contain a lot more information about the MP3 file than ID3 v1.x tags.

Return Values

Returns an associative array with various keys like: title, artist, ..

The key genre will contain an integer between 0 and 147. You may use id3_get_genre_name() to convert it to a human readable string.

Examples

Example #1 id3_get_tag() example

<?php
$tag = id3_get_tag( "path/to/example.mp3" );
print_r($tag);
?>

The above example will output something similar to:

Array
(
    [title] => DN-38416
    [artist] => Re:\Legion
    [album] => Reflections
    [year] => 2004
    [genre] => 19
)

Example #2 id3_get_tag() example

<?php
$tag = id3_get_tag( "path/to/example2.mp3", ID3_V2_3 );
print_r($tag);
?>

The above example will output something similar to:

Array
(
    [copyright] => Dirty Mac
    [originalArtist] => Dirty Mac
    [composer] => Marcus Götze
    [artist] => Dirty Mac
    [title] => Little Big Man
    [album] => Demo-Tape
    [track] => 5/12
    [genre] => (17)Rock
    [year] => 2001
)

See Also

  • id3_set_tag() - Update information stored in an ID3 tag
  • id3_remove_tag() - Remove an existing ID3 tag
  • id3_get_version() - Get version of an ID3 tag

id3_get_genre_name
id3_get_version
ID3 Functions


Get version of an ID3 tag

id3_get_tag
id3_remove_tag
ID3 Functions
PHP Manual

id3_get_version

(PECL id3 >= 0.1)

id3_get_version — Get version of an ID3 tag

Description

int id3_get_version ( string $filename )

id3_get_version() retrieves the version(s) of the ID3 tag(s) in the MP3 file.

If a file contains an ID3 v1.1 tag, it always contains a 1.0 tag, as version 1.1 is just an extension of 1.0.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

Return Values

Returns the version number of the ID3 tag of the file. As a tag can contain ID3 v1.x and v2.x tags, the return value of this function should be bitwise compared with the predefined constants ID3_V1_0, ID3_V1_1 and ID3_V2.

Examples

Example #1 id3_get_version() example

<?php
$version = id3_get_version( "path/to/example.mp3" );
if ($version & ID3_V1_0) {
    echo "Contains a 1.x tag\n";
}
if ($version & ID3_V1_1) {
    echo "Contains a 1.1 tag\n";
}
if ($version & ID3_V2) {
    echo "Contains a 2.x tag\n";
}
?>

The above example will output something similar to:

Contains a 1.x tag
Contains a 1.1 tag

See Also

  • id3_set_tag() - Update information stored in an ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_remove_tag() - Remove an existing ID3 tag

id3_get_tag
id3_remove_tag
ID3 Functions


Remove an existing ID3 tag

id3_get_version
id3_set_tag
ID3 Functions
PHP Manual

id3_remove_tag

(PECL id3 >= 0.1)

id3_remove_tag — Remove an existing ID3 tag

Description

bool id3_remove_tag ( string $filename [, int $version = ID3_V1_0 ] )

id3_remove_tag() is used to remove the information stored of an ID3 tag.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 id3_remove_tag() example

<?php
$result = id3_remove_tag( "path/to/example.mp3", ID3_V1_0 );
if ($result === true) {
    echo "Tag succesfully removed\n";
}
?>

If the file is writable and contained a 1.0 tag, this will output:

Tag succesfully removed

Notes

Note: Currently id3_remove_tag() only supports version 1.0 and 1.1. If you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag will be removed, as v1.1 is only an extension of 1.0.

See Also

  • id3_set_tag() - Update information stored in an ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_get_version() - Get version of an ID3 tag

id3_get_version
id3_set_tag
ID3 Functions


Update information stored in an ID3 tag

id3_remove_tag
KTaglib
ID3 Functions
PHP Manual

id3_set_tag

(PECL id3 >= 0.1)

id3_set_tag — Update information stored in an ID3 tag

Description

bool id3_set_tag ( string $filename , array $tag [, int $version = ID3_V1_0 ] )

id3_set_tag() is used to change the information stored of an ID3 tag. If no tag has been present, it will be added to the file.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

tag

An associative array of tag keys and values

The following keys may be used in the associative array:

Keys in the associative array
key | possible value | available in version
title | string with maximum of 30 characters | v1.0, v1.1
artist | string with maximum of 30 characters | v1.0, v1.1
album | string with maximum of 30 characters | v1.0, v1.1
year | 4 digits | v1.0, v1.1
genre | integer value between 0 and 147 | v1.0, v1.1
comment | string with maximum of 30 characters (28 in v1.1) | v1.0, v1.1
track | integer between 0 and 255 | v1.1

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 id3_set_tag() example

<?php
$data = array(
              "title" => "Re:Start",
              "artist" => "Re:\Legion",
              "comment" => "A nice track"
             );
$result = id3_set_tag( "path/to/example.mp3", $data, ID3_V1_0 );
if ($result === true) {
    echo "Tag succesfully updated\n";
}
?>

If the file is writable, this will output:

Tag succesfully updated

Notes

Note: Currently id3_remove_tag() only supports version 1.0 and 1.1.

See Also

  • id3_remove_tag() - Remove an existing ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_get_version() - Get version of an ID3 tag

id3_remove_tag
KTaglib
ID3 Functions


Format a local time/date as integer

gmstrftime
localtime
Date/Time Functions
PHP Manual

idate

(PHP 5)

idate — Format a local time/date as integer

Description

int idate ( string $format [, int $timestamp = time() ] )

Returns a number formatted according to the given format string using the given integer timestamp or the current local time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

Unlike the function date(), idate() accepts just one char in the format parameter.

Parameters

format

The following characters are recognized in the format parameter string
format character | Description
B | Swatch Beat/Internet Time
d | Day of the month
h | Hour (12 hour format)
H | Hour (24 hour format)
i | Minutes
I (uppercase i) | returns 1 if DST is activated, 0 otherwise
L (uppercase l) | returns 1 for leap year, 0 otherwise
m | Month number
s | Seconds
t | Days in current month
U | Seconds since the Unix Epoch - January 1 1970 00:00:00 UTC - this is the same as time()
w | Day of the week (0 on Sunday)
W | ISO-8601 week number of year, weeks starting on Monday
y | Year (1 or 2 digits - check note below)
Y | Year (4 digits)
z | Day of the year
Z | Timezone offset in seconds

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns an integer.

As idate() always returns an integer and as they can't start with a "0", idate() may return fewer digits than you would expect. See the example below.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 idate() example

<?php
$timestamp = strtotime('1st January 2004'); //1072915200

// this prints the year in a two digit format
// however, as this would start with a "0", it
// only prints "4"
echo idate('y', $timestamp);
?>

See Also

  • date() - Format a local time/date
  • getdate() - Get date/time information
  • time() - Return current Unix timestamp

gmstrftime
localtime
Date/Time Functions


Convert domain name to IDNA ASCII form.

IDN Functions
idn_to_unicode
IDN Functions
PHP Manual

idn_to_ascii

(PHP 5 >= 5.3.0, PECL intl >= 1.0.2)

idn_to_ascii — Convert domain name to IDNA ASCII form.

Description

Procedural style

string idn_to_ascii ( string $domain [, int $options ] )

This function converts Unicode domain name to IDNA ASCII-compatible format.

Parameters

domain

Domain to convert. In PHP 5 must be UTF-8 encoded.

options

Conversion options - combination of IDNA_* constants.

Return Values

Domain name encoded in ASCII-compatible form.

Examples

Example #1 idn_to_ascii() example

<?php

echo idn_to_ascii('täst.de');

?>

The above example will output:

xn--tst-qla.de

See Also

  • idn_to_unicode() - Alias of idn_to_utf8

IDN Functions
idn_to_unicode
IDN Functions


Alias of idn_to_utf8

idn_to_ascii
idn_to_utf8
IDN Functions
PHP Manual

idn_to_unicode

(PHP 6)

idn_to_unicode — Alias of idn_to_utf8()

Description

This function is an alias of: idn_to_utf8().

idn_to_ascii
idn_to_utf8
IDN Functions


Convert domain name from IDNA ASCII to Unicode.

idn_to_unicode
intl Functions
IDN Functions
PHP Manual

idn_to_utf8

(PHP 5 >= 5.3.0, PECL intl >= 1.0.2)

idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.

Description

Procedural style

string idn_to_utf8 ( string $domain [, int $options ] )

This function converts Unicode domain name from IDNA ASCII-compatible format to plain Unicode.

Parameters

domain

Domain to convert in IDNA ASCII-compatible format.

options

Conversion options - combination of IDNA_* constants.

Return Values

Domain name in Unicode. In PHP5, domain name will be in UTF-8.

Examples

Example #1 idn_to_utf8() example

<?php

echo idn_to_utf8('xn--tst-qla.de');

?>

The above example will output:

täst.de

See Also

  • idn_to_unicode() - Alias of idn_to_utf8

idn_to_unicode
intl Functions
IDN Functions


Get number of rows affected by a query

Informix Functions
ifx_blobinfile_mode
Informix Functions
PHP Manual

ifx_affected_rows

(PHP 4, PHP <=5.2.0)

ifx_affected_rows — Get number of rows affected by a query

Description

int ifx_affected_rows ( resource $result_id )

Returns the number of rows affected by a query associated with result_id .

For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it. The database server can never return the actual number of rows that will be returned by a SELECT because it has not even begun fetching them at this stage (just after the "PREPARE" when the optimizer has determined the query plan).

Useful after ifx_prepare() to limit queries to reasonable result sets.

Parameters

result_id

A valid result id returned by ifx_query() or ifx_prepare().

Return Values

Returns the number of rows as an integer.

Examples

Example #1 Informix affected rows

<?php
$rid = ifx_prepare("select * from emp
                     where name like " . $name, $connid);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
?>

See Also

  • ifx_num_rows() - Count the rows already fetched from a query

Informix Functions
ifx_blobinfile_mode
Informix Functions


Set the default blob mode for all select queries

ifx_affected_rows
ifx_byteasvarchar
Informix Functions
PHP Manual

ifx_blobinfile_mode

(PHP 4, PHP <=5.2.0)

ifx_blobinfile_mode — Set the default blob mode for all select queries

Description

bool ifx_blobinfile_mode ( int $mode )

Set the default blob mode for all select queries.

Parameters

mode

Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.

Return Values

Returns TRUE on success or FALSE on failure.

ifx_affected_rows
ifx_byteasvarchar
Informix Functions


Set the default byte mode

ifx_blobinfile_mode
ifx_close
Informix Functions
PHP Manual

ifx_byteasvarchar

(PHP 4, PHP <=5.2.0)

ifx_byteasvarchar — Set the default byte mode

Description

bool ifx_byteasvarchar ( int $mode )

Sets the default byte mode for all select-queries.

Parameters

mode

Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_textasvarchar() - Set the default text mode

ifx_blobinfile_mode
ifx_close
Informix Functions


Close Informix connection

ifx_byteasvarchar
ifx_connect
Informix Functions
PHP Manual

ifx_close

(PHP 4, PHP <=5.2.0)

ifx_close — Close Informix connection

Description

bool ifx_close ([ resource $link_identifier ] )

ifx_close() closes the link to an Informix database that's associated with the specified link identifier.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

ifx_close() will not close persistent links generated by ifx_pconnect().

Parameters

link_identifier

The link identifier. If not specified, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a Informix connection

<?php
$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
/* ... some queries and stuff ... */
ifx_close($conn_id);
?>

See Also

  • ifx_connect() - Open Informix server connection
  • ifx_pconnect() - Open persistent Informix connection

ifx_byteasvarchar
ifx_connect
Informix Functions


Open Informix server connection

ifx_close
ifx_copy_blob
Informix Functions
PHP Manual

ifx_connect

(PHP 4, PHP <=5.2.0)

ifx_connect — Open Informix server connection

Description

resource ifx_connect ([ string $database [, string $userid [, string $password ]]] )

ifx_connect() establishes a connection to an Informix server.

In case a second call is made to ifx_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ifx_close().

Parameters

All of the arguments are optional, and if they're missing, defaults are taken from values supplied in php.ini (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

database

The database name, as a string.

userid

The username, as a string.

password

The password, as a string.

Return Values

Returns a connection identifier on success, or FALSE on error.

Examples

Example #1 Connect to a Informix database

<?php
$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");
?>

See Also

  • ifx_pconnect() - Open persistent Informix connection
  • ifx_close() - Close Informix connection

ifx_close
ifx_copy_blob
Informix Functions


Duplicates the given blob object

ifx_connect
ifx_create_blob
Informix Functions
PHP Manual

ifx_copy_blob

(PHP 4, PHP <=5.2.0)

ifx_copy_blob — Duplicates the given blob object

Description

int ifx_copy_blob ( int $bid )

Duplicates the given blob object.

Parameters

bid

A BLOB identifier.

Return Values

Returns the new blob object-id, or FALSE on errors.

See Also

  • ifx_create_blob() - Creates an blob object
  • ifx_free_blob() - Deletes the blob object

ifx_connect
ifx_create_blob
Informix Functions


Creates an blob object

ifx_copy_blob
ifx_create_char
Informix Functions
PHP Manual

ifx_create_blob

(PHP 4, PHP <=5.2.0)

ifx_create_blob — Creates an blob object

Description

int ifx_create_blob ( int $type , int $mode , string $param )

Creates a blob object.

Parameters

type

1 = TEXT, 0 = BYTE

mode

0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.

param

if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.

Return Values

Returns the new BLOB object-id, or FALSE on errors.

See Also

  • ifx_copy_blob() - Duplicates the given blob object
  • ifx_free_blob() - Deletes the blob object

ifx_copy_blob
ifx_create_char
Informix Functions


Creates an char object

ifx_create_blob
ifx_do
Informix Functions
PHP Manual

ifx_create_char

(PHP 4, PHP <=5.2.0)

ifx_create_char — Creates an char object

Description

int ifx_create_char ( string $param )

Creates an char object.

Parameters

param

The char content.

Return Values

Returns the new char object id, or FALSE on errors.

See Also

  • ifx_free_char() - Deletes the char object

ifx_create_blob
ifx_do
Informix Functions


Execute a previously prepared SQL-statement

ifx_create_char
ifx_error
Informix Functions
PHP Manual

ifx_do

(PHP 4, PHP <=5.2.0)

ifx_do — Execute a previously prepared SQL-statement

Description

bool ifx_do ( resource $result_id )

Executes a previously prepared query or opens a cursor for it.

Does NOT free result_id on error.

Also sets the real number of ifx_affected_rows() for non-select statements for retrieval by ifx_affected_rows().

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

Example #1 ifx_do() Example

<?php
$conn = fx_connect( "db", "user", "password" );
$result = ifx_prepare("SELECT customer_num, company FROM customer", $conn);
ifx_do($result);
?>

See Also

  • ifx_prepare() - Prepare an SQL-statement for execution

ifx_create_char
ifx_error
Informix Functions


Returns error code of last Informix call

ifx_do
ifx_errormsg
Informix Functions
PHP Manual

ifx_error

(PHP 4, PHP <=5.2.0)

ifx_error — Returns error code of last Informix call

Description

string ifx_error ([ resource $link_identifier ] )

Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed.

Parameters

link_identifier

The link identifier.

Return Values

The Informix error codes (SQLSTATE & SQLCODE) formatted as x [SQLSTATE = aa bbb SQLCODE=cccc].

where x = space : no error

E : error

N : no more data

W : warning

? : undefined

If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.

See the Informix manual for the description of SQLSTATE and SQLCODE

See Also

  • ifx_errormsg() - Returns error message of last Informix call

ifx_do
ifx_errormsg
Informix Functions


Returns error message of last Informix call

ifx_error
ifx_fetch_row
Informix Functions
PHP Manual

ifx_errormsg

(PHP 4, PHP <=5.2.0)

ifx_errormsg — Returns error message of last Informix call

Description

string ifx_errormsg ([ int $errorcode ] )

Returns the Informix error message associated with the most recent Informix error.

Parameters

errorcode

If specified, the function will return the message corresponding to the specified code.

Return Values

Return the error message, as a string.

Examples

Example #1 ifx_errormsg() example

printf("%s\n&lt;br>", ifx_errormsg(-201));

See Also

  • ifx_error() - Returns error code of last Informix call

ifx_error
ifx_fetch_row
Informix Functions


Get row as an associative array

ifx_errormsg
ifx_fieldproperties
Informix Functions
PHP Manual

ifx_fetch_row

(PHP 4, PHP <=5.2.0)

ifx_fetch_row — Get row as an associative array

Description

array ifx_fetch_row ( resource $result_id [, mixed $position ] )

Fetches one row of data from the result associated with the specified result identifier.

Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

position

An optional parameter for a "fetch" operation on "scroll" cursors: NEXT, PREVIOUS, CURRENT, FIRST, LAST or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for SCROLL cursors.

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values.

Examples

Example #1 Informix fetch rows

<?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
if (! ifx_do ($rid)) {
   /* ... error ... */
}
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
    for (reset($row); $fieldname=key($row); next($row)) {
        $fieldvalue = $row[$fieldname];
        printf ("%s = %s,", $fieldname, $fieldvalue);
    }
    printf("\n<br />");
    $row = ifx_fetch_row($rid, "NEXT");
}
ifx_free_result ($rid);
?>

ifx_errormsg
ifx_fieldproperties
Informix Functions


List of SQL fieldproperties

ifx_fetch_row
ifx_fieldtypes
Informix Functions
PHP Manual

ifx_fieldproperties

(PHP 4, PHP <=5.2.0)

ifx_fieldproperties — List of SQL fieldproperties

Description

array ifx_fieldproperties ( resource $result_id )

Returns the Informix SQL fieldproperties of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id . Returns FALSE on errors.

Examples

Example #1 Informix SQL fieldproperties

<?php
$properties = ifx_fieldproperties($resultid);
if (!isset($properties)) {
    /* ... error ... */
}
foreach ($properties as $fname => $val) {
    echo "$fname:\t property = $val\n";
}
?>

See Also

  • ifx_fieldtypes() - List of Informix SQL fields

ifx_fetch_row
ifx_fieldtypes
Informix Functions


List of Informix SQL fields

ifx_fieldproperties
ifx_free_blob
Informix Functions
PHP Manual

ifx_fieldtypes

(PHP 4, PHP <=5.2.0)

ifx_fieldtypes — List of Informix SQL fields

Description

array ifx_fieldtypes ( resource $result_id )

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for the query associated with result_id .

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id . Returns FALSE on error.

Examples

Example #1 Fieldnames and SQL fieldtypes

<?php
$types = ifx_fieldtypes($resultid);
if (is_array($types)) {
    foreach ($types as $fname => $val) {
        echo "$fname:\t type = $val\n";
    }
}
?>

See Also

  • ifx_fieldproperties() - List of SQL fieldproperties

ifx_fieldproperties
ifx_free_blob
Informix Functions


Deletes the blob object

ifx_fieldtypes
ifx_free_char
Informix Functions
PHP Manual

ifx_free_blob

(PHP 4, PHP <=5.2.0)

ifx_free_blob — Deletes the blob object

Description

bool ifx_free_blob ( int $bid )

Deletes the blobobject for the given blob object-id.

Parameters

bid

The BLOB object id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_create_blob() - Creates an blob object

ifx_fieldtypes
ifx_free_char
Informix Functions


Deletes the char object

ifx_free_blob
ifx_free_result
Informix Functions
PHP Manual

ifx_free_char

(PHP 4, PHP <=5.2.0)

ifx_free_char — Deletes the char object

Description

bool ifx_free_char ( int $bid )

Deletes the charobject for the given char object-id.

Parameters

bid

The char object id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_create_char() - Creates an char object

ifx_free_blob
ifx_free_result
Informix Functions


Releases resources for the query

ifx_free_char
ifx_get_blob
Informix Functions
PHP Manual

ifx_free_result

(PHP 4, PHP <=5.2.0)

ifx_free_result — Releases resources for the query

Description

bool ifx_free_result ( resource $result_id )

Releases resources for the query associated with result_id .

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_do() - Execute a previously prepared SQL-statement

ifx_free_char
ifx_get_blob
Informix Functions


Return the content of a blob object

ifx_free_result
ifx_get_char
Informix Functions
PHP Manual

ifx_get_blob

(PHP 4, PHP <=5.2.0)

ifx_get_blob — Return the content of a blob object

Description

string ifx_get_blob ( int $bid )

Returns the content of the blob object.

Parameters

bid

The BLOB object id.

Return Values

The contents of the BLOB as a string, or FALSE on errors.

See Also

  • ifx_get_char() - Return the content of the char object

ifx_free_result
ifx_get_char
Informix Functions


Return the content of the char object

ifx_get_blob
ifx_getsqlca
Informix Functions
PHP Manual

ifx_get_char

(PHP 4, PHP <=5.2.0)

ifx_get_char — Return the content of the char object

Description

string ifx_get_char ( int $bid )

Returns the content of the char object.

Parameters

bid

The char object-id.

Return Values

Returns the contents as a string, or FALSE on errors.

See Also

  • ifx_get_blob() - Return the content of a blob object

ifx_get_blob
ifx_getsqlca
Informix Functions


Get the contents of sqlca.sqlerrd[0..5] after a query

ifx_get_char
ifx_htmltbl_result
Informix Functions
PHP Manual

ifx_getsqlca

(PHP 4, PHP <=5.2.0)

ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query

Description

array ifx_getsqlca ( resource $result_id )

Returns a pseudo-row with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the query associated with result_id .

For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For SELECTs the values are those saved after the PREPARE statement. This gives access to the *estimated* number of affected rows. The use of this function saves the overhead of executing a SELECT dbinfo('sqlca.sqlerrdx') query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.

Parameters

result_id

result_id is a valid result id returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns an associative array with the following entries: sqlerrd0, sqlerrd1, sqlerrd2, sqlerrd3, sqlerrd4 and sqlerrd5.

Examples

Example #1 Retrieve Informix sqlca.sqlerrd[x] values

<?php
/* assume the first column of 'sometable' is a serial */
$qid = ifx_query("insert into sometable
                  values (0, '2nd column', 'another column') ", $connid);
if (!$qid) {
    /* ... error ... */
}
$sqlca = ifx_getsqlca($qid);
$serial_value = $sqlca["sqlerrd1"];
echo "The serial value of the inserted row is : $serial_value<br />\n";
?>

ifx_get_char
ifx_htmltbl_result
Informix Functions


Formats all rows of a query into a HTML table

ifx_getsqlca
ifx_nullformat
Informix Functions
PHP Manual

ifx_htmltbl_result

(PHP 4, PHP <=5.2.0)

ifx_htmltbl_result — Formats all rows of a query into a HTML table

Description

int ifx_htmltbl_result ( resource $result_id [, string $html_table_options ] )

Formats and prints all rows of the result_id query into a HTML table.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

html_table_options

This optional argument is a string of <table> tag options.

Return Values

Returns the number of fetched rows, or FALSE on errors.

Examples

Example #1 Informix results as HTML table

<?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
if (! ifx_do($rid)) {
    /* ... error ... */
}

ifx_htmltbl_result ($rid, "border=\"2\"");

ifx_free_result($rid);
?>

ifx_getsqlca
ifx_nullformat
Informix Functions


Sets the default return value on a fetch row

ifx_htmltbl_result
ifx_num_fields
Informix Functions
PHP Manual

ifx_nullformat

(PHP 4, PHP <=5.2.0)

ifx_nullformat — Sets the default return value on a fetch row

Description

bool ifx_nullformat ( int $mode )

Sets the default return value of a NULL-value on a fetch row.

Parameters

mode

Mode "0" returns "", and mode "1" returns "NULL".

Return Values

Returns TRUE on success or FALSE on failure.

ifx_htmltbl_result
ifx_num_fields
Informix Functions


Returns the number of columns in the query

ifx_nullformat
ifx_num_rows
Informix Functions
PHP Manual

ifx_num_fields

(PHP 4, PHP <=5.2.0)

ifx_num_fields — Returns the number of columns in the query

Description

int ifx_num_fields ( resource $result_id )

After preparing or executing a query, this call gives you the number of columns in the query.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns the number of columns in query for result_id , or FALSE on errors.

Examples

Example #1 ifx_num_fields() Example

<?php
$conn_id = ifx_connect("db", "user", "password");
$res_id = ifx_query("select * from systables", $conn_id);
echo ifx_num_fields($res_id);
?>

See Also

  • ifx_num_rows() - Count the rows already fetched from a query

ifx_nullformat
ifx_num_rows
Informix Functions


Count the rows already fetched from a query

ifx_num_fields
ifx_pconnect
Informix Functions
PHP Manual

ifx_num_rows

(PHP 4, PHP <=5.2.0)

ifx_num_rows — Count the rows already fetched from a query

Description

int ifx_num_rows ( resource $result_id )

Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns the number of fetched rows or FALSE on errors.

See Also

  • ifx_num_fields() - Returns the number of columns in the query

ifx_num_fields
ifx_pconnect
Informix Functions


Open persistent Informix connection

ifx_num_rows
ifx_prepare
Informix Functions
PHP Manual

ifx_pconnect

(PHP 4, PHP <=5.2.0)

ifx_pconnect — Open persistent Informix connection

Description

resource ifx_pconnect ([ string $database [, string $userid [, string $password ]]] )

ifx_pconnect() acts very much like ifx_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ifx_close() will not close links established by ifx_pconnect()).

This type of links is therefore called 'persistent'.

Parameters

All of the arguments are optional, and if they're missing, defaults are taken from values supplied in php.ini (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

database

The database name, as a string.

userid

The username, as a string.

password

The password, as a string.

Return Values

Returns: valid Informix persistent link identifier on success, or FALSE on errors.

See Also

  • ifx_connect() - Open Informix server connection

ifx_num_rows
ifx_prepare
Informix Functions


Prepare an SQL-statement for execution

ifx_pconnect
ifx_query
Informix Functions
PHP Manual

ifx_prepare

(PHP 4, PHP <=5.2.0)

ifx_prepare — Prepare an SQL-statement for execution

Description

resource ifx_prepare ( string $query , resource $link_identifier [, int $cursor_def ], mixed $blobidarray )

Prepares a query for later use with ifx_do().

For "select-type" queries a cursor is declared and opened. Non-select queries are "execute immediate".

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If the contents of the TEXT (or BYTE) column allow it, you can also use ifx_textasvarchar(1) and ifx_byteasvarchar(1). This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

Parameters

query

The query string.

link_identifier

The link identifier.

cursor_def

This optional parameter allows you to make this a scroll and/or hold cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together.

blobidarray

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

Return Values

Returns a valid result identifier for use by ifx_do(), or FALSE on errors.

See Also

  • ifx_do() - Execute a previously prepared SQL-statement

ifx_pconnect
ifx_query
Informix Functions


Send Informix query

ifx_prepare
ifx_textasvarchar
Informix Functions
PHP Manual

ifx_query

(PHP 4, PHP <=5.2.0)

ifx_query — Send Informix query

Description

resource ifx_query ( string $query , resource $link_identifier [, int $cursor_type [, mixed $blobidarray ]] )

Sends a query to the currently active database on the server that's associated with the specified link identifier.

For "select-type" queries a cursor is declared and opened. Non-select queries are "execute immediate".

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If the contents of the TEXT (or BYTE) column allow it, you can also use ifx_textasvarchar(1) and ifx_byteasvarchar(1). This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

Parameters

query

The query string.

link_identifier

The link identifier.

cursor_def

This optional parameter allows you to make this a scroll and/or hold cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. I you omit this parameter the cursor is a normal sequential cursor.

blobidarray

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

Return Values

Returns valid Informix result identifier on success, or FALSE on errors.

Examples

Example #1 Show all rows of the "orders" table as a HTML table

<?php
ifx_textasvarchar(1);      // use "text mode" for blobs
$res_id = ifx_query("select * from orders", $conn_id);
if (! $res_id) {
    printf("Can't select orders : %s\n<br />%s<br />\n", ifx_error(), ifx_errormsg());
    die;
}
ifx_htmltbl_result($res_id, "border=\"1\"");
ifx_free_result($res_id);
?>

Example #2 Insert some values into the "catalog" table

<?php

// create blob id's for a byte and text column
$textid = ifx_create_blob(0, 0, "Text column in memory");
$byteid = ifx_create_blob(1, 0, "Byte column in memory");

// store blob id's in a blobid array
$blobidarray[] = $textid;
$blobidarray[] = $byteid;

// launch query
$query = "insert into catalog (stock_num, manu_code, " .
         "cat_descr,cat_picture) values(1,'HRO',?,?)";
$res_id = ifx_query($query, $conn_id, $blobidarray);
if (! $res_id) {
    /* ... error ... */
}

// free result id
ifx_free_result($res_id);
?>

See Also

  • ifx_connect() - Open Informix server connection

ifx_prepare
ifx_textasvarchar
Informix Functions


Set the default text mode

ifx_query
ifx_update_blob
Informix Functions
PHP Manual

ifx_textasvarchar

(PHP 4, PHP <=5.2.0)

ifx_textasvarchar — Set the default text mode

Description

bool ifx_textasvarchar ( int $mode )

Sets the default text mode for all select-queries.

Parameters

mode

Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_byteasvarchar() - Set the default byte mode

ifx_query
ifx_update_blob
Informix Functions


Updates the content of the blob object

ifx_textasvarchar
ifx_update_char
Informix Functions
PHP Manual

ifx_update_blob

(PHP 4, PHP <=5.2.0)

ifx_update_blob — Updates the content of the blob object

Description

bool ifx_update_blob ( int $bid , string $content )

Updates the content of the blob object for the given blob object bid .

Parameters

bid

A BLOB object identifier.

content

The new data, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_update_char() - Updates the content of the char object

ifx_textasvarchar
ifx_update_char
Informix Functions


Updates the content of the char object

ifx_update_blob
ifxus_close_slob
Informix Functions
PHP Manual

ifx_update_char

(PHP 4, PHP <=5.2.0)

ifx_update_char — Updates the content of the char object

Description

bool ifx_update_char ( int $bid , string $content )

Updates the content of the char object for the given char object bid .

Parameters

bid

A char object identifier.

content

The new data, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_update_blob() - Updates the content of the blob object

ifx_update_blob
ifxus_close_slob
Informix Functions


Deletes the slob object

ifx_update_char
ifxus_create_slob
Informix Functions
PHP Manual

ifxus_close_slob

(PHP 4, PHP <=5.2.0)

ifxus_close_slob — Deletes the slob object

Description

bool ifxus_close_slob ( int $bid )

Deletes the slob object on the given slob object-id bid .

Parameters

bid

An existing slob id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifxus_open_slob() - Opens an slob object

ifx_update_char
ifxus_create_slob
Informix Functions


Creates an slob object and opens it

ifxus_close_slob
ifxus_free_slob
Informix Functions
PHP Manual

ifxus_create_slob

(PHP 4, PHP <=5.2.0)

ifxus_create_slob — Creates an slob object and opens it

Description

int ifxus_create_slob ( int $mode )

Creates an slob object and opens it.

Parameters

mode

A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.

Return Values

Return the new slob object-id, or FALSE on errors.

See Also

  • ifxus_close_slob() - Deletes the slob object
  • ifxus_free_slob() - Deletes the slob object

ifxus_close_slob
ifxus_free_slob
Informix Functions


Deletes the slob object

ifxus_create_slob
ifxus_open_slob
Informix Functions
PHP Manual

ifxus_free_slob

(PHP 4, PHP <=5.2.0)

ifxus_free_slob — Deletes the slob object

Description

bool ifxus_free_slob ( int $bid )

Deletes the slob object.

Parameters

bid

An existing slob id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifxus_close_slob() - Deletes the slob object

ifxus_create_slob
ifxus_open_slob
Informix Functions


Opens an slob object

ifxus_free_slob
ifxus_read_slob
Informix Functions
PHP Manual

ifxus_open_slob

(PHP 4, PHP <=5.2.0)

ifxus_open_slob — Opens an slob object

Description

int ifxus_open_slob ( int $bid , int $mode )

Opens an slob object. bid should be an existing slob id.

Parameters

bid

An existing slob id.

mode

A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.

Return Values

Returns the new slob object-id, or FALSE on errors.

See Also

  • ifxus_close_slob() - Deletes the slob object
  • ifxus_free_slob() - Deletes the slob object

ifxus_free_slob
ifxus_read_slob
Informix Functions


Reads nbytes of the slob object

ifxus_open_slob
ifxus_seek_slob
Informix Functions
PHP Manual

ifxus_read_slob

(PHP 4, PHP <=5.2.0)

ifxus_read_slob — Reads nbytes of the slob object

Description

string ifxus_read_slob ( int $bid , int $nbytes )

Reads nbytes of the slob object.

Parameters

bid

An existing slob id.

nbytes

The number of bytes to read.

Return Values

Returns the slob contents as a string, or FALSE on errors.

See Also

  • ifxus_write_slob() - Writes a string into the slob object

ifxus_open_slob
ifxus_seek_slob
Informix Functions


Sets the current file or seek position

ifxus_read_slob
ifxus_tell_slob
Informix Functions
PHP Manual

ifxus_seek_slob

(PHP 4, PHP <=5.2.0)

ifxus_seek_slob — Sets the current file or seek position

Description

int ifxus_seek_slob ( int $bid , int $mode , int $offset )

Sets the current file or seek position of an open slob object.

Parameters

bid

An existing slob id.

mode

0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END.

offset

A byte offset.

Return Values

Returns the seek position as an integer, or FALSE on errors.

See Also

  • ifxus_tell_slob() - Returns the current file or seek position

ifxus_read_slob
ifxus_tell_slob
Informix Functions


Returns the current file or seek position

ifxus_seek_slob
ifxus_write_slob
Informix Functions
PHP Manual

ifxus_tell_slob

(PHP 4, PHP <=5.2.0)

ifxus_tell_slob — Returns the current file or seek position

Description

int ifxus_tell_slob ( int $bid )

Returns the current file or seek position of an open slob object

Parameters

bid

An existing slob id.

Return Values

Returns the seek position as an integer, or FALSE on errors.

See Also

  • ifxus_seek_slob() - Sets the current file or seek position

ifxus_seek_slob
ifxus_write_slob
Informix Functions


Writes a string into the slob object

ifxus_tell_slob
IBM DB2
Informix Functions
PHP Manual

ifxus_write_slob

(PHP 4, PHP <=5.2.0)

ifxus_write_slob — Writes a string into the slob object

Description

int ifxus_write_slob ( int $bid , string $content )

Writes a string into the slob object.

Parameters

bid

An existing slob id.

content

The content to write, as a string.

Return Values

Returns the bytes written as an integer, or FALSE on errors.

See Also

  • ifxus_read_slob() - Reads nbytes of the slob object

ifxus_tell_slob
IBM DB2
Informix Functions


Set whether a client disconnect should abort script execution

highlight_string
pack
Misc. Functions
PHP Manual

ignore_user_abort

(PHP 4, PHP 5)

ignore_user_abort — Set whether a client disconnect should abort script execution

Description

int ignore_user_abort ([ string $value ] )

Sets whether a client disconnect should cause a script to be aborted.

When running PHP as a command line script, and the script's tty goes away without the script being terminated then the script will die the next time it tries to write anything, unless value is set to TRUE

Parameters

value

If set, this function will set the ignore_user_abort ini setting to the given value . If not, this function will only return the previous setting without changing it.

Return Values

Returns the previous setting, as an integer.

Examples

Example #1 A ignore_user_abort() example

<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);

echo 'Testing connection handling in PHP';

// Run a pointless loop that sometime
// hopefully will make us click away from
// page or click the "Stop" button.
while(1)
{
    // Did the connection fail?
    if(connection_status() != CONNECTION_NORMAL)
    {
        break;
    }

    // Sleep for 10 seconds
    sleep(10);
}

// If this is reached, then the 'break'
// was triggered from inside the while loop

// So here we can log, or perform any other tasks
// we need without actually being dependent on the
// browser.
?>

Notes

PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see flush().

See Also

  • connection_aborted() - Check whether client disconnected
  • connection_status() - Returns connection status bitfield
  • Connection Handling for a complete description of connection handling in PHP.

highlight_string
pack
Misc. Functions


Output image to browser or file

image_type_to_mime_type
imagealphablending
GD and Image Functions
PHP Manual

image2wbmp

(PHP 4 >= 4.0.5, PHP 5)

image2wbmp — Output image to browser or file

Description

bool image2wbmp ( resource $image [, string $filename [, int $threshold ]] )

image2wbmp() outputs or save a WBMP version of the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

Path to the saved file. If not given, the raw image stream will be outputted directly.

threshold

Threshold value, between 0 and 255 (inclusive).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 image2wbmp() example

<?php
$file = 'php.png';
$image = imagecreatefrompng($file);

header('Content-type: ' . image_type_to_mime_type(IMAGETYPE_WBMP));
image2wbmp($image); // output the stream directly
imagedestroy($image);
?>

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See Also

  • imagewbmp() - Output image to browser or file

image_type_to_mime_type
imagealphablending
GD and Image Functions


Get file extension for image type

getimagesize
image_type_to_mime_type
GD and Image Functions
PHP Manual

image_type_to_extension

(PHP 5)

image_type_to_extension — Get file extension for image type

Description

string image_type_to_extension ( int $imagetype [, bool $include_dot ] )

Returns the extension for the given IMAGETYPE_XXX constant.

Parameters

imagetype

One of the IMAGETYPE_XXX constant.

include_dot

Whether to prepend a dot to the extension or not. Default to TRUE.

Return Values

A string with the extension corresponding to the given image type.

Examples

Example #1 image_type_to_extension() example

<?php
// Create image instance
$im = imagecreatetruecolor(100, 100);

// Save image
imagepng($im, './test' . image_type_to_extension(IMAGETYPE_PNG));
imagedestroy($im);
?>

Notes

Note: This function does not require the GD image library.

getimagesize
image_type_to_mime_type
GD and Image Functions


Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

image_type_to_extension
image2wbmp
GD and Image Functions
PHP Manual

image_type_to_mime_type

(PHP 4 >= 4.3.0, PHP 5)

image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

Description

string image_type_to_mime_type ( int $imagetype )

The image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.

Parameters

imagetype

One of the IMAGETYPE_XXX constants.

Return Values

The returned values are as follows

Returned values Constants
imagetype | Returned value
IMAGETYPE_GIF | image/gif
IMAGETYPE_JPEG | image/jpeg
IMAGETYPE_PNG | image/png
IMAGETYPE_SWF | application/x-shockwave-flash
IMAGETYPE_PSD | image/psd
IMAGETYPE_BMP | image/bmp
IMAGETYPE_TIFF_II (intel byte order) | image/tiff
IMAGETYPE_TIFF_MM (motorola byte order) | image/tiff
IMAGETYPE_JPC | application/octet-stream
IMAGETYPE_JP2 | image/jp2
IMAGETYPE_JPX | application/octet-stream
IMAGETYPE_JB2 | application/octet-stream
IMAGETYPE_SWC | application/x-shockwave-flash
IMAGETYPE_IFF | image/iff
IMAGETYPE_WBMP | image/vnd.wap.wbmp
IMAGETYPE_XBM | image/xbm
IMAGETYPE_ICO | image/vnd.microsoft.icon

Examples

Example #1 image_type_to_mime_type() example

<?php
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
?>

Notes

Note: This function does not require the GD image library.

See Also

  • getimagesize() - Get the size of an image
  • exif_imagetype() - Determine the type of an image
  • exif_read_data() - Reads the EXIF headers from JPEG or TIFF
  • exif_thumbnail() - Retrieve the embedded thumbnail of a TIFF or JPEG image

image_type_to_extension
image2wbmp
GD and Image Functions


Set the blending mode for an image

image2wbmp
imageantialias
GD and Image Functions
PHP Manual

imagealphablending

(PHP 4 >= 4.0.6, PHP 5)

imagealphablending — Set the blending mode for an image

Description

bool imagealphablending ( resource $image , bool $blendmode )

imagealphablending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as imagesetpixel() determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

blendmode

Whether to enable the blending mode or not. On true color images the default value is TRUE otherwise the default value is FALSE

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagealphablending() usage example

<?php
// Create image
$im = imagecreatetruecolor(100, 100);

// Set alphablending to on
imagealphablending($im, true);

// Draw a square
imagefilledrectangle($im, 30, 30, 70, 70, imagecolorallocate($im, 255, 0, 0));

// Output
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

image2wbmp
imageantialias
GD and Image Functions


Should antialias functions be used or not

imagealphablending
imagearc
GD and Image Functions
PHP Manual

imageantialias

(PHP 4 >= 4.3.2, PHP 5)

imageantialias — Should antialias functions be used or not

Description

bool imageantialias ( resource $image , bool $enabled )

Activate the fast drawing antialiased methods for lines and wired polygons. It does not support alpha components. It works using a direct blend operation. It works only with truecolor images.

Thickness and styled are not supported.

Using antialiased primitives with transparent background color can end with some unexpected results. The blend method uses the background color as any other colors. The lack of alpha component support does not allow an alpha based antialiasing method.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

enabled

Whether to enable antialiasing or not.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A comparison of two lines, one with anti-aliasing switched on

<?php
// Setup an anti-aliased image and a normal image
$aa = imagecreatetruecolor(400, 100);
$normal = imagecreatetruecolor(200, 100);

// Switch antialiasing on for one image
imageantialias($aa, true);

// Allocate colors
$red = imagecolorallocate($normal, 255, 0, 0);
$red_aa = imagecolorallocate($aa, 255, 0, 0);

// Draw two lines, one with AA enabled
imageline($normal, 0, 0, 200, 100, $red);
imageline($aa, 0, 0, 200, 100, $red_aa);

// Merge the two images side by side for output (AA: left, Normal: Right)
imagecopymerge($aa, $normal, 200, 0, 0, 0, 200, 100, 100);

// Output image
header('Content-type: image/png');

imagepng($aa);
imagedestroy($aa);
imagedestroy($normal);
?>

The above example will output something similar to:

Output of example : A comparison of two lines, one with anti-aliasing switched on

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

See Also

  • imagecreatetruecolor() - Create a new true color image

imagealphablending
imagearc
GD and Image Functions


Draws an arc

imageantialias
imagechar
GD and Image Functions
PHP Manual

imagearc

(PHP 4, PHP 5)

imagearc — Draws an arc

Description

bool imagearc ( resource $image , int $cx , int $cy , int $width , int $height , int $start , int $end , int $color )

imagearc() draws an arc of circle centered at the given coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center.

cy

y-coordinate of the center.

width

The arc width.

height

The arc height.

start

The arc start angle, in degrees.

end

The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Drawing a circle with imagearc()

<?php

// create a 200*200 image
$img = imagecreatetruecolor(200, 200);

// allocate some colors
$white = imagecolorallocate($img, 255, 255, 255);
$red   = imagecolorallocate($img, 255,   0,   0);
$green = imagecolorallocate($img,   0, 255,   0);
$blue  = imagecolorallocate($img,   0,   0, 255);

// draw the head
imagearc($img, 100, 100, 200, 200,  0, 360, $white);
// mouth
imagearc($img, 100, 100, 150, 150, 25, 155, $red);
// left and then the right eye
imagearc($img,  60,  75,  50,  50,  0, 360, $green);
imagearc($img, 140,  75,  50,  50,  0, 360, $blue);

// output image in the browser
header("Content-type: image/png");
imagepng($img);

// free memory
imagedestroy($img);

?>

The above example will output something similar to:

Output of example : Drawing a circle with imagearc()

See Also

  • imagefilledarc() - Draw a partial arc and fill it
  • imageellipse() - Draw an ellipse
  • imagefilledellipse() - Draw a filled ellipse

imageantialias
imagechar
GD and Image Functions


Draw a character horizontally

imagearc
imagecharup
GD and Image Functions
PHP Manual

imagechar

(PHP 4, PHP 5)

imagechar — Draw a character horizontally

Description

bool imagechar ( resource $image , int $font , int $x , int $y , string $c , int $color )

imagechar() draws the first character of c in the image identified by image with its upper-left at x ,y (top left is 0, 0) with the color color .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

font

Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the start.

y

y-coordinate of the start.

c

The character to draw.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagechar() example

<?php

$im = imagecreate(100, 100);

$string = 'PHP';

$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// prints a black "P" in the top left corner
imagechar($im, 1, 0, 0, $string, $black);

header('Content-type: image/png');
imagepng($im);

?>

The above example will output something similar to:

Output of example : imagechar()

See Also

  • imagecharup() - Draw a character vertically
  • imageloadfont() - Load a new font

imagearc
imagecharup
GD and Image Functions


Draw a character vertically

imagechar
imagecolorallocate
GD and Image Functions
PHP Manual

imagecharup

(PHP 4, PHP 5)

imagecharup — Draw a character vertically

Description

bool imagecharup ( resource $image , int $font , int $x , int $y , string $c , int $color )

Draws the character c vertically at the specified coordinate on the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

font

Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the start.

y

y-coordinate of the start.

c

The character to draw.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagecharup() example

<?php

$im = imagecreate(100, 100);

$string = 'Note that the first letter is a N';

$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// prints a black "Z" on a white background
imagecharup($im, 3, 10, 10, $string, $black);

header('Content-type: image/png');
imagepng($im);

?>

The above example will output something similar to:

Output of example : imagecharup()

See Also

  • imagechar() - Draw a character horizontally
  • imageloadfont() - Load a new font

imagechar
imagecolorallocate
GD and Image Functions


Allocate a color for an image

imagecharup
imagecolorallocatealpha
GD and Image Functions
PHP Manual

imagecolorallocate

(PHP 4, PHP 5)

imagecolorallocate — Allocate a color for an image

Description

int imagecolorallocate ( resource $image , int $red , int $green , int $blue )

Returns a color identifier representing the color composed of the given RGB components.

imagecolorallocate() must be called to create each color that is to be used in the image represented by image .

Note: The first call to imagecolorallocate() fills the background color in palette-based images - images created using imagecreate().

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

A color identifier or FALSE if the allocation failed.

Changelog

Version | Description
Prior to 5.1.3 | Returns -1 if the allocation failed.

Examples

Example #1 imagecolorallocate() example

<?php

$im = imagecreate(100, 100);

// sets background to red
$background = imagecolorallocate($im, 255, 0, 0);

// sets some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// hexadecimal way
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

?>

See Also

  • imagecolorallocatealpha() - Allocate a color for an image
  • imagecolordeallocate() - De-allocate a color for an image

imagecharup
imagecolorallocatealpha
GD and Image Functions


Allocate a color for an image

imagecolorallocate
imagecolorat
GD and Image Functions
PHP Manual

imagecolorallocatealpha

(PHP 4 >= 4.3.2, PHP 5)

imagecolorallocatealpha — Allocate a color for an image

Description

int imagecolorallocatealpha ( resource $image , int $red , int $green , int $blue , int $alpha )

imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

A color identifier or FALSE if the allocation failed.

Changelog

Version | Description
Prior to 5.1.3 | Returns -1 if the allocation failed.

Examples

Example #1 Example of using imagecolorallocatealpha()

<?php
$size = 300;
$image=imagecreatetruecolor($size, $size);

// something to get a white background with black border
$back = imagecolorallocate($image, 255, 255, 255);
$border = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $size - 1, $size - 1, $back);
imagerectangle($image, 0, 0, $size - 1, $size - 1, $border);

$yellow_x = 100;
$yellow_y = 75;
$red_x    = 120;
$red_y    = 165;
$blue_x   = 187;
$blue_y   = 125;
$radius   = 150;

// allocate colors with alpha values
$yellow = imagecolorallocatealpha($image, 255, 255, 0, 75);
$red    = imagecolorallocatealpha($image, 255, 0, 0, 75);
$blue   = imagecolorallocatealpha($image, 0, 0, 255, 75);

// drawing 3 overlapped circle
imagefilledellipse($image, $yellow_x, $yellow_y, $radius, $radius, $yellow);
imagefilledellipse($image, $red_x, $red_y, $radius, $radius, $red);
imagefilledellipse($image, $blue_x, $blue_y, $radius, $radius, $blue);

// don't forget to output a correct header!
header('Content-type: image/png');

// and finally, output the result
imagepng($image);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : Example of using imagecolorallocatealpha()

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecolorallocate() - Allocate a color for an image
  • imagecolordeallocate() - De-allocate a color for an image

imagecolorallocate
imagecolorat
GD and Image Functions


Get the index of the color of a pixel

imagecolorallocatealpha
imagecolorclosest
GD and Image Functions
PHP Manual

imagecolorat

(PHP 4, PHP 5)

imagecolorat — Get the index of the color of a pixel

Description

int imagecolorat ( resource $image , int $x , int $y )

Returns the index of the color of the pixel at the specified location in the image specified by image .

If PHP is compiled against GD library 2.0 or higher and the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values:

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x

x-coordinate of the point.

y

y-coordinate of the point.

Return Values

Returns the index of the color.

Examples

Example #1 Access distinct RGB values

<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;

var_dump($r, $g, $b);
?>

The above example will output something similar to:

int(119)
int(123)
int(180)

Example #2 Human-readable RGB values using imagecolorsforindex()

<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);

$colors = imagecolorsforindex($im, $rgb);

var_dump($colors);
?>

The above example will output something similar to:

array(4) {
  ["red"]=>
  int(119)
  ["green"]=>
  int(123)
  ["blue"]=>
  int(180)
  ["alpha"]=>
  int(127)
}

See Also

  • imagecolorset() - Set the color for the specified palette index
  • imagecolorsforindex() - Get the colors for an index

imagecolorallocatealpha
imagecolorclosest
GD and Image Functions


Get the index of the closest color to the specified color

imagecolorat
imagecolorclosestalpha
GD and Image Functions
PHP Manual

imagecolorclosest

(PHP 4, PHP 5)

imagecolorclosest — Get the index of the closest color to the specified color

Description

int imagecolorclosest ( resource $image , int $red , int $green , int $blue )

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value.

The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.

If you created the image from a file, only colors used in the image are resolved. Colors present only in the palette are not resolved.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

Returns the index of the closest color, in the palette of the image, to the specified one

Examples

Example #1 Search for a set of colors in an image

<?php
// Start with an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);

// Search colors (RGB)
$colors = array(
    array(254, 145, 154),
    array(153, 145, 188),
    array(153, 90, 145),
    array(255, 137, 92)
);

// Loop through each search and find the closest color in the palette.
// Return the search number, the search RGB and the converted RGB match
foreach($colors as $id => $rgb)
{
    $result = imagecolorclosest($im, $rgb[0], $rgb[1], $rgb[2]);
    $result = imagecolorsforindex($im, $result);
    $result = "({$result['red']}, {$result['green']}, {$result['blue']})";

    echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2]); Closest match: $result.\n";
}

imagedestroy($im);
?>

The above example will output something similar to:

#0: Search (254, 145, 154); Closest match: (252, 150, 148).
#1: Search (153, 145, 188); Closest match: (148, 150, 196).
#2: Search (153, 90, 145); Closest match: (148, 90, 156).
#3: Search (255, 137, 92); Closest match: (252, 150, 92).

See Also

  • imagecolorexact() - Get the index of the specified color
  • imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha
  • imagecolorclosesthwb() - Get the index of the color which has the hue, white and blackness

imagecolorat
imagecolorclosestalpha
GD and Image Functions


Get the index of the closest color to the specified color + alpha

imagecolorclosest
imagecolorclosesthwb
GD and Image Functions
PHP Manual

imagecolorclosestalpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha

Description

int imagecolorclosestalpha ( resource $image , int $red , int $green , int $blue , int $alpha )

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value and alpha level.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

Returns the index of the closest color in the palette.

Examples

Example #1 Search for a set of colors in an image

<?php
// Start with an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);

// Search colors (RGB)
$colors = array(
    array(254, 145, 154, 50),
    array(153, 145, 188, 127),
    array(153, 90, 145, 0),
    array(255, 137, 92, 84)
);

// Loop through each search and find the closest color in the palette.
// Return the search number, the search RGB and the converted RGB match
foreach($colors as $id => $rgb)
{
    $result = imagecolorclosestalpha($im, $rgb[0], $rgb[1], $rgb[2], $rgb[3]);
    $result = imagecolorsforindex($im, $result);
    $result = "({$result['red']}, {$result['green']}, {$result['blue']}, {$result['alpha']})";

    echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2], $rgb[3]); Closest match: $result.\n";
}

imagedestroy($im);
?>

The above example will output something similar to:

#0: Search (254, 145, 154, 50); Closest match: (252, 150, 148, 0).
#1: Search (153, 145, 188, 127); Closest match: (148, 150, 196, 0).
#2: Search (153, 90, 145, 0); Closest match: (148, 90, 156, 0).
#3: Search (255, 137, 92, 84); Closest match: (252, 150, 92, 0).

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecolorexactalpha() - Get the index of the specified color + alpha
  • imagecolorclosest() - Get the index of the closest color to the specified color
  • imagecolorclosesthwb() - Get the index of the color which has the hue, white and blackness

imagecolorclosest
imagecolorclosesthwb
GD and Image Functions


Get the index of the color which has the hue, white and blackness

imagecolorclosestalpha
imagecolordeallocate
GD and Image Functions
PHP Manual

imagecolorclosesthwb

(PHP 4 >= 4.0.1, PHP 5)

imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness

Description

int imagecolorclosesthwb ( resource $image , int $red , int $green , int $blue )

Get the index of the color which has the hue, white and blackness nearest the given color.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

Return Values

Returns an integer with the index of the color which has the hue, white and blackness nearest the given color.

Examples

Example #1 Example of using imagecolorclosesthwb()

<?php
$im = imagecreatefromgif('php.gif');

echo 'HWB: ' . imagecolorclosesthwb($im, 116, 115, 152);

imagedestroy($im);
?>

The above example will output something similar to:

HWB: 33

Changelog

Version | Description
5.3.0 | This function is now available on Windows

See Also

  • imagecolorclosest() - Get the index of the closest color to the specified color

imagecolorclosestalpha
imagecolordeallocate
GD and Image Functions


De-allocate a color for an image

imagecolorclosesthwb
imagecolorexact
GD and Image Functions
PHP Manual

imagecolordeallocate

(PHP 4, PHP 5)

imagecolordeallocate — De-allocate a color for an image

Description

bool imagecolordeallocate ( resource $image , int $color )

De-allocates a color previously allocated with imagecolorallocate() or imagecolorallocatealpha().

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

color

The color identifier.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using imagecolordeallocate()

<?php
$white = imagecolorallocate($im, 255, 255, 255);
imagecolordeallocate($im, $white);
?>

See Also

  • imagecolorallocate() - Allocate a color for an image
  • imagecolorallocatealpha() - Allocate a color for an image

imagecolorclosesthwb
imagecolorexact
GD and Image Functions


Get the index of the specified color

imagecolordeallocate
imagecolorexactalpha
GD and Image Functions
PHP Manual

imagecolorexact

(PHP 4, PHP 5)

imagecolorexact — Get the index of the specified color

Description

int imagecolorexact ( resource $image , int $red , int $green , int $blue )

Returns the index of the specified color in the palette of the image.

If you created the image from a file, only colors used in the image are resolved. Colors present only in the palette are not resolved.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

Return Values

Returns the index of the specified color in the palette, or -1 if the color does not exist.

Examples

Example #1 Get colors from the GD logo

<?php
// Setup an image
$im = imagecreatefrompng('./gdlogo.png');

$colors   = Array();
$colors[] = imagecolorexact($im, 255, 0, 0);
$colors[] = imagecolorexact($im, 0, 0, 0);
$colors[] = imagecolorexact($im, 255, 255, 255);
$colors[] = imagecolorexact($im, 100, 255, 52);

print_r($colors);

// Free from memory
imagedestroy($im);
?>

The above example will output something similar to:

Array
(
    [0] => 16711680
    [1] => 0
    [2] => 16777215
    [3] => 6618932
)

See Also

  • imagecolorclosest() - Get the index of the closest color to the specified color

imagecolordeallocate
imagecolorexactalpha
GD and Image Functions


Get the index of the specified color + alpha

imagecolorexact
imagecolormatch
GD and Image Functions
PHP Manual

imagecolorexactalpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorexactalpha — Get the index of the specified color + alpha

Description

int imagecolorexactalpha ( resource $image , int $red , int $green , int $blue , int $alpha )

Returns the index of the specified color+alpha in the palette of the image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

Returns the index of the specified color+alpha in the palette of the image, or -1 if the color does not exist in the image's palette.

Examples

Example #1 Get colors from the GD logo

<?php

// Setup an image
$im = imagecreatefrompng('./gdlogo.png');

$colors   = Array();
$colors[] = imagecolorexactalpha($im, 255, 0, 0, 0);
$colors[] = imagecolorexactalpha($im, 0, 0, 0, 127);
$colors[] = imagecolorexactalpha($im, 255, 255, 255, 55);
$colors[] = imagecolorexactalpha($im, 100, 255, 52, 20);

print_r($colors);

// Free from memory
imagedestroy($im);
?>

The above example will output something similar to:

Array
(
    [0] => 16711680
    [1] => 2130706432
    [2] => 939524095
    [3] => 342163252
)

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha

imagecolorexact
imagecolormatch
GD and Image Functions


Makes the colors of the palette version of an image more closely match the true color version

imagecolorexactalpha
imagecolorresolve
GD and Image Functions
PHP Manual

imagecolormatch

(PHP 4 >= 4.3.0, PHP 5)

imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version

Description

bool imagecolormatch ( resource $image1 , resource $image2 )

Makes the colors of the palette version of an image more closely match the true color version.

Parameters

image1

A truecolor image link resource.

image2

A palette image link resource pointing to an image that has the same size as image1 .

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagecolormatch() example

<?php
// Setup the true color and palette images
$im1 = imagecreatefrompng('./gdlogo.png');
$im2 = imagecreate(imagesx($im1), imagesy($im1));

// Add some colors to $im2
$colors   = Array();
$colors[] = imagecolorallocate($im2, 255, 36, 74);
$colors[] = imagecolorallocate($im2, 40, 0, 240);
$colors[] = imagecolorallocate($im2, 82, 100, 255);
$colors[] = imagecolorallocate($im2, 84, 63, 44);

// Match these colors with the true color image
imagecolormatch($im1, $im2);

// Free from memory
imagedestroy($im1);
imagedestroy($im2);
?>

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecreatetruecolor() - Create a new true color image

imagecolorexactalpha
imagecolorresolve
GD and Image Functions


Get the index of the specified color or its closest possible alternative

imagecolormatch
imagecolorresolvealpha
GD and Image Functions
PHP Manual

imagecolorresolve

(PHP 4, PHP 5)

imagecolorresolve — Get the index of the specified color or its closest possible alternative

Description

int imagecolorresolve ( resource $image , int $red , int $green , int $blue )

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

If you created the image from a file, only colors used in the image are resolved. Colors present only in the palette are not resolved.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

Return Values

Returns a color index.

Examples

Example #1 Using imagecoloresolve() to get colors from an image

<?php
// Load an image
$im = imagecreatefromgif('phplogo.gif');

// Get closest colors from the image
$colors = array();
$colors[] = imagecolorresolve($im, 255, 255, 255);
$colors[] = imagecolorresolve($im, 0, 0, 200);

// Output
print_r($colors);

imagedestroy($im);
?>

The above example will output something similar to:

Array
(
    [0] => 89
    [1] => 85
)

See Also

  • imagecolorclosest() - Get the index of the closest color to the specified color

imagecolormatch
imagecolorresolvealpha
GD and Image Functions


Get the index of the specified color + alpha or its closest possible alternative

imagecolorresolve
imagecolorset
GD and Image Functions
PHP Manual

imagecolorresolvealpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative

Description

int imagecolorresolvealpha ( resource $image , int $red , int $green , int $blue , int $alpha )

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

Returns a color index.

Examples

Example #1 Using imagecoloresolvealpha() to get colors from an image

<?php
// Load an image
$im = imagecreatefromgif('phplogo.gif');

// Get closest colors from the image
$colors = array();
$colors[] = imagecolorresolvealpha($im, 255, 255, 255, 0);
$colors[] = imagecolorresolvealpha($im, 0, 0, 200, 127);

// Output
print_r($colors);

imagedestroy($im);
?>

The above example will output something similar to:

Array
(
    [0] => 89
    [1] => 85
)

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha

imagecolorresolve
imagecolorset
GD and Image Functions


Set the color for the specified palette index

imagecolorresolvealpha
imagecolorsforindex
GD and Image Functions
PHP Manual

imagecolorset

(PHP 4, PHP 5)

imagecolorset — Set the color for the specified palette index

Description

void imagecolorset ( resource $image , int $index , int $red , int $green , int $blue )

This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in palleted images without the overhead of performing the actual flood-fill.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

index

An index in the palette.

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

Return Values

No value is returned.

Examples

Example #1 imagecolorset() example

<?php
// Create a 300x100 image
$im = imagecreate(300, 100);

// Set the background to be red
imagecolorallocate($im, 255, 0, 0);

// Get the color index for the background
$bg = imagecolorat($im, 0, 0);

// Set the backgrund to be blue
imagecolorset($im, $bg, 0, 0, 255);

// Output the image to the browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

See Also

  • imagecolorat() - Get the index of the color of a pixel

imagecolorresolvealpha
imagecolorsforindex
GD and Image Functions


Get the colors for an index

imagecolorset
imagecolorstotal
GD and Image Functions
PHP Manual

imagecolorsforindex

(PHP 4, PHP 5)

imagecolorsforindex — Get the colors for an index

Description

array imagecolorsforindex ( resource $image , int $index )

Gets the color for a specified index.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

index

The color index.

Return Values

Returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.

Examples

Example #1 imagecolorsforindex() example

<?php

// open an image
$im = imagecreatefrompng('nexen.png');

// get a color
$start_x = 40;
$start_y = 50;
$color_index = imagecolorat($im, $start_x, $start_y);

// make it human readable
$color_tran = imagecolorsforindex($im, $color_index);

// what is it ?
print_r($color_tran);

?>

The above example will output something similar to:

Array
(
   [red] => 226
   [green] => 222
   [blue] => 252
   [alpha] => 0
)

See Also

  • imagecolorat() - Get the index of the color of a pixel
  • imagecolorexact() - Get the index of the specified color

imagecolorset
imagecolorstotal
GD and Image Functions


Find out the number of colors in an image's palette

imagecolorsforindex
imagecolortransparent
GD and Image Functions
PHP Manual

imagecolorstotal

(PHP 4, PHP 5)

imagecolorstotal — Find out the number of colors in an image's palette

Description

int imagecolorstotal ( resource $image )

Returns the number of colors in an image palette.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Returns the number of colors in the specified image's palette or 0 for truecolor images.

Examples

Example #1 Getting total number of colors in an image using imagecolorstotal()

<?php
// Create image instance
$im = imagecreatefromgif('php.gif');

echo 'Total colors in image: ' . imagecolorstotal($im);

// Free image
imagedestroy($im);
?>

The above example will output something similar to:

Total colors in image: 128

See Also

  • imagecolorat() - Get the index of the color of a pixel
  • imagecolorsforindex() - Get the colors for an index
  • imageistruecolor() - Finds whether an image is a truecolor image

imagecolorsforindex
imagecolortransparent
GD and Image Functions


Define a color as transparent

imagecolorstotal
imageconvolution
GD and Image Functions
PHP Manual

imagecolortransparent

(PHP 4, PHP 5)

imagecolortransparent — Define a color as transparent

Description

int imagecolortransparent ( resource $image [, int $color ] )

Sets the transparent color in the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

color

A color identifier created with imagecolorallocate().

Return Values

The identifier of the new (or current, if none is specified) transparent color is returned.

Examples

Example #1 imagecolortransparent() example

<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);

// Make the background transparent
imagecolortransparent($im, $black);

// Draw a red rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $red);

// Save the image
imagepng($im, './imagecolortransparent.png');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagecolortransparent()

Notes

Note: Transparency is copied only with imagecopymerge() and true color images, not with imagecopy() or pallete images.

Note: The transparent color is a property of the image, transparency is not a property of the color. Once you have set a color to be the transparent color, any regions of the image in that color that were drawn previously will be transparent.

imagecolorstotal
imageconvolution
GD and Image Functions


Apply a 3x3 convolution matrix, using coefficient and offset

imagecolortransparent
imagecopy
GD and Image Functions
PHP Manual

imageconvolution

(PHP 5 >= 5.1.0)

imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset

Description

bool imageconvolution ( resource $image , array $matrix , float $div , float $offset )

Applies a convolution matrix on the image, using the given coefficient and offset.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

matrix

A 3x3 matrix: an array of three arrays of three floats.

div

The divisor of the result of the convolution, used for normalization.

offset

Color offset.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Embossing the PHP.net logo

<?php
$image = imagecreatefromgif('http://www.php.net/images/php.gif');

$emboss = array(array(2, 0, 0), array(0, -1, 0), array(0, 0, -1));
imageconvolution($image, $emboss, 1, 127);

header('Content-Type: image/png');
imagepng($image, null, 9);
?>

The above example will output:

Output of example : Embossing the PHP.net logo

Example #2 Gaussian blur

<?php
$image = imagecreatetruecolor(180,40);

// Writes the text and apply a gaussian blur on the image
imagestring($image, 5, 10, 8, 'Gaussian Blur Text', 0x00ff00);
$gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 4.0, 2.0), array(1.0, 2.0, 1.0));
imageconvolution($image, $gaussian, 16, 0);

// Rewrites the text for comparison
imagestring($image, 5, 10, 18, 'Gaussian Blur Text', 0x00ff00);

header('Content-Type: image/png');
imagepng($image, null, 9);
?>

The above example will output:

Output of example : Gaussian blur

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

See Also

  • imagefilter() - Applies a filter to an image

imagecolortransparent
imagecopy
GD and Image Functions


Copy part of an image

imageconvolution
imagecopymerge
GD and Image Functions
PHP Manual

imagecopy

(PHP 4, PHP 5)

imagecopy — Copy part of an image

Description

bool imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x , src_y with a width of src_w and a height of src_h . The portion defined will be copied onto the x,y coordinates, dst_x and dst_y .

Parameters

dst_im

Destination image link resource.

src_im

Source image link resource.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

src_w

Source width.

src_h

Source height.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Cropping the PHP.net logo

<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);

// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

The above example will output something similar to:

Output of example : Cropping the PHP.net logo

imageconvolution
imagecopymerge
GD and Image Functions


Copy and merge part of an image

imagecopy
imagecopymergegray
GD and Image Functions
PHP Manual

imagecopymerge

(PHP 4 >= 4.0.1, PHP 5)

imagecopymerge — Copy and merge part of an image

Description

bool imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x , src_y with a width of src_w and a height of src_h . The portion defined will be copied onto the x,y coordinates, dst_x and dst_y .

Parameters

dst_im

Destination image link resource.

src_im

Source image link resource.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

src_w

Source width.

src_h

Source height.

pct

The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy() for pallete images, while it implements alpha transparency for true colour images.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Merging two copies of the PHP.net logo with 75% transparency

<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');

// Copy and merge
imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 47, 75);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

imagecopy
imagecopymergegray
GD and Image Functions


Copy and merge part of an image with gray scale

imagecopymerge
imagecopyresampled
GD and Image Functions
PHP Manual

imagecopymergegray

(PHP 4 >= 4.0.6, PHP 5)

imagecopymergegray — Copy and merge part of an image with gray scale

Description

bool imagecopymergegray ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )

imagecopymergegray() copy a part of src_im onto dst_im starting at the x,y coordinates src_x , src_y with a width of src_w and a height of src_h . The portion defined will be copied onto the x,y coordinates, dst_x and dst_y .

This function is identical to imagecopymerge() except that when merging it preserves the hue of the source by converting the destination pixels to gray scale before the copy operation.

Parameters

dst_im

Destination image link resource.

src_im

Source image link resource.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

src_w

Source width.

src_h

Source height.

pct

The src_im will be changed to grayscale according to pct where 0 is fully grayscale and 100 is unchanged. When pct = 100 this function behaves identically to imagecopy() for pallete images, while it implements alpha transparency for true colour images.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagecopymergegray() usage

<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');

// Copy and merge - Gray = 20%
imagecopymergegray($dest, $src, 10, 10, 0, 0, 100, 47, 20);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

imagecopymerge
imagecopyresampled
GD and Image Functions


Copy and resize part of an image with resampling

imagecopymergegray
imagecopyresized
GD and Image Functions
PHP Manual

imagecopyresampled

(PHP 4 >= 4.0.6, PHP 5)

imagecopyresampled — Copy and resize part of an image with resampling

Description

bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

In other words, imagecopyresampled() will take an rectangular area from src_image of width src_w and height src_h at position (src_x ,src_y ) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x ,dst_y ).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image ) but if the regions overlap the results will be unpredictable.

Parameters

dst_im

Destination image link resource.

src_im

Source image link resource.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

dst_w

Destination width.

dst_h

Destination height.

src_w

Source width.

src_h

Source height.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Simple example

This example will resample an image to half its original size.

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>

The above example will output something similar to:

Output of example : Simple example

Example #2 Resampling an image proportionally

This example will display an image with the maximum width, or height, of 200 pixels.

<?php
// The file
$filename = 'test.jpg';

// Set a maximum height and width
$width = 200;
$height = 200;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, null, 100);
?>

The above example will output something similar to:

Output of example : Resampling an image proportionally

Notes

Note: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

See Also

imagecopyresized() - Copy and resize part of an image

imagecopymergegray
imagecopyresized
GD and Image Functions


Copy and resize part of an image

imagecopyresampled
imagecreate
GD and Image Functions
PHP Manual

imagecopyresized

(PHP 4, PHP 5)

imagecopyresized — Copy and resize part of an image

Description

bool imagecopyresized ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )

imagecopyresized() copies a rectangular portion of one image to another image. dst_image is the destination image, src_image is the source image identifier.

In other words, imagecopyresized() will take an rectangular area from src_image of width src_w and height src_h at position (src_x ,src_y ) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x ,dst_y ).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image ) but if the regions overlap the results will be unpredictable.

Parameters

dst_im

Destination image link resource.

src_im

Source image link resource.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

dst_w

Destination width.

dst_h

Destination height.

src_w

Source width.

src_h

Source height.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Resizing an image

This example will display the image at half size.

<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
imagejpeg($thumb);
?>

The above example will output something similar to:

Output of example : Resizing an image

The image will be output at half size, though better quality could be obtained using imagecopyresampled().

Notes

Note: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

See Also

imagecopyresampled() - Copy and resize part of an image with resampling

imagecopyresampled
imagecreate
GD and Image Functions


Create a new palette based image

imagecopyresized
imagecreatefromgd2
GD and Image Functions
PHP Manual

imagecreate

(PHP 4, PHP 5)

imagecreate — Create a new palette based image

Description

resource imagecreate ( int $width , int $height )

imagecreate() returns an image identifier representing a blank image of specified size.

We recommend the use of imagecreatetruecolor().

Parameters

width

The image width.

height

The image height.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Creating a new GD image stream and outputting an image.

<?php
header("Content-type: image/png");
$im = @imagecreate(110, 20)
    or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : Creating a new GD image stream and outputting an image.

See Also

  • imagedestroy() - Destroy an image
  • imagecreatetruecolor() - Create a new true color image

imagecopyresized
imagecreatefromgd2
GD and Image Functions


Create a new image from GD file or URL

imagecreatefromgd2part
imagecreatefromgif
GD and Image Functions
PHP Manual

imagecreatefromgd

(PHP 4 >= 4.0.7, PHP 5)

imagecreatefromgd — Create a new image from GD file or URL

Description

resource imagecreatefromgd ( string $filename )

Create a new image from GD file or URL.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the GD file.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 imagecreatefromgd() example

<?php
// Load the gd image
$im = @imagecreatefromgd('./test.gd');

// Test if the image was loaded
if(!is_resource($im))
{
     die('Unable to load gd image!');
}

// Do image operations here

// Save the image
imagegd($im, './test_updated.gd');
imagedestroy($im);
?>

Notes

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

imagecreatefromgd2part
imagecreatefromgif
GD and Image Functions


Create a new image from GD2 file or URL

imagecreate
imagecreatefromgd2part
GD and Image Functions
PHP Manual

imagecreatefromgd2

(PHP 4 >= 4.0.7, PHP 5)

imagecreatefromgd2 — Create a new image from GD2 file or URL

Description

resource imagecreatefromgd2 ( string $filename )

Create a new image from GD2 file or URL.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the GD2 image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 imagecreatefromgd2() example

<?php
// Load the gd2 image
$im = imagecreatefromgd2('./test.gd2');

// Apply an effect on the image, in this
// case negate the image if PHP5+
if(function_exists('imagefilter'))
{
    imagefilter($im, IMG_FILTER_NEGATE);
}

// Save the image
imagegd2($im, './test_updated.gd2');
imagedestroy($im);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

imagecreate
imagecreatefromgd2part
GD and Image Functions


Create a new image from a given part of GD2 file or URL

imagecreatefromgd2
imagecreatefromgd
GD and Image Functions
PHP Manual

imagecreatefromgd2part

(PHP 4 >= 4.0.7, PHP 5)

imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL

Description

resource imagecreatefromgd2part ( string $filename , int $srcX , int $srcY , int $width , int $height )

Create a new image from a given part of GD2 file or URL.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the GD2 image.

srcX

x-coordinate of source point.

srcY

y-coordinate of source point.

width

Source width.

height

Source height.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 imagecreatefromgd2part() example

<?php
// For this example we need the image size before
$image = getimagesize('./test.gd2');

// Create the image instance now we got the image
// sizes
$im = imagecreatefromgd2part('./test.gd2', 4, 4, ($image[0] / 2) - 6, ($image[1] / 2) - 6);

// Do an image operation, in this case we emboss the
// image if PHP5+
if(function_exists('imagefilter'))
{
    imagefilter($im, IMG_FILTER_EMBOSS);
}

// Save optimized image
imagegd2($im, './test_emboss.gd2');
imagedestroy($im);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

imagecreatefromgd2
imagecreatefromgd
GD and Image Functions


Create a new image from file or URL

imagecreatefromgd
imagecreatefromjpeg
GD and Image Functions
PHP Manual

imagecreatefromgif

(PHP 4, PHP 5)

imagecreatefromgif — Create a new image from file or URL

Description

resource imagecreatefromgif ( string $filename )

imagecreatefromgif() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the GIF image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a GIF

<?php
function LoadGif($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefromgif($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a blank image */
        $im = imagecreatetruecolor (150, 30);
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc = imagecolorallocate ($im, 0, 0, 0);

        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring ($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/gif');

$img = LoadGif('bogus.image');

imagegif($img);
imagedestroy($img);
?>

The above example will output something similar to:

Output of example : Example to handle an error during loading of a GIF

Notes

Note: GIF support was removed from the GD library in Version 1.6, and added back in Version 2.0.28. This function is not available between these versions.

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

imagecreatefromgd
imagecreatefromjpeg
GD and Image Functions


Create a new image from file or URL

imagecreatefromgif
imagecreatefrompng
GD and Image Functions
PHP Manual

imagecreatefromjpeg

(PHP 4, PHP 5)

imagecreatefromjpeg — Create a new image from file or URL

Description

resource imagecreatefromjpeg ( string $filename )

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the JPEG image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a JPEG

<?php
function LoadJpeg($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefromjpeg($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a black image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/jpeg');

$img = LoadJpeg('bogus.image');

imagejpeg($img);
imagedestroy($img);
?>

The above example will output something similar to:

Output of example : Example to handle an error during loading of a JPEG

Notes

Note: JPEG support is only available if PHP was compiled against GD-1.8 or later.

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

imagecreatefromgif
imagecreatefrompng
GD and Image Functions


Create a new image from file or URL

imagecreatefromjpeg
imagecreatefromstring
GD and Image Functions
PHP Manual

imagecreatefrompng

(PHP 4, PHP 5)

imagecreatefrompng — Create a new image from file or URL

Description

resource imagecreatefrompng ( string $filename )

imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the PNG image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a PNG

<?php
function LoadPNG($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefrompng($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a blank image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/png');

$img = LoadPNG('bogus.image');

imagepng($img);
imagedestroy($img);
?>

Notes

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

imagecreatefromjpeg
imagecreatefromstring
GD and Image Functions


Create a new image from the image stream in the string

imagecreatefrompng
imagecreatefromwbmp
GD and Image Functions
PHP Manual

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5)

imagecreatefromstring — Create a new image from the image stream in the string

Description

resource imagecreatefromstring ( string $data )

imagecreatefromstring() returns an image identifier representing the image obtained from the given data . These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

Parameters

image

A string containing the image data.

Return Values

An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.

Examples

Example #1 imagecreatefromstring() example

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
       . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
       . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
       . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);

$im = imagecreatefromstring($data);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
}
else {
    echo 'An error occurred.';
}
?>

The above example will output something similar to:

Output of example : imagecreatefromstring()

See Also

  • imagecreatefromjpeg() - Create a new image from file or URL
  • imagecreatefrompng() - Create a new image from file or URL
  • imagecreatefromgif() - Create a new image from file or URL
  • imagecreatetruecolor() - Create a new true color image

imagecreatefrompng
imagecreatefromwbmp
GD and Image Functions


Create a new image from file or URL

imagecreatefromstring
imagecreatefromxbm
GD and Image Functions
PHP Manual

imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromwbmp — Create a new image from file or URL

Description

resource imagecreatefromwbmp ( string $filename )

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the WBMP image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a WBMP

<?php
function LoadWBMP($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefromwbmp($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a blank image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-type: image/vnd.wap.wbmp');

$img = LoadWBMP('bogus.image');

imagewbmp($img);
imagedestroy($img);
?>

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

imagecreatefromstring
imagecreatefromxbm
GD and Image Functions


Create a new image from file or URL

imagecreatefromwbmp
imagecreatefromxpm
GD and Image Functions
PHP Manual

imagecreatefromxbm

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromxbm — Create a new image from file or URL

Description

resource imagecreatefromxbm ( string $filename )

imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the XBM image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Convert an XBM image to a png image using imagecreatefromxbm()

<?php
// Load the xbm file
$xbm = imagecreatefromxbm('./example.xbm');

// Convert it to a png file
imagepng($xbm, './example.png');
imagedestroy($xbm);
?>

Notes

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

imagecreatefromwbmp
imagecreatefromxpm
GD and Image Functions


Create a new image from file or URL

imagecreatefromxbm
imagecreatetruecolor
GD and Image Functions
PHP Manual

imagecreatefromxpm

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromxpm — Create a new image from file or URL

Description

resource imagecreatefromxpm ( string $filename )

imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Parameters

filename

Path to the XPM image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Creating an image instance using imagecreatefromxpm()

<?php
// Check for XPM support
if(!(imagetypes() & IMG_XPM))
{
    die('Support for xpm was not found!');
}

// Create the image instance
$xpm = imagecreatefromxpm('./example.xpm');

// Do image operations here

// PHP has no support for writing xpm images
// so in this case we save the image as a
// jpeg file with 100% quality
imagejpeg($xpm, './example.jpg', 100);
imagedestroy($xpm);
?>

Return Values

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

Note: This function is not implemented on Windows platforms.

imagecreatefromxbm
imagecreatetruecolor
GD and Image Functions


Create a new true color image

imagecreatefromxpm
imagedashedline
GD and Image Functions
PHP Manual

imagecreatetruecolor

(PHP 4 >= 4.0.6, PHP 5)

imagecreatetruecolor — Create a new true color image

Description

resource imagecreatetruecolor ( int $width , int $height )

imagecreatetruecolor() returns an image identifier representing a black image of the specified size.

Depending on your PHP and GD versions this function is defined or not. With PHP 4.0.6 through 4.1.x this function always exists if the GD module is loaded, but calling it without GD2 being installed PHP will issue a fatal error and exit. With PHP 4.2.x this behaviour is different in issuing a warning instead of an error. Other versions only define this function, if the correct GD version is installed.

Parameters

width

Image width.

height

Image height.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Creating a new GD image stream and outputting an image.

<?php
header ('Content-type: image/png');
$im = @imagecreatetruecolor(120, 20)
      or die('Cannot Initialize new GD image stream');
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);
imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : Creating a new GD image stream and outputting an image.

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Note: This function will not work with GIF file formats.

See Also

  • imagedestroy() - Destroy an image
  • imagecreate() - Create a new palette based image

imagecreatefromxpm
imagedashedline
GD and Image Functions


Draw a dashed line

imagecreatetruecolor
imagedestroy
GD and Image Functions
PHP Manual

imagedashedline

(PHP 4, PHP 5)

imagedashedline — Draw a dashed line

Description

bool imagedashedline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

This function is deprecated. Use combination of imagesetstyle() and imageline() instead.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x1

Upper left x coordinate.

y1

Upper left y coordinate 0, 0 is the top left corner of the image.

x2

Bottom right x coordinate.

y2

Bottom right y coordinate.

color

The fill color. A color identifier created with imagecolorallocate().

Return Values

Always returns true

Examples

Example #1 imagedashedline() example

<?php
// Create a 100x100 image
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

// Draw a vertical dashed line
imagedashedline($im, 50, 25, 50, 75, $white);

// Save the image
imagepng($im, './dashedline.png');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagedashedline()

Example #2 Alternative to imagedashedline()

<?php
// Create a 100x100 image
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

// Define our style: First 4 pixels is white and the
// next 4 is transparent. This creates the dashed line effect
$style = Array(
                $white,
                $white,
                $white,
                $white,
                IMG_COLOR_TRANSPARENT,
                IMG_COLOR_TRANSPARENT,
                IMG_COLOR_TRANSPARENT,
                IMG_COLOR_TRANSPARENT
                );

imagesetstyle($im, $style);

// Draw the dashed line
imageline($im, 50, 25, 50, 75, IMG_COLOR_STYLED);

// Save the image
imagepng($im, './imageline.png');
imagedestroy($im);
?>

See Also

  • imagesetstyle() - Set the style for line drawing
  • imageline() - Draw a line

imagecreatetruecolor
imagedestroy
GD and Image Functions


Destroy an image

imagedashedline
imageellipse
GD and Image Functions
PHP Manual

imagedestroy

(PHP 4, PHP 5)

imagedestroy — Destroy an image

Description

bool imagedestroy ( resource $image )

imagedestroy() frees any memory associated with image image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using imagedestroy() example

<?php
// create a 100 x 100 image
$im = imagecreatetruecolor(100, 100);

// alter or save the image

// frees image from memory
imagedestroy($im);
?>

imagedashedline
imageellipse
GD and Image Functions


Draw an ellipse

imagedestroy
imagefill
GD and Image Functions
PHP Manual

imageellipse

(PHP 4 >= 4.0.6, PHP 5)

imageellipse — Draw an ellipse

Description

bool imageellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color )

Draws an ellipse centered at the specified coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center.

cy

y-coordinate of the center.

width

The ellipse width.

height

The ellipse height.

color

The color of the ellipse. A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imageellipse() example

<?php

// Create a blank image.
$image = imagecreatetruecolor(400, 300);

// Select the background color.
$bg = imagecolorallocate($image, 0, 0, 0);

// Fill the background with the color selected above.
imagefill($image, 0, 0, $bg);

// Choose a color for the ellipse.
$col_ellipse = imagecolorallocate($image, 255, 255, 255);

// Draw the ellipse.
imageellipse($image, 200, 150, 300, 200, $col_ellipse);

// Output the image.
header("Content-type: image/png");
imagepng($image);

?>

The above example will output something similar to:

Output of example : imageellipse()

Notes

Note: This function requires GD 2.0.2 or later.

See Also

  • imagefilledellipse() - Draw a filled ellipse
  • imagearc() - Draws an arc

imagedestroy
imagefill
GD and Image Functions


Flood fill

imageellipse
imagefilledarc
GD and Image Functions
PHP Manual

imagefill

(PHP 4, PHP 5)

imagefill — Flood fill

Description

bool imagefill ( resource $image , int $x , int $y , int $color )

Performs a flood fill starting at the given coordinate (top left is 0, 0) with the given color in the image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x

x-coordinate of start point.

y

y-coordinate of start point.

color

The fill color. A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagefill() example

<?php

$im = imagecreatetruecolor(100, 100);

// sets background to red
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $red);

header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagefill()

See Also

  • imagecolorallocate() - Allocate a color for an image

imageellipse
imagefilledarc
GD and Image Functions


Draw a partial arc and fill it

imagefill
imagefilledellipse
GD and Image Functions
PHP Manual

imagefilledarc

(PHP 4 >= 4.0.6, PHP 5)

imagefilledarc — Draw a partial arc and fill it

Description

bool imagefilledarc ( resource $image , int $cx , int $cy , int $width , int $height , int $start , int $end , int $color , int $style )

Draws a partial arc centered at the specified coordinate in the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center.

cy

y-coordinate of the center.

width

The arc width.

height

The arc height.

start

The arc start angle, in degrees.

end

The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise.

color

A color identifier created with imagecolorallocate().

style

A bitwise OR of the following possibilities:

  1. IMG_ARC_PIE
  2. IMG_ARC_CHORD
  3. IMG_ARC_NOFILL
  4. IMG_ARC_EDGED

IMG_ARC_PIE and IMG_ARC_CHORD are mutually exclusive; IMG_ARC_CHORD just connects the starting and ending angles with a straight line, while IMG_ARC_PIE produces a rounded edge. IMG_ARC_NOFILL indicates that the arc or chord should be outlined, not filled. IMG_ARC_EDGED, used together with IMG_ARC_NOFILL, indicates that the beginning and ending angles should be connected to the center - this is a good way to outline (rather than fill) a 'pie slice'.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Creating a 3D looking pie

<?php

// create image
$image = imagecreatetruecolor(100, 100);

// allocate some solors
$white    = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray     = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90);
$navy     = imagecolorallocate($image, 0x00, 0x00, 0x80);
$darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50);
$red      = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$darkred  = imagecolorallocate($image, 0x90, 0x00, 0x00);

// make the 3D effect
for ($i = 60; $i > 50; $i--) {
   imagefilledarc($image, 50, $i, 100, 50, 0, 45, $darknavy, IMG_ARC_PIE);
   imagefilledarc($image, 50, $i, 100, 50, 45, 75 , $darkgray, IMG_ARC_PIE);
   imagefilledarc($image, 50, $i, 100, 50, 75, 360 , $darkred, IMG_ARC_PIE);
}

imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);

// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : Creating a 3D looking pie

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

imagefill
imagefilledellipse
GD and Image Functions


Draw a filled ellipse

imagefilledarc
imagefilledpolygon
GD and Image Functions
PHP Manual

imagefilledellipse

(PHP 4 >= 4.0.6, PHP 5)

imagefilledellipse — Draw a filled ellipse

Description

bool imagefilledellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color )

Draws an ellipse centered at the specified coordinate on the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center.

cy

y-coordinate of the center.

width

The ellipse width.

height

The ellipse height.

color

The fill color. A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagefilledellipse() example

<?php

// create a blank image
$image = imagecreatetruecolor(400, 300);

// fill the background color
$bg = imagecolorallocate($image, 0, 0, 0);

// choose a color for the ellipse
$col_ellipse = imagecolorallocate($image, 255, 255, 255);

// draw the white ellipse
imagefilledellipse($image, 200, 150, 300, 200, $col_ellipse);

// output the picture
header("Content-type: image/png");
imagepng($image);

?>

The above example will output something similar to:

Output of example : imagefilledellipse()

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imageellipse() - Draw an ellipse
  • imagefilledarc() - Draw a partial arc and fill it

imagefilledarc
imagefilledpolygon
GD and Image Functions


Draw a filled polygon

imagefilledellipse
imagefilledrectangle
GD and Image Functions
PHP Manual

imagefilledpolygon

(PHP 4, PHP 5)

imagefilledpolygon — Draw a filled polygon

Description

bool imagefilledpolygon ( resource $image , array $points , int $num_points , int $color )

imagefilledpolygon() creates a filled polygon in the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

points

An array containing the x and y coordinates of the polygons vertices consecutively.

num_points

Total number of vertices, which must be at least 3.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagefilledpolygon() example

<?php
// set up array of points for polygon
$values = array(
            40,  50,  // Point 1 (x, y)
            20,  240, // Point 2 (x, y)
            60,  60,  // Point 3 (x, y)
            240, 20,  // Point 4 (x, y)
            50,  40,  // Point 5 (x, y)
            10,  10   // Point 6 (x, y)
            );

// create image
$image = imagecreatetruecolor(250, 250);

// allocate colors
$bg   = imagecolorallocate($image, 0, 0, 0);
$blue = imagecolorallocate($image, 0, 0, 255);

// fill the background
imagefilledrectangle($image, 0, 0, 249, 249, $bg);

// draw a polygon
imagefilledpolygon($image, $values, 6, $blue);

// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : imagefilledpolygon()

imagefilledellipse
imagefilledrectangle
GD and Image Functions


Draw a filled rectangle

imagefilledpolygon
imagefilltoborder
GD and Image Functions
PHP Manual

imagefilledrectangle

(PHP 4, PHP 5)

imagefilledrectangle — Draw a filled rectangle

Description

bool imagefilledrectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

Creates a rectangle filled with color in the given image starting at point 1 and ending at point 2. 0, 0 is the top left corner of the image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x1

x-coordinate for point 1.

y1

y-coordinate for point 1.

x2

x-coordinate for point 2.

y2

y-coordinate for point 2.

color

The fill color. A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagefilledrectangle() usage

<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$white = imagecolorallocate($im, 255, 255, 255);

// Draw a white rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $white);

// Save the image
imagepng($im, './imagefilledrectangle.png');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagefilledrectangle()

imagefilledpolygon
imagefilltoborder
GD and Image Functions


Flood fill to specific color

imagefilledrectangle
imagefilter
GD and Image Functions
PHP Manual

imagefilltoborder

(PHP 4, PHP 5)

imagefilltoborder — Flood fill to specific color

Description

bool imagefilltoborder ( resource $image , int $x , int $y , int $border , int $color )

imagefilltoborder() performs a flood fill whose border color is defined by border . The starting point for the fill is x , y (top left is 0, 0) and the region is filled with color color .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x

x-coordinate of start.

y

y-coordinate of start.

border

The border color. A color identifier created with imagecolorallocate().

color

The fill color. A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Filling an ellipse with a color

<?php
// Create the image handle, set the background to white
$im = imagecreatetruecolor(100, 100);
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 255, 255, 255));

// Draw an ellipse to fill with a black border
imageellipse($im, 50, 50, 50, 50, imagecolorallocate($im, 0, 0, 0));

// Set the border and fill colors
$border = imagecolorallocate($im, 0, 0, 0);
$fill = imagecolorallocate($im, 255, 0, 0);

// Fill the selection
imagefilltoborder($im, 50, 50, $border, $fill);

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : Filling an ellipse with a color

imagefilledrectangle
imagefilter
GD and Image Functions


Applies a filter to an image

imagefilltoborder
imagefontheight
GD and Image Functions
PHP Manual

imagefilter

(PHP 5)

imagefilter — Applies a filter to an image

Description

bool imagefilter ( resource $image , int $filtertype [, int $arg1 [, int $arg2 [, int $arg3 [, int $arg4 ]]]] )

imagefilter() applies the given filter filtertype on the image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filtertype

filtertype can be one of the following:

  • IMG_FILTER_NEGATE: Reverses all colors of the image.
  • IMG_FILTER_GRAYSCALE: Converts the image into grayscale.
  • IMG_FILTER_BRIGHTNESS: Changes the brightness of the image. Use arg1 to set the level of brightness.
  • IMG_FILTER_CONTRAST: Changes the contrast of the image. Use arg1 to set the level of contrast.
  • IMG_FILTER_COLORIZE: Like IMG_FILTER_GRAYSCALE, except you can specify the color. Use arg1 , arg2 and arg3 in the form of red , blue , green and arg4 for the alpha channel. The range for each color is 0 to 255.
  • IMG_FILTER_EDGEDETECT: Uses edge detection to highlight the edges in the image.
  • IMG_FILTER_EMBOSS: Embosses the image.
  • IMG_FILTER_GAUSSIAN_BLUR: Blurs the image using the Gaussian method.
  • IMG_FILTER_SELECTIVE_BLUR: Blurs the image.
  • IMG_FILTER_MEAN_REMOVAL: Uses mean removal to achieve a "sketchy" effect.
  • IMG_FILTER_SMOOTH: Makes the image smoother. Use arg1 to set the level of smoothness.
  • IMG_FILTER_PIXELATE: Applies pixelation effect to the image, use arg1 to set the block size and arg2 to set the pixelation effect mode.

arg1

  • IMG_FILTER_BRIGHTNESS: Brightness level.
  • IMG_FILTER_CONTRAST: Contrast level.
  • IMG_FILTER_COLORIZE: Value of red component.
  • IMG_FILTER_SMOOTH: Smoothness level.
  • IMG_FILTER_PIXELATE: Block size in pixels.

arg2

  • IMG_FILTER_COLORIZE: Value of green component.
  • IMG_FILTER_PIXELATE: Whether to use advanced pixelation effect or not (defaults to FALSE).

arg3

  • IMG_FILTER_COLORIZE: Value of blue component.

arg4

  • IMG_FILTER_COLORIZE: Alpha channel, A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | Pixelation support (IMG_FILTER_PIXELATE) was added.
5.2.5 | Alpha support for IMG_FILTER_COLORIZE was added.

Examples

Example #1 imagefilter() grayscale example

<?php
$im = imagecreatefrompng('dave.png');

if($im && imagefilter($im, IMG_FILTER_GRAYSCALE))
{
    echo 'Image converted to grayscale.';

    imagepng($im, 'dave.png');
}
else
{
    echo 'Conversion to grayscale failed.';
}

imagedestroy($im);
?>

Example #2 imagefilter() brightness example

<?php
$im = imagecreatefrompng('sean.png');

if($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20))
{
    echo 'Image brightness changed.';

    imagepng($im, 'sean.png');
    imagedestroy($im);
}
else
{
    echo 'Image brightness change failed.';
}
?>

Example #3 imagefilter() colorize example

<?php
$im = imagecreatefrompng('philip.png');

/* R, G, B, so 0, 255, 0 is green */
if($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0))
{
    echo 'Image successfully shaded green.';

    imagepng($im, 'philip.png');
    imagedestroy($im);
}
else
{
    echo 'Green shading failed.';
}
?>

Example #4 imagefilter() negate example

<?php
// Define our negate function so its portable for
// php versions without imagefilter()
function negate($im)
{
    if(function_exists('imagefilter'))
    {
        return imagefilter($im, IMG_FILTER_NEGATE);
    }

    for($x = 0; $x < imagesx($im); ++$x)
    {
        for($y = 0; $y < imagesy($im); ++$y)
        {
            $index = imagecolorat($im, $x, $y);
            $rgb = imagecolorsforindex($index);
            $color = imagecolorallocate($im, 255 - $rgb['red'], 255 - $rgb['green'], 255 - $rgb['blue']);

            imagesetpixel($im, $x, $y, $color);
        }
    }

    return(true);
}

$im = imagecreatefromjpeg('kalle.jpg');

if($im && negate($im))
{
    echo 'Image successfully converted to negative colors.';

    imagejpeg($im, 'kalle.jpg', 100);
    imagedestroy($im);
}
else
{
    echo 'Converting to negative colors failed.';
}
?>

Example #5 imagefilter() pixelate example

<?php
// Load the PHP logo, we need to create two instances
// to show the differences
$logo1 = imagecreatefrompng('./php.png');
$logo2 = imagecreatefrompng('./php.png');

// Create the image instance we want to show the
// differences on
$output = imagecreatetruecolor(imagesx($logo1) * 2, imagesy($logo1));

// Apply pixelation to each instance, with a block
// size of 3
imagefilter($logo1, IMG_FILTER_PIXELATE, 3);
imagefilter($logo2, IMG_FILTER_PIXELATE, 3, true);

// Merge the differences onto the output image
imagecopy($output, $logo1, 0, 0, 0, 0, imagesx($logo1) - 1, imagesy($logo1) - 1);
imagecopy($output, $logo2, imagesx($logo2), 0, 0, 0, imagesx($logo2) - 1, imagesy($logo2) - 1);
imagedestroy($logo1);
imagedestroy($logo2);

// Output the differences
header('Content-Type: image/png');
imagepng($output);
imagedestroy($output);
?>

The above example will output something similar to:

Output of example : imagefilter() pixelate

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

See Also

  • imageconvolution() - Apply a 3x3 convolution matrix, using coefficient and offset

imagefilltoborder
imagefontheight
GD and Image Functions


Get font height

imagefilter
imagefontwidth
GD and Image Functions
PHP Manual

imagefontheight

(PHP 4, PHP 5)

imagefontheight — Get font height

Description

int imagefontheight ( int $font )

Returns the pixel height of a character in the specified font.

Parameters

font

Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

Return Values

Returns the height of the pixel.

Examples

Example #1 Using imagefontheight() on built-in fonts

<?php
echo 'Font height: ' . imagefontheight(4);
?>

The above example will output something similar to:

Font height: 16

Example #2 Using imagefontheight() together with imageloadfont()

<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');

echo 'Font height: ' . imagefontheight($font);
?>

The above example will output something similar to:

Font height: 43

See Also

  • imagefontwidth() - Get font width
  • imageloadfont() - Load a new font

imagefilter
imagefontwidth
GD and Image Functions


Get font width

imagefontheight
imageftbbox
GD and Image Functions
PHP Manual

imagefontwidth

(PHP 4, PHP 5)

imagefontwidth — Get font width

Description

int imagefontwidth ( int $font )

Returns the pixel width of a character in font.

Parameters

font

Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

Return Values

Returns the width of the pixel

Examples

Example #1 Using imagefontwidth() on built-in fonts

<?php
echo 'Font width: ' . imagefontwidth(4);
?>

The above example will output something similar to:

Font width: 8

Example #2 Using imagefontwidth() together with imageloadfont()

<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');

echo 'Font width: ' . imagefontwidth($font);
?>

The above example will output something similar to:

Font width: 23

See Also

  • imagefontheight() - Get font height
  • imageloadfont() - Load a new font

imagefontheight
imageftbbox
GD and Image Functions


Give the bounding box of a text using fonts via freetype2

imagefontwidth
imagefttext
GD and Image Functions
PHP Manual

imageftbbox

(PHP 4 >= 4.0.7, PHP 5)

imageftbbox — Give the bounding box of a text using fonts via freetype2

Description

array imageftbbox ( float $size , float $angle , string $fontfile , string $text [, array $extrainfo ] )

This function calculates and returns the bounding box in pixels for a FreeType text.

Parameters

size

The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).

angle

Angle in degrees in which text will be measured.

fontfile

The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path.

text

The string to be measured.

extrainfo

Possible array indexes for extrainfo
Key | Type | Meaning
linespacing | float | Defines drawing linespacing

Return Values

imageftbbox() returns an array with 8 elements representing four points making the bounding box of the text:

0 | lower left corner, X position
1 | lower left corner, Y position
2 | lower right corner, X position
3 | lower right corner, Y position
4 | upper right corner, X position
5 | upper right corner, Y position
6 | upper left corner, X position
7 | upper left corner, Y position

The points are relative to the text regardless of the angle , so "upper left" means in the top left-hand corner seeing the text horizontally.

Examples

Example #1 imageftbbox() example

<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);

// Path to our font file
$font = './arial.ttf';

// First we create our bounding box
$bbox = imageftbbox(10, 0, $font, 'The PHP Documentation Group');

// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 5;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

imagefttext($im, 10, 0, $x, $y, $black, $font, 'The PHP Documentation Group');

// Output to browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Note: This function is only available if PHP is compiled with freetype support (--with-freetype-dir=DIR)

Changelog

Version | Description
4.3.5 | extrainfo was made optional.

imagefontwidth
imagefttext
GD and Image Functions


Write text to the image using fonts using FreeType 2

imageftbbox
imagegammacorrect
GD and Image Functions
PHP Manual

imagefttext

(PHP 4 >= 4.0.7, PHP 5)

imagefttext — Write text to the image using fonts using FreeType 2

Description

array imagefttext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text [, array $extrainfo ] )

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

size

The font size to use in points.

angle

The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.

x

The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x and y define the upper-left corner of the first character. For example, "top left" is 0, 0.

y

The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

color

The index of the desired color for the text, see imagecolorexact().

fontfile

The path to the TrueType font you wish to use.

Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.

In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.

<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

text

Text to be inserted into image.

extrainfo

Possible array indexes for extrainfo
Key | Type | Meaning
linespacing | float | Defines drawing linespacing

Return Values

This function returns an array defining the four points of the box, starting in the lower left and moving counter-clockwise:

0 | lower left x-coordinate
1 | lower left y-coordinate
2 | lower right x-coordinate
3 | lower right y-coordinate
4 | upper right x-coordinate
5 | upper right y-coordinate
6 | upper left x-coordinate
7 | upper left y-coordinate

Examples

Example #1 imagefttext() example

<?php
// Create a 300x100 image
$im = imagecreatetruecolor(300, 100);
$red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

// Make the background red
imagefilledrectangle($im, 0, 0, 299, 99, $red);

// Path to our ttf font file
$font_file = './arial.ttf';

// Draw the text 'PHP Manual' using font size 13
imagefttext($im, 13, 0, 105, 55, $black, $font_file, 'PHP Manual');

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Note: This function is only available if PHP is compiled with freetype support (--with-freetype-dir=DIR)

Changelog

Version | Description
4.3.5 | extrainfo was made optional.

imageftbbox
imagegammacorrect
GD and Image Functions


Apply a gamma correction to a GD image

imagefttext
imagegd2
GD and Image Functions
PHP Manual

imagegammacorrect

(PHP 4, PHP 5)

imagegammacorrect — Apply a gamma correction to a GD image

Description

bool imagegammacorrect ( resource $image , float $inputgamma , float $outputgamma )

Applies gamma correction to the given gd image given an input and an output gamma.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

inputgamma

The input gamma.

outputgamma

The output gamma.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagegammacorrect() usage

<?php
// Create image instance
$im = imagecreatefromgif('php.gif');

// Correct gamma, out = 1.537
imagegammacorrect($im, 1.0, 1.537);

// Save and free image
imagegif($im, './php_gamma_corrected.gif');
imagedestroy($im);
?>

imagefttext
imagegd2
GD and Image Functions


Output GD image to browser or file

imagegd2
imagegif
GD and Image Functions
PHP Manual

imagegd

(PHP 4 >= 4.0.7, PHP 5)

imagegd — Output GD image to browser or file

Description

bool imagegd ( resource $image [, string $filename ] )

Outputs a GD image to the given filename .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Outputting a GD image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Output the image
imagegd($im);

// Free up memory
imagedestroy($im);
?>

Example #2 Saving a GD image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Save the gd image
// The file format for GD images is .gd, see http://www.libgd.org/GdFileFormats
imagegd($im, 'simple.gd');

// Free up memory
imagedestroy($im);
?>

Notes

Note: The GD format is commonly used to allow fast loading of parts of images. Note that the GD format is only usable in GD-compatible applications.

See Also

  • imagegd2() - Output GD2 image to browser or file

imagegd2
imagegif
GD and Image Functions


Output GD2 image to browser or file

imagegammacorrect
imagegd
GD and Image Functions
PHP Manual

imagegd2

(PHP 4 >= 4.0.7, PHP 5)

imagegd2 — Output GD2 image to browser or file

Description

bool imagegd2 ( resource $image [, string $filename [, int $chunk_size [, int $type ]]] )

Outputs a GD2 image to the given filename .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

chunk_size

Chunk size.

type

Either IMG_GD2_RAW or IMG_GD2_COMPRESSED. Default is IMG_GD2_RAW.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Outputting a GD2 image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Output the image
imagegd2($im);

// Free up memory
imagedestroy($im);
?>

Example #2 Saving a GD2 image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Save the gd2 image
// The file format for GD2 images is .gd2, see http://www.libgd.org/GdFileFormats
imagegd2($im, 'simple.gd2');

// Free up memory
imagedestroy($im);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

Note: The GD2 format is commonly used to allow fast loading of parts of images. Note that the GD2 format is only usable in GD2-compatible applications.

Changelog

Version | Description
4.3.2 | chunk_size and type were added.

See Also

  • imagegd() - Output GD image to browser or file

imagegammacorrect
imagegd
GD and Image Functions


Output image to browser or file

imagegd
imagegrabscreen
GD and Image Functions
PHP Manual

imagegif

(PHP 4, PHP 5)

imagegif — Output image to browser or file

Description

bool imagegif ( resource $image [, string $filename ] )

imagegif() creates the GIF file in filename from the image image . The image argument is the return from the imagecreate() or imagecreatefrom* function.

The image format will be GIF87a unless the image has been made transparent with imagecolortransparent(), in which case the image format will be GIF89a.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Outputting an image using imagegif()

<?php
// Create a new image instance
$im = imagecreatetruecolor(100, 100);

// Make the background white
imagefilledrectangle($im, 0, 0, 99, 99, 0xFFFFFF);

// Draw a text string on the image
imagestring($im, 3, 40, 20, 'GD Library', 0xFFBA00);

// Output the image to browser
header('Content-type: image/gif');

imagegif($im);
imagedestroy($im);
?>

Example #2 Converting a PNG image to GIF using imagegif()

<?php

// Load the PNG
$png = imagecreatefrompng('./php.png');

// Save the image as a GIF
imagegif($png, './php.gif');

// Free from memory
imagedestroy($png);

// We're done
echo 'Converted PNG image to GIF with success!';
?>

Notes

Note: GIF support was removed from the GD library in Version 1.6, and added back in Version 2.0.28. This function is not available between these versions. For more information, see the » GD Project site.
The following code snippet allows you to write more portable PHP applications by auto-detecting the type of GD support which is available. Replace the sequence header ("Content-type: image/gif"); imagegif ($im); by the more flexible sequence:

<?php
// Create a new image instance
$im = imagecreatetruecolor(100, 100);

// Do some image operations here

// Handle output
if(function_exists('imagegif'))
{
    // For GIF
    header('Content-type: image/gif');

    imagegif($im);
}
elseif(function_exists('imagejpeg'))
{
    // For JPEG
    header('Content-type: image/jpeg');

    imagejpeg($im, NULL, 100);
}
elseif(function_exists('imagepng'))
{
    // For PNG
    header('Content-type: image/png');

    imagepng($im);
}
elseif(function_exists('imagewbmp'))
{
    // For WBMP
    header('Content-type: image/vnd.wap.wbmp');

    imagewbmp($im);
}
else
{
    imagedestroy($im);

    die('No image support in this PHP server');
}

// If image support was found for one of these
// formats, then free it from memory
if($im)
{
    imagedestroy($im);
}
?>

Note: As of PHP 4.0.2 you can use the function imagetypes() in place of function_exists() for checking the presence of the various supported image formats:

<?php
if(imagetypes() & IMG_GIF)
{
    header('Content-type: image/gif');
    imagegif($im);
}
elseif(imagetypes() & IMG_JPG)
{
    /* ... etc. */
}
?>

See Also

  • imagepng() - Output a PNG image to either the browser or a file
  • imagewbmp() - Output image to browser or file
  • imagejpeg() - Output image to browser or file
  • imagetypes() - Return the image types supported by this PHP build

imagegd
imagegrabscreen
GD and Image Functions


Captures the whole screen

imagegif
imagegrabwindow
GD and Image Functions
PHP Manual

imagegrabscreen

(PHP 5 >= 5.2.2)

imagegrabscreen — Captures the whole screen

Description

resource imagegrabscreen ( void )

Grabs a screenshot of the whole screen.

Return Values

Returns an image resource identifier on success, FALSE on failure.

Examples

Example #1 imagegrabscreen() example

This example demonstrates how to take a screenshot of the current screen and save it as a png image.

<?php
$im = imagegrabscreen();
imagepng($im, "myscreenshot.png");
imagedestroy($im);
?>

Notes

Note: This function is only available on Windows.

See Also

  • imagegrabwindow() - Captures a window

imagegif
imagegrabwindow
GD and Image Functions


Captures a window

imagegrabscreen
imageinterlace
GD and Image Functions
PHP Manual

imagegrabwindow

(PHP 5 >= 5.2.2)

imagegrabwindow — Captures a window

Description

resource imagegrabwindow ( int $window_handle [, int $client_area = 0 ] )

Grabs a window or its client area using a windows handle (HWND property in COM instance)

Parameters

window_handle

The HWND window ID.

client_area

Include the client area of the application window.

Return Values

Returns an image resource identifier on success, FALSE on failure.

Errors/Exceptions

E_NOTICE is issued if window_handle is invalid window handle. E_WARNING is issued if the Windows API is too old.

Examples

Example #1 imagegrabwindow() example

Capture a window (IE for example)

<?php
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$im = imagegrabwindow($handle);
$browser->Quit();
imagepng($im, "iesnap.png");
imagedestroy($im);
?>

Capture a window (IE for example) but with its content

<?php
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$browser->Navigate("http://www.libgd.org");

/* Still working? */
while ($browser->Busy) {
    com_message_pump(4000);
}
$im = imagegrabwindow($handle, 0);
$browser->Quit();
imagepng($im, "iesnap.png");
imagedestroy($im);
?>

Notes

Note: This function is only available on Windows.

See Also

  • imagegrabscreen() - Captures the whole screen

imagegrabscreen
imageinterlace
GD and Image Functions


Enable or disable interlace

imagegrabwindow
imageistruecolor
GD and Image Functions
PHP Manual

imageinterlace

(PHP 4, PHP 5)

imageinterlace — Enable or disable interlace

Description

int imageinterlace ( resource $image [, int $interlace = 0 ] )

imageinterlace() turns the interlace bit on or off.

If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

interlace

If non-zero, the image will be interlaced, else the interlace bit is turned off.

Return Values

Returns 1 if the interlace bit is set for the image, 0 otherwise.

Examples

Example #1 Turn on interlacing using imageinterlace()

<?php
// Create an image instance
$im = imagecreatefromgif('php.gif');

// Enable interlancing
imageinterlace($im, true);

// Save the interlaced image
imagegif($im, './php_interlaced.gif');
imagedestroy($im);
?>

imagegrabwindow
imageistruecolor
GD and Image Functions


Finds whether an image is a truecolor image

imageinterlace
imagejpeg
GD and Image Functions
PHP Manual

imageistruecolor

(PHP 4 >= 4.3.2, PHP 5)

imageistruecolor — Finds whether an image is a truecolor image

Description

bool imageistruecolor ( resource $image )

imageistruecolor() finds whether the image image is a truecolor image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Returns TRUE if the image is truecolor, FALSE otherwise.

Examples

Example #1 Simple detection of true color image instances using imageistruecolor()

<?php
// $im is an image instance

// Check if image is a true color image or not
if(!imageistruecolor($im))
{
    // Create a new true color image instance
    $tc = imagecreatetruecolor(imagesx($im), imagesy($im));

    imagecopy($tc, $im, 0, 0, 0, 0, imagesx($im), imagesy($im));
    imagedestroy($im);

    $im = $tc;
    $tc = NULL;
}

// Continue working with image instance
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecreatetruecolor() - Create a new true color image

imageinterlace
imagejpeg
GD and Image Functions


Output image to browser or file

imageistruecolor
imagelayereffect
GD and Image Functions
PHP Manual

imagejpeg

(PHP 4, PHP 5)

imagejpeg — Output image to browser or file

Description

bool imagejpeg ( resource $image [, string $filename [, int $quality ]] )

imagejpeg() creates a JPEG file from the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

To skip this argument in order to provide the quality parameter, use NULL.

quality

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Outputting a JPEG image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/jpeg
header('Content-type: image/jpeg');

// Output the image
imagejpeg($im);

// Free up memory
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : Outputting a JPEG image

Example #2 Saving a JPEG image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Save the image as 'simpletext.jpg'
imagejpeg($im, 'simpletext.jpg');

// Free up memory
imagedestroy($im);
?>

Example #3 Outputting the image at 75% quality

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/jpeg
header('Content-type: image/jpeg');

// Skip the filename parameter using NULL, then set the quality to 75%
imagejpeg($im, NULL, 75);

// Free up memory
imagedestroy($im);
?>

Notes

Note: JPEG support is only available if PHP was compiled against GD-1.8 or later.

Note: If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().

See Also

  • imagepng() - Output a PNG image to either the browser or a file
  • imagegif() - Output image to browser or file
  • imagewbmp() - Output image to browser or file
  • imageinterlace() - Enable or disable interlace
  • imagetypes() - Return the image types supported by this PHP build

imageistruecolor
imagelayereffect
GD and Image Functions


Set the alpha blending flag to use the bundled libgd layering effects

imagejpeg
imageline
GD and Image Functions
PHP Manual

imagelayereffect

(PHP 4 >= 4.3.0, PHP 5)

imagelayereffect — Set the alpha blending flag to use the bundled libgd layering effects

Description

bool imagelayereffect ( resource $image , int $effect )

Set the alpha blending flag to use the bundled libgd layering effects.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

effect

One of the following constants:

IMG_EFFECT_REPLACE
Use pixel replacement (equivalent of passing TRUE to imagealphablending())
IMG_EFFECT_ALPHABLEND
Use normal pixel blending (equivalent of passing FALSE to imagealphablending())
IMG_EFFECT_NORMAL
Same as IMG_EFFECT_ALPHABLEND.
IMG_EFFECT_OVERLAY
Overlay has the effect that black background pixels will remain black, white background pixels will remain white, but grey background pixels will take the colour of the foreground pixel.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagelayereffect() example

<?php
// Setup an image
$im = imagecreatetruecolor(100, 100);

// Set a background
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 220, 220, 220));

// Apply the overlay alpha blending flag
imagelayereffect($im, IMG_EFFECT_OVERLAY);

// Draw two grey ellipses
imagefilledellipse($im, 50, 50, 40, 40, imagecolorallocate($im, 100, 255, 100));
imagefilledellipse($im, 50, 50, 50, 80, imagecolorallocate($im, 100, 100, 255));
imagefilledellipse($im, 50, 50, 80, 50, imagecolorallocate($im, 255, 100, 100));

// Output
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagelayereffect()

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

imagejpeg
imageline
GD and Image Functions


Draw a line

imagelayereffect
imageloadfont
GD and Image Functions
PHP Manual

imageline

(PHP 4, PHP 5)

imageline — Draw a line

Description

bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

Draws a line between the two given points.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x1

x-coordinate for first point.

y1

y-coordinate for first point.

x2

x-coordinate for second point.

y2

y-coordinate for second point.

color

The line color. A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Drawing a thick line

<?php

function imagelinethick($image, $x1, $y1, $x2, $y2, $color, $thick = 1)
{
    /* this way it works well only for orthogonal lines
    imagesetthickness($image, $thick);
    return imageline($image, $x1, $y1, $x2, $y2, $color);
    */
    if ($thick == 1) {
        return imageline($image, $x1, $y1, $x2, $y2, $color);
    }
    $t = $thick / 2 - 0.5;
    if ($x1 == $x2 || $y1 == $y2) {
        return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color);
    }
    $k = ($y2 - $y1) / ($x2 - $x1); //y = kx + q
    $a = $t / sqrt(1 + pow($k, 2));
    $points = array(
        round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a),
        round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a),
        round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a),
        round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a),
    );
    imagefilledpolygon($image, $points, 4, $color);
    return imagepolygon($image, $points, 4, $color);
}

?>

See Also

  • imagecreatetruecolor() - Create a new true color image
  • imagecolorallocate() - Allocate a color for an image

imagelayereffect
imageloadfont
GD and Image Functions


Load a new font

imageline
imagepalettecopy
GD and Image Functions
PHP Manual

imageloadfont

(PHP 4, PHP 5)

imageloadfont — Load a new font

Description

int imageloadfont ( string $file )

imageloadfont() loads a user-defined bitmap and returns its identifier.

Parameters

file

The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.

Font file format
byte position | C data type | description
byte 0-3 | int | number of characters in the font
byte 4-7 | int | value of first character in the font (often 32 for space)
byte 8-11 | int | pixel width of each character
byte 12-15 | int | pixel height of each character
byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes.

Return Values

The font identifier which is always bigger than 5 to avoid conflicts with built-in fonts or FALSE on errors.

Examples

Example #1 imageloadfont() usage example

<?php
// Create a new image instance
$im = imagecreatetruecolor(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Make the background white
imagefilledrectangle($im, 0, 0, 49, 19, $white);

// Load the gd font and write 'Hello'
$font = imageloadfont('./04b.gdf');
imagestring($im, $font, 0, 0, 'Hello', $black);

// Output to browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

See Also

  • imagefontwidth() - Get font width
  • imagefontheight() - Get font height

imageline
imagepalettecopy
GD and Image Functions


Copy the palette from one image to another

imageloadfont
imagepng
GD and Image Functions
PHP Manual

imagepalettecopy

(PHP 4 >= 4.0.1, PHP 5)

imagepalettecopy — Copy the palette from one image to another

Description

void imagepalettecopy ( resource $destination , resource $source )

imagepalettecopy() copies the palette from the source image to the destination image.

Parameters

destination

The destination image resource.

source

The source image resource.

Return Values

No value is returned.

Examples

Example #1 imagepalettecopy() example

<?php
// Create two palette images
$palette1 = imagecreate(100, 100);
$palette2 = imagecreate(100, 100);

// Allocate the background to be
// green in the first palette image
$green = imagecolorallocate($palette1, 0, 255, 0);

// Copy the palette from image 1 to image 2
imagepalettecopy($palette2, $palette1);

// Since the palette is now copied we can use the
// green color allocated to image 1 without using
// imagecolorallocate() twice
imagefilledrectangle($palette2, 0, 0, 99, 99, $green);

// Output image to the browser
header('Content-type: image/png');

imagepng($palette2);
imagedestroy($palette1);
imagedestroy($palette2);
?>

imageloadfont
imagepng
GD and Image Functions


Output a PNG image to either the browser or a file

imagepalettecopy
imagepolygon
GD and Image Functions
PHP Manual

imagepng

(PHP 4, PHP 5)

imagepng — Output a PNG image to either the browser or a file

Description

bool imagepng ( resource $image [, string $filename [, int $quality [, int $filters ]]] )

Outputs or saves a PNG image from the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

Note: NULL is invalid if the quality and filters arguments are not used.

quality

Compression level: from 0 (no compression) to 9.

filters

Allows reducing the PNG file size. It is a bitmask field which may be set to any combination of the PNG_FILTER_XXX constants. PNG_NO_FILTER or PNG_ALL_FILTERS may also be used to respectively disable or activate all filters.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.1.3 | Added the filters parameter.
5.1.2 | Added the quality parameter.

Examples

<?php
$im = imagecreatefrompng("test.png");

header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

See Also

  • imagegif() - Output image to browser or file
  • imagewbmp() - Output image to browser or file
  • imagejpeg() - Output image to browser or file
  • imagetypes() - Return the image types supported by this PHP build
  • imagesavealpha() - Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

imagepalettecopy
imagepolygon
GD and Image Functions


Draws a polygon

imagepng
imagepsbbox
GD and Image Functions
PHP Manual

imagepolygon

(PHP 4, PHP 5)

imagepolygon — Draws a polygon

Description

bool imagepolygon ( resource $image , array $points , int $num_points , int $color )

imagepolygon() creates a polygon in the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

points

An array containing the polygon's vertices, e.g.:

points[0] | = x0
points[1] | = y0
points[2] | = x1
points[3] | = y1

num_points

Total number of points (vertices).

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagepolygon() example

<?php
// Create a blank image
$image = imagecreatetruecolor(400, 300);

// Allocate a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);

// Draw the polygon
imagepolygon($image, array(
        0,   0,
        100, 200,
        300, 200
    ),
    3,
    $col_poly);

// Output the picture to the browser
header('Content-type: image/png');

imagepng($image);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : imagepolygon()

See Also

  • imagecreate() - Create a new palette based image
  • imagecreatetruecolor() - Create a new true color image

imagepng
imagepsbbox
GD and Image Functions


Give the bounding box of a text rectangle using PostScript Type1 fonts

imagepolygon
imagepsencodefont
GD and Image Functions
PHP Manual

imagepsbbox

(PHP 4, PHP 5)

imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts

Description

array imagepsbbox ( string $text , resource $font , int $size )
array imagepsbbox ( string $text , resource $font , int $size , int $space , int $tightness , float $angle )

Gives the bounding box of a text rectangle using PostScript Type1 fonts.

The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.

Parameters

text

The text to be written.

font_index

A font resource, returned by imagepsloadfont().

size

size is expressed in pixels.

space

Allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

tightness

tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

angle

angle is in degrees.

Return Values

Returns an array containing the following elements:

0 | left x-coordinate
1 | upper y-coordinate
2 | right x-coordinate
3 | lower y-coordinate

Examples

Example #1 imagepsbbox() usage

<?php
// Create image handle
$im = imagecreatetruecolor(200, 200);

// Allocate colors
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Load the PostScript Font
$font = imagepsloadfont('font.pfm');

// Make a bounding box for the font
$bbox = imagepsbbox('Sample text is simple', $font, 12);

// Define our X and Y cordinates
$x = ($bbox[2] / 2) - 10;
$y = ($bbox[3] / 2) - 10;

// Write the font to the image
imagepstext($im, 'Sample text is simple', $font, 12, $black, $white, $x, $y);

// Output and free memory
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

See Also

  • imagepstext() - Draws a text over an image using PostScript Type1 fonts

imagepolygon
imagepsencodefont
GD and Image Functions


Change the character encoding vector of a font

imagepsbbox
imagepsextendfont
GD and Image Functions
PHP Manual

imagepsencodefont

(PHP 4, PHP 5)

imagepsencodefont — Change the character encoding vector of a font

Description

bool imagepsencodefont ( resource $font_index , string $encodingfile )

Loads a character encoding vector from a file and changes the fonts encoding vector to it. As a PostScript fonts default vector lacks most of the character positions above 127, you'll definitely want to change this if you use an other language than English.

If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding.

Parameters

font_index

A font resource, returned by imagepsloadfont().

encodingfile

The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagepsencodefont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Tell T1lib to use ISO Latin 1 encoding
imagepsencode($font, './IsoLatin1.enc');

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

imagepsbbox
imagepsextendfont
GD and Image Functions


Extend or condense a font

imagepsencodefont
imagepsfreefont
GD and Image Functions
PHP Manual

imagepsextendfont

(PHP 4, PHP 5)

imagepsextendfont — Extend or condense a font

Description

bool imagepsextendfont ( resource $font_index , float $extend )

Extend or condense a font (font_index ), if the value of the extend parameter is less than one you will be condensing the font.

Parameters

font_index

A font resource, returned by imagepsloadfont().

extend

Extension value, must be greater than 0.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagepsextendfont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Extend the font by 2.5
imagepsextendfont($font, 2.5);

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

imagepsencodefont
imagepsfreefont
GD and Image Functions


Free memory used by a PostScript Type 1 font

imagepsextendfont
imagepsloadfont
GD and Image Functions
PHP Manual

imagepsfreefont

(PHP 4, PHP 5)

imagepsfreefont — Free memory used by a PostScript Type 1 font

Description

bool imagepsfreefont ( resource $font_index )

imagepsfreefont() frees memory used by a PostScript Type 1 font.

Parameters

font_index

A font resource, returned by imagepsloadfont().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagepsfreefont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./bchbi.pfb');

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

See Also

  • imagepsloadfont() - Load a PostScript Type 1 font from file

imagepsextendfont
imagepsloadfont
GD and Image Functions


Load a PostScript Type 1 font from file

imagepsfreefont
imagepsslantfont
GD and Image Functions
PHP Manual

imagepsloadfont

(PHP 4, PHP 5)

imagepsloadfont — Load a PostScript Type 1 font from file

Description

resource imagepsloadfont ( string $filename )

Load a PostScript Type 1 font from the given filename .

Parameters

filename

Path to the Postscript font file.

Return Values

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE.

Examples

Example #1 imagepsloadfont() example

<?php
// Create a new image instance
$im = imagecreatetruecolor(350, 45);

// Allocate colors and fill the background
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 349, 44, $white);

// Load a font, write to the image and free the font from memory
$font = imagepsloadfont("bchbi.pfb");
imagepstext($im, "Testing... It worked!", $font, 32, $white, $black, 32, 32);
imagepsfreefont($font);

// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

See Also

  • imagepsfreefont() - Free memory used by a PostScript Type 1 font

imagepsfreefont
imagepsslantfont
GD and Image Functions


Slant a font

imagepsloadfont
imagepstext
GD and Image Functions
PHP Manual

imagepsslantfont

(PHP 4, PHP 5)

imagepsslantfont — Slant a font

Description

bool imagepsslantfont ( resource $font_index , float $slant )

Slant a given font given.

Parameters

font_index

A font resource, returned by imagepsloadfont().

slant

Slant level.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagepsslantfont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Slant the font by 22.5
imagepsslantfont($font, 22.5);

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

imagepsloadfont
imagepstext
GD and Image Functions


Draws a text over an image using PostScript Type1 fonts

imagepsslantfont
imagerectangle
GD and Image Functions
PHP Manual

imagepstext

(PHP 4, PHP 5)

imagepstext — Draws a text over an image using PostScript Type1 fonts

Description

array imagepstext ( resource $image , string $text , resource $font_index , int $size , int $foreground , int $background , int $x , int $y [, int $space = 0 [, int $tightness = 0 [, float $angle = 0.0 [, int $antialias_steps = 4 ]]]] )

Draws a text on an image using PostScript Type1 fonts.

Refer to PostScript documentation about fonts and their measuring system if you have trouble understanding how this works.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

text

The text to be written.

font_index

A font resource, returned by imagepsloadfont().

size

size is expressed in pixels.

foreground

The color in which the text will be painted.

background

The color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.

x

x-coordinate for the lower-left corner of the first character.

y

y-coordinate for the lower-left corner of the first character.

space

Allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

tightness

tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

angle

angle is in degrees.

antialias_steps

Allows you to control the number of colours used for antialiasing text. Allowed values are 4 and 16. The higher value is recommended for text sizes lower than 20, where the effect in text quality is quite visible. With bigger sizes, use 4. It's less computationally intensive.

Return Values

This function returns an array containing the following elements:

0 | lower left x-coordinate
1 | lower left y-coordinate
2 | upper right x-coordinate
3 | upper right y-coordinate

Examples

Example #1 imagepstext() usage

<?php
// Create image handle
$im = imagecreatetruecolor(200, 200);

// Allocate colors
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Load the PostScript Font
$font = imagepsloadfont('font.pfm');

// Write the font to the image
imagepstext($im, 'Sample text is simple', $font, 12, $black, $white, 50, 50);

// Output and free memory
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR].

See Also

  • imagepsbbox() - Give the bounding box of a text rectangle using PostScript Type1 fonts

imagepsslantfont
imagerectangle
GD and Image Functions


Draw a rectangle

imagepstext
imagerotate
GD and Image Functions
PHP Manual

imagerectangle

(PHP 4, PHP 5)

imagerectangle — Draw a rectangle

Description

bool imagerectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

imagerectangle() creates a rectangle starting at the specified coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x1

Upper left x coordinate.

y1

Upper left y coordinate 0, 0 is the top left corner of the image.

x2

Bottom right x coordinate.

y2

Bottom right y coordinate.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Simple imagerectangle() example

<?php
// Create a 200 x 200 image
$canvas = imagecreatetruecolor(200, 200);

// Allocate colors
$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 132, 135, 28);

// Draw three rectangles each with its own color
imagerectangle($canvas, 50, 50, 150, 150, $pink);
imagerectangle($canvas, 45, 60, 120, 100, $white);
imagerectangle($canvas, 100, 120, 75, 160, $green);

// Output and free from memory
header('Content-Type: image/jpeg');

imagejpeg($canvas);
imagedestroy($canvas);
?>

The above example will output something similar to:

Output of example : Simple imagerectangle() example

imagepstext
imagerotate
GD and Image Functions


Rotate an image with a given angle

imagerectangle
imagesavealpha
GD and Image Functions
PHP Manual

imagerotate

(PHP 4 >= 4.3.0, PHP 5)

imagerotate — Rotate an image with a given angle

Description

resource imagerotate ( resource $image , float $angle , int $bgd_color [, int $ignore_transparent = 0 ] )

Rotates the image image using the given angle in degrees.

The center of rotation is the center of the image, and the rotated image may have different dimensions than the original image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

angle

Rotation angle, in degrees.

bgd_color

Specifies the color of the uncovered zone after the rotation

ignore_transparent

If set and non-zero, transparent colors are ignored (otherwise kept).

Return Values

Changelog

Version | Description
5.1.0 | ignore_transparent was added.

Examples

Example #1 Rotate an image 180 degrees

This example rotates an image 180 degrees - upside down.

<?php
// File and rotation
$filename = 'test.jpg';
$degrees = 180;

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

// Output
imagejpeg($rotate);
?>

The above example will output something similar to:

Output of example : Rotate an image 180 degrees

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

imagerectangle
imagesavealpha
GD and Image Functions


Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

imagerotate
imagesetbrush
GD and Image Functions
PHP Manual

imagesavealpha

(PHP 4 >= 4.3.2, PHP 5)

imagesavealpha — Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

Description

bool imagesavealpha ( resource $image , bool $saveflag )

imagesavealpha() sets the flag to attempt to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.

You have to unset alphablending (imagealphablending($im, false)), to use it.

Alpha channel is not supported by all browsers, if you have problem with your browser, try to load your script with an alpha channel compliant browser, e.g. latest Mozilla.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

saveflag

Whether to save the alpha channel or not. Default to FALSE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagesavealpha() example

<?php
// Load a png image with alpha channels
$png = imagecreatefrompng('./alphachannel_example.png');

// Do required operations

// Turn off alpha blending and set alpha flag
imagealphablending($png, false);
imagesavealpha($png, true);

// Output image to browser
header('Content-Type: image/png');

imagepng($png);
imagedestroy($png);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagealphablending() - Set the blending mode for an image

imagerotate
imagesetbrush
GD and Image Functions


Set the brush image for line drawing

imagesavealpha
imagesetpixel
GD and Image Functions
PHP Manual

imagesetbrush

(PHP 4 >= 4.0.6, PHP 5)

imagesetbrush — Set the brush image for line drawing

Description

bool imagesetbrush ( resource $image , resource $brush )

imagesetbrush() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

brush

An image resource.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagesetbrush() example

<?php
// Load a mini php logo
$php = imagecreatefrompng('./php.png');

// Create the main image, 100x100
$im = imagecreatetruecolor(100, 100);

// Fill the background with white
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 299, 99, $white);

// Set the brush
imagesetbrush($im, $php);

// Draw a couple of brushes, each overlaying each
imageline($im, 50, 50, 50, 60, IMG_COLOR_BRUSHED);

// Output image to the browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
imagedestroy($php);
?>

The above example will output something similar to:

Output of example : imagesetbrush()

Notes

Note: You need not take special action when you are finished with a brush, but if you destroy the brush image, you must not use the IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED colors until you have set a new brush image!

imagesavealpha
imagesetpixel
GD and Image Functions


Set a single pixel

imagesetbrush
imagesetstyle
GD and Image Functions
PHP Manual

imagesetpixel

(PHP 4, PHP 5)

imagesetpixel — Set a single pixel

Description

bool imagesetpixel ( resource $image , int $x , int $y , int $color )

imagesetpixel() draws a pixel at the specified coordinate.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x

x-coordinate.

y

y-coordinate.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagesetpixel() example

A random drawing that ends with a regular picture.

<?php

$x = 200;
$y = 200;

$gd = imagecreatetruecolor($x, $y);

$corners[0] = array('x' => 100, 'y' =>  10);
$corners[1] = array('x' =>   0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);

$red = imagecolorallocate($gd, 255, 0, 0);

for ($i = 0; $i < 100000; $i++) {
  imagesetpixel($gd, round($x),round($y), $red);
  $a = rand(0, 2);
  $x = ($x + $corners[$a]['x']) / 2;
  $y = ($y + $corners[$a]['y']) / 2;
}

header('Content-Type: image/png');
imagepng($gd);

?>

The above example will output something similar to:

Output of example : imagesetpixel()

See Also

  • imagecreatetruecolor() - Create a new true color image
  • imagecolorallocate() - Allocate a color for an image

imagesetbrush
imagesetstyle
GD and Image Functions


Set the style for line drawing

imagesetpixel
imagesetthickness
GD and Image Functions
PHP Manual

imagesetstyle

(PHP 4 >= 4.0.6, PHP 5)

imagesetstyle — Set the style for line drawing

Description

bool imagesetstyle ( resource $image , array $style )

imagesetstyle() sets the style to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

style

An array of pixel colors. You can use the IMG_COLOR_TRANSPARENT constant to add a transparent pixel.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Following example script draws a dashed line from upper left to lower right corner of the canvas:

Example #1 imagesetstyle() example

<?php
header("Content-type: image/jpeg");
$im  = imagecreatetruecolor(100, 100);
$w   = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);

/* Draw a dashed line, 5 red pixels, 5 white pixels */
$style = array($red, $red, $red, $red, $red, $w, $w, $w, $w, $w);
imagesetstyle($im, $style);
imageline($im, 0, 0, 100, 100, IMG_COLOR_STYLED);

/* Draw a line of happy faces using imagesetbrush() with imagesetstyle */
$style = array($w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $red);
imagesetstyle($im, $style);

$brush = imagecreatefrompng("http://www.libpng.org/pub/png/images/smile.happy.png");
$w2 = imagecolorallocate($brush, 255, 255, 255);
imagecolortransparent($brush, $w2);
imagesetbrush($im, $brush);
imageline($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED);

imagejpeg($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagesetstyle()

See Also

  • imagesetbrush() - Set the brush image for line drawing
  • imageline() - Draw a line

imagesetpixel
imagesetthickness
GD and Image Functions


Set the thickness for line drawing

imagesetstyle
imagesettile
GD and Image Functions
PHP Manual

imagesetthickness

(PHP 4 >= 4.0.6, PHP 5)

imagesetthickness — Set the thickness for line drawing

Description

bool imagesetthickness ( resource $image , int $thickness )

imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, ellipses etc. etc. to thickness pixels.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

thickness

Thickness, in pixels.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagesetthickness() example

<?php
// Create a 200x100 image
$im = imagecreatetruecolor(200, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 99, $white);

// Set the line thickness to 5
imagesetthickness($im, 5);

// Draw the rectangle
imagerectangle($im, 14, 14, 185, 85, $black);

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagesetthickness()

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

imagesetstyle
imagesettile
GD and Image Functions


Set the tile image for filling

imagesetthickness
imagestring
GD and Image Functions
PHP Manual

imagesettile

(PHP 4 >= 4.0.6, PHP 5)

imagesettile — Set the tile image for filling

Description

bool imagesettile ( resource $image , resource $tile )

imagesettile() sets the tile image to be used by all region filling functions (such as imagefill() and imagefilledpolygon()) when filling with the special color IMG_COLOR_TILED.

A tile is an image used to fill an area with a repeated pattern. Any GD image can be used as a tile, and by setting the transparent color index of the tile image with imagecolortransparent(), a tile allows certain parts of the underlying area to shine through can be created.

Note: You need not take special action when you are finished with a tile, but if you destroy the tile image, you must not use the IMG_COLOR_TILED color until you have set a new tile image!

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

tile

The image resource to be used as a tile.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagesettile() example

<?php
// Load an external image
$zend = imagecreatefromgif('./zend.gif');

// Create a 200x200 image
$im = imagecreatetruecolor(200, 200);

// Set the tile
imagesettile($im, $zend);

// Make the image repeat
imagefilledrectangle($im, 0, 0, 199, 199, IMG_COLOR_TILED);

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
imagedestroy($zend);
?>

The above example will output something similar to:

Output of example : imagesettile()

imagesetthickness
imagestring
GD and Image Functions


Draw a string horizontally

imagesettile
imagestringup
GD and Image Functions
PHP Manual

imagestring

(PHP 4, PHP 5)

imagestring — Draw a string horizontally

Description

bool imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color )

Draws a string at the given coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

font

Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the upper left corner.

y

y-coordinate of the upper left corner.

string

The string to be written.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagestring() example

<?php
// Create a 100*30 image
$im = imagecreate(100, 30);

// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);

// Write the string at the top left
imagestring($im, 5, 0, 0, 'Hello world!', $textcolor);

// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagestring()

See Also

  • imageloadfont() - Load a new font
  • imagettftext() - Write text to the image using TrueType fonts

imagesettile
imagestringup
GD and Image Functions


Draw a string vertically

imagestring
imagesx
GD and Image Functions
PHP Manual

imagestringup

(PHP 4, PHP 5)

imagestringup — Draw a string vertically

Description

bool imagestringup ( resource $image , int $font , int $x , int $y , string $string , int $color )

Draws a string vertically at the given coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

font

Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the upper left corner.

y

y-coordinate of the upper left corner.

string

The string to be written.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imagestringup() example

<?php
// create a 100*100 image
$im = imagecreatetruecolor(100, 100);

// Write the text
$textcolor = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
imagestringup($im, 3, 40, 80, 'gd library', $textcolor);

// Save the image
imagepng($im, './stringup.png');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagestringup()

See Also

  • imageloadfont() - Load a new font

imagestring
imagesx
GD and Image Functions


Get image width

imagestringup
imagesy
GD and Image Functions
PHP Manual

imagesx

(PHP 4, PHP 5)

imagesx — Get image width

Description

int imagesx ( resource $image )

Returns the width of the given image resource.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Return the width of the image or FALSE on errors.

Examples

Example #1 Using imagesx()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesx($img); // 300

?>

See Also

  • imagecreatetruecolor() - Create a new true color image
  • getimagesize() - Get the size of an image
  • imagesy() - Get image height

imagestringup
imagesy
GD and Image Functions


Get image height

imagesx
imagetruecolortopalette
GD and Image Functions
PHP Manual

imagesy

(PHP 4, PHP 5)

imagesy — Get image height

Description

int imagesy ( resource $image )

Returns the height of the given image resource.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Return the height of the image or FALSE on errors.

Examples

Example #1 Using imagesy()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesy($img); // 200

?>

See Also

  • imagecreatetruecolor() - Create a new true color image
  • getimagesize() - Get the size of an image
  • imagesx() - Get image width

imagesx
imagetruecolortopalette
GD and Image Functions


Convert a true color image to a palette image

imagesy
imagettfbbox
GD and Image Functions
PHP Manual

imagetruecolortopalette

(PHP 4 >= 4.0.6, PHP 5)

imagetruecolortopalette — Convert a true color image to a palette image

Description

bool imagetruecolortopalette ( resource $image , bool $dither , int $ncolors )

imagetruecolortopalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

dither

Indicates if the image should be dithered - if it is TRUE then dithering will be used which will result in a more speckled image but with better color approximation.

ncolors

Sets the maximum number of colors that should be retained in the palette.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Converting a true color image to a palette-based image

<?php
// Create a new true color image
$im = imagecreatetruecolor(100, 100);

// Convert to palette-based with no dithering and 255 colors
imagetruecolortopalette($im, false, 255);

// Save the image
imagepng($im, './paletteimage.png');
imagedestroy($im);
?>

Notes

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

imagesy
imagettfbbox
GD and Image Functions


Give the bounding box of a text using TrueType fonts

imagetruecolortopalette
imagettftext
GD and Image Functions
PHP Manual

imagettfbbox

(PHP 4, PHP 5)

imagettfbbox — Give the bounding box of a text using TrueType fonts

Description

array imagettfbbox ( float $size , float $angle , string $fontfile , string $text )

This function calculates and returns the bounding box in pixels for a TrueType text.

Parameters

size

The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).

angle

Angle in degrees in which text will be measured.

fontfile

The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path.

text

The string to be measured.

Return Values

imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text on success and FALSE on error.

key | contents
0 | lower left corner, X position
1 | lower left corner, Y position
2 | lower right corner, X position
3 | lower right corner, Y position
4 | upper right corner, X position
5 | upper right corner, Y position
6 | upper left corner, X position
7 | upper left corner, Y position

The points are relative to the text regardless of the angle , so "upper left" means in the top left-hand corner seeing the text horizontally.

Examples

Example #1 imagettfbbox() example

<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);

// Path to our font file
$font = './arial.ttf';

// First we create our bounding box for the first text
$bbox = imagettfbbox(10, 45, $font, 'Powered by PHP ' . phpversion());

// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 25;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

// Write it
imagettftext($im, 10, 45, $x, $y, $black, $font, 'Powered by PHP ' . phpversion());

// Create the next bounding box for the second text
$bbox = imagettfbbox(10, 45, $font, 'and Zend Engine ' . zend_version());

// Set the cordinates so its next to the first text
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) + 10;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

// Write it
imagettftext($im, 10, 45, $x, $y, $black, $font, 'and Zend Engine ' . zend_version());

// Output to browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function requires both the GD library and the » FreeType library.

See Also

  • imagettftext() - Write text to the image using TrueType fonts

imagetruecolortopalette
imagettftext
GD and Image Functions


Write text to the image using TrueType fonts

imagettfbbox
imagetypes
GD and Image Functions
PHP Manual

imagettftext

(PHP 4, PHP 5)

imagettftext — Write text to the image using TrueType fonts

Description

array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )

Writes the given text into the image using TrueType fonts.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

size

The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).

angle

The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.

x

The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x and y define the upper-left corner of the first character. For example, "top left" is 0, 0.

y

The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

color

The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate().

fontfile

The path to the TrueType font you wish to use.

Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.

In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.

<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

text

The text string in UTF-8 encoding.

May include decimal numeric character references (of the form: &#8364;) to access characters in a font beyond position 127. The hexadecimal format (like &#xA9;) is supported. Strings in UTF-8 encoding can be passed directly.

Named entities, such as &copy;, are not supported. Consider using html_entity_decode() to decode these named entities into UTF-8 strings (html_entity_decode() supports this as of PHP 5.0.0).

If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character.

Return Values

Returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontally. Returns FALSE on error.

Changelog

Version | Description
5.2.0 | It is now possible to specify an hexadecimal entity in text .

Examples

Example #1 imagettftext() example

This example script will produce a white PNG 400x30 pixels, with the words "Testing..." in black (with grey shadow), in the font Arial.

<?php
// Set the content-type
header('Content-type: image/png');

// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagettftext()

Notes

Note: This function requires both the GD library and the » FreeType library.

See Also

  • imagettfbbox() - Give the bounding box of a text using TrueType fonts

imagettfbbox
imagetypes
GD and Image Functions


Return the image types supported by this PHP build

imagettftext
imagewbmp
GD and Image Functions
PHP Manual

imagetypes

(PHP 4 >= 4.0.2, PHP 5)

imagetypes — Return the image types supported by this PHP build

Description

int imagetypes ( void )

Returns the image types supported by the current PHP installation.

Return Values

Returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM.

Examples

Example #1 Checking for PNG support

<?php
if (imagetypes() & IMG_PNG) {
    echo "PNG Support is enabled";
}
?>

imagettftext
imagewbmp
GD and Image Functions


Output image to browser or file

imagetypes
imagexbm
GD and Image Functions
PHP Manual

imagewbmp

(PHP 4 >= 4.0.1, PHP 5)

imagewbmp — Output image to browser or file

Description

bool imagewbmp ( resource $image [, string $filename [, int $foreground ]] )

imagewbmp() outputs or save a WBMP version of the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

foreground

You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Outputting a WBMP image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/vnd.wap.wbmp
// Hint: see image_type_to_mime_type() for content-types
header('Content-type: image/vnd.wap.wbmp');

// Output the image
imagewbmp($im);

// Free up memory
imagedestroy($im);
?>

Example #2 Saving the WBMP image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Save the image
imagewbmp($im, 'simpletext.wbmp');

// Free up memory
imagedestroy($im);
?>

Example #3 Outputting the image with a different foreground

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/vnd.wap.wbmp
// Hint: see image_type_to_mime_type() for content-types
header('Content-type: image/vnd.wap.wbmp');

// Set a replacement foreground color
$foreground_color = imagecolorallocate($im, 255, 0, 0);

imagewbmp($im, NULL, $foreground_color);

// Free up memory
imagedestroy($im);
?>

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See Also

  • image2wbmp() - Output image to browser or file
  • imagepng() - Output a PNG image to either the browser or a file
  • imagegif() - Output image to browser or file
  • imagejpeg() - Output image to browser or file
  • imagetypes() - Return the image types supported by this PHP build

imagetypes
imagexbm
GD and Image Functions


Output XBM image to browser or file

imagewbmp
iptcembed
GD and Image Functions
PHP Manual

imagexbm

(PHP 5)

imagexbm — Output XBM image to browser or file

Description

bool imagexbm ( resource $image , string $filename [, int $foreground ] )

Outputs or save an XBM version of the given image .

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

foreground

You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Saving an XBM file

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Save the image
imagexbm($im, 'simpletext.xbm');

// Free up memory
imagedestroy($im);
?>

Example #2 Saving an XBM file with a different foreground color

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set a replacement foreground color
$foreground_color = imagecolorallocate($im, 255, 0, 0);

// Save the image
imagexbm($im, NULL, $foreground_color);

// Free up memory
imagedestroy($im);
?>

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

imagewbmp
iptcembed
GD and Image Functions


Adds adaptive blur filter to image

The Imagick class
Imagick::adaptiveResizeImage
The Imagick class
PHP Manual

Imagick::adaptiveBlurImage

(PECL imagick 2.0.0)

Imagick::adaptiveBlurImage — Adds adaptive blur filter to image

Description

bool Imagick::adaptiveBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Adds an adaptive blur filter to image. The intensity of an adaptive blur depends is dramatically decreased at edge of the image, whereas a standard blur is uniform across the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel. Provide a value of 0 and the radius will be chosen automagically.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::adaptiveBlurImage():

Adaptively blur an image, then display to the browser.

<?php

header('Content-type: image/jpeg');

$image = new Imagick('test.jpg');

$image->adaptiveBlurImage(5,3);
echo $image;

?>

The above example will output something similar to:

Output of example : Using Imagick::adaptiveBlurImage()

See Also

  • Imagick::blurImage() - Adds blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

The Imagick class
Imagick::adaptiveResizeImage
The Imagick class


Adaptively resize image with data dependent triangulation

Imagick::adaptiveBlurImage
Imagick::adaptiveSharpenImage
The Imagick class
PHP Manual

Imagick::adaptiveResizeImage

(PECL imagick 2.0.0)

Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation

Description

bool Imagick::adaptiveResizeImage ( int $columns , int $rows [, bool $bestfit = false ] )

Adaptively resize image with data-dependent triangulation. Avoids blurring across sharp color changes. Most useful when used to shrink images slightly to a slightly smaller "web size"; may not look good when a full-sized image is adaptively resized to a thumbnail. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Note: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parameters

columns

The number of columns in the scaled image.

rows

The number of rows in the scaled image.

bestfit

Whether to fit the image inside a bounding box.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Added optional fit parameter.
2.1.0 | This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

Examples

Example #1 Using Imagick::adaptiveResizeImage()

Resize an image to a standard size for the web. This method works best when resizing to a size only slightly smaller than the previous image size.

<?php
header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');
$image->adaptiveResizeImage(1024,768);

echo $image;
?>

See Also

  • Imagick::chopImage() - Removes a region of an image and trims
  • Imagick::cropImage() - Extracts a region of the image
  • Imagick::magnifyImage() - Scales an image proportionally 2x
  • Imagick::minifyImage() - Scales an image proportionally to half its size
  • Imagick::resizeImage() - Scales an image
  • Imagick::scaleImage() - Scales the size of an image
  • Imagick::shaveImage() - Shaves pixels from the image edges
  • Imagick::thumbnailImage() - Changes the size of an image
  • Imagick::trimImage() - Remove edges from the image

Imagick::adaptiveBlurImage
Imagick::adaptiveSharpenImage
The Imagick class


Adaptively sharpen the image

Imagick::adaptiveResizeImage
Imagick::adaptiveThresholdImage
The Imagick class
PHP Manual

Imagick::adaptiveSharpenImage

(PECL imagick 2.0.0)

Imagick::adaptiveSharpenImage — Adaptively sharpen the image

Description

bool Imagick::adaptiveSharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Adaptively sharpen the image by sharpening more intensely near image edges and less intensely far from edges. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel. Use 0 for auto-select.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Examples

Example #1 A Imagick::adaptiveSharpenImage() example

Adaptively sharpen the image with radius 2 and sigma 1.

<?php
try {
    $image = new Imagick('image.png');
    $image->adaptiveSharpenImage(2,1);
} catch(ImagickException $e) {
    echo 'Error: ' , $e->getMessage();
    die();
}
header('Content-type: image/png');
echo $image;
?>

See Also

  • Imagick::sharpenImage() - Sharpens an image

Imagick::adaptiveResizeImage
Imagick::adaptiveThresholdImage
The Imagick class


Selects a threshold for each pixel based on a range of intensity

Imagick::adaptiveSharpenImage
Imagick::addImage
The Imagick class
PHP Manual

Imagick::adaptiveThresholdImage

(PECL imagick 2.0.0)

Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity

Description

bool Imagick::adaptiveThresholdImage ( int $width , int $height , int $offset )

Selects an individual threshold for each pixel based on the range of intensity values in its local neighborhood. This allows for thresholding of an image whose global intensity histogram doesn't contain distinctive peaks.

Parameters

width

Width of the local neighborhood.

height

Height of the local neighborhood.

offset

The mean offset

Return Values

Returns TRUE on success.

Imagick::adaptiveSharpenImage
Imagick::addImage
The Imagick class


Adds new image to Imagick object image list

Imagick::adaptiveThresholdImage
Imagick::addNoiseImage
The Imagick class
PHP Manual

Imagick::addImage

(PECL imagick 2.0.0)

Imagick::addImage — Adds new image to Imagick object image list

Description

bool Imagick::addImage ( Imagick $source )
Warning

This function is currently not documented; only its argument list is available.

Adds new image to Imagick object from the current position of the source object. After the operation iterator position is moved at the end of the list.

Parameters

source

The source Imagick object

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::adaptiveThresholdImage
Imagick::addNoiseImage
The Imagick class


Adds random noise to the image

Imagick::addImage
Imagick::affineTransformImage
The Imagick class
PHP Manual

Imagick::addNoiseImage

(PECL imagick 2.0.0)

Imagick::addNoiseImage — Adds random noise to the image

Description

bool Imagick::addNoiseImage ( int $noise_type [, int $channel = Imagick::CHANNEL_DEFAULT ] )
Warning

This function is currently not documented; only its argument list is available.

Adds random noise to the image.

Parameters

noise_type

The type of the noise. Refer to this list of noise constants.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Imagick::addImage
Imagick::affineTransformImage
The Imagick class


Transforms an image

Imagick::addNoiseImage
Imagick::animateImages
The Imagick class
PHP Manual

Imagick::affineTransformImage

(PECL imagick 2.0.0)

Imagick::affineTransformImage — Transforms an image

Description

bool Imagick::affineTransformImage ( ImagickDraw $matrix )
Warning

This function is currently not documented; only its argument list is available.

Transforms an image as dictated by the affine matrix.

Parameters

matrix

The affine matrix

Return Values

Returns TRUE on success.

Imagick::addNoiseImage
Imagick::animateImages
The Imagick class


Animates an image or images

Imagick::affineTransformImage
Imagick::annotateImage
The Imagick class
PHP Manual

Imagick::animateImages

(No version information available, might only be in SVN)

Imagick::animateImages — Animates an image or images

Description

bool Imagick::animateImages ( string $x_server )

This method animates the image onto a local or remote X server. This method is not available on Windows. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

x_server

X server address

Return Values

Returns TRUE on success.

See Also

  • Imagick::displayImage() - Displays an image

Imagick::affineTransformImage
Imagick::annotateImage
The Imagick class


Annotates an image with text

Imagick::animateImages
Imagick::appendImages
The Imagick class
PHP Manual

Imagick::annotateImage

(PECL imagick 2.0.0)

Imagick::annotateImage — Annotates an image with text

Description

bool Imagick::annotateImage ( ImagickDraw $draw_settings , float $x , float $y , float $angle , string $text )

Annotates an image with text.

Parameters

draw_settings

The ImagickDraw object that contains settings for drawing the text

x

Horizontal offset in pixels to the left of text

y

Vertical offset in pixels to the baseline of text

angle

The angle at which to write the text

text

The string to draw

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::annotateImage():

Annotate text on an empty image

<?php
/* Create some objects */
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(800, 75, $pixel);

/* Black text */
$draw->setFillColor('black');

/* Font properties */
$draw->setFont('Bookman-DemiItalic');
$draw->setFontSize( 30 );

/* Create text */
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox jumps over the lazy dog');

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;

?>

See Also

  • ImagickDraw::annotation() - Draws text on the image
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text

Imagick::animateImages
Imagick::appendImages
The Imagick class


Append a set of images

Imagick::annotateImage
Imagick::averageImages
The Imagick class
PHP Manual

Imagick::appendImages

(PECL imagick 2.0.0)

Imagick::appendImages — Append a set of images

Description

Imagick Imagick::appendImages ( bool $stack )

Append a set of images into one larger image.

Parameters

stack

The direction of the stack (top to bottom or bottom to top)

Return Values

Returns Imagick instance on success. Throw an ImagickException on error.

Examples

Example #1 Imagick::appendImages example

<?php

/* Create new imagick object */
$im = new Imagick();

/* create red, green and blue images */
$im->newImage(100, 50, "red");
$im->newImage(100, 50, "green");
$im->newImage(100, 50, "blue");

/* Append the images into one */
$im->resetIterator();
$combined = $im->appendImages(true);

/* Output the image */
$combined->setImageFormat("png");
header("Content-Type: image/png");
echo $combined;
?>

The above example will output something similar to:

Output of example : Imagick::appendImages()

Imagick::annotateImage
Imagick::averageImages
The Imagick class


Average a set of images

Imagick::appendImages
Imagick::blackThresholdImage
The Imagick class
PHP Manual

Imagick::averageImages

(PECL imagick 2.0.0)

Imagick::averageImages — Average a set of images

Description

Imagick Imagick::averageImages ( void )
Warning

This function is currently not documented; only its argument list is available.

Average a set of images.

Return Values

Returns a new Imagick object on success. Throw an ImagickException on error.

Imagick::appendImages
Imagick::blackThresholdImage
The Imagick class


Forces all pixels below the threshold into black

Imagick::averageImages
Imagick::blurImage
The Imagick class
PHP Manual

Imagick::blackThresholdImage

(PECL imagick 2.0.0)

Imagick::blackThresholdImage — Forces all pixels below the threshold into black

Description

bool Imagick::blackThresholdImage ( mixed $threshold )
Warning

This function is currently not documented; only its argument list is available.

Is like Imagick::thresholdImage() but forces all pixels below the threshold into black while leaving all pixels above the threshold unchanged.

Parameters

threshold

The threshold below which everything turns black

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

Imagick::averageImages
Imagick::blurImage
The Imagick class


Adds blur filter to image

Imagick::blackThresholdImage
Imagick::borderImage
The Imagick class
PHP Manual

Imagick::blurImage

(PECL imagick 2.0.0)

Imagick::blurImage — Adds blur filter to image

Description

bool Imagick::blurImage ( float $radius , float $sigma [, int $channel ] )
Warning

This function is currently not documented; only its argument list is available.

Adds blur filter to image. Optional third parameter to blur a specific channel.

Parameters

radius

Blur radius

sigma

Standard deviation

channel

The Channeltype constant. When not supplied, all channels are blurred.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::blurImage():

Blur an image, then display to the browser.

<?php

header('Content-type: image/jpeg');

$image = new Imagick('test.jpg');

$image->blurImage(5,3);
echo $image;

?>

See Also

  • Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

Imagick::blackThresholdImage
Imagick::borderImage
The Imagick class


Surrounds the image with a border

Imagick::blurImage
Imagick::charcoalImage
The Imagick class
PHP Manual

Imagick::borderImage

(PECL imagick 2.0.0)

Imagick::borderImage — Surrounds the image with a border

Description

bool Imagick::borderImage ( mixed $bordercolor , int $width , int $height )
Warning

This function is currently not documented; only its argument list is available.

Surrounds the image with a border of the color defined by the bordercolor ImagickPixel object.

Parameters

bordercolor

ImagickPixel object or a string containing the border color

width

Border width

height

Border height

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Imagick::blurImage
Imagick::charcoalImage
The Imagick class


Simulates a charcoal drawing

Imagick::borderImage
Imagick::chopImage
The Imagick class
PHP Manual

Imagick::charcoalImage

(PECL imagick 2.0.0)

Imagick::charcoalImage — Simulates a charcoal drawing

Description

bool Imagick::charcoalImage ( float $radius , float $sigma )
Warning

This function is currently not documented; only its argument list is available.

Simulates a charcoal drawing.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels

Return Values

Returns TRUE on success.

Imagick::borderImage
Imagick::chopImage
The Imagick class


Removes a region of an image and trims

Imagick::charcoalImage
Imagick::clear
The Imagick class
PHP Manual

Imagick::chopImage

(PECL imagick 2.0.0)

Imagick::chopImage — Removes a region of an image and trims

Description

bool Imagick::chopImage ( int $width , int $height , int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Removes a region of an image and collapses the image to occupy the removed portion.

Parameters

width

Width of the chopped area

height

Height of the chopped area

x

X origo of the chopped area

y

Y origo of the chopped area

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::chopImage():

Example of using Imagick::chopImage

<?php
/* Create some objects */
$image = new Imagick();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(400, 200, $pixel);

/* Chop image */
$image->chopImage(200, 200, 0, 0);

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;

?>

See Also

  • Imagick::cropImage() - Extracts a region of the image

Imagick::charcoalImage
Imagick::clear
The Imagick class


Clears all resources associated to Imagick object

Imagick::chopImage
Imagick::clipImage
The Imagick class
PHP Manual

Imagick::clear

(PECL imagick 2.0.0)

Imagick::clear — Clears all resources associated to Imagick object

Description

bool Imagick::clear ( void )
Warning

This function is currently not documented; only its argument list is available.

Clears all resources associated to Imagick object

Return Values

Returns TRUE on success.

Imagick::chopImage
Imagick::clipImage
The Imagick class


Clips along the first path from the 8BIM profile

Imagick::clear
Imagick::clipPathImage
The Imagick class
PHP Manual

Imagick::clipImage

(PECL imagick 2.0.0)

Imagick::clipImage — Clips along the first path from the 8BIM profile

Description

bool Imagick::clipImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Clips along the first path from the 8BIM profile, if present.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::clear
Imagick::clipPathImage
The Imagick class


Clips along the named paths from the 8BIM profile

Imagick::clipImage
Imagick::clone
The Imagick class
PHP Manual

Imagick::clipPathImage

(PECL imagick 2.0.0)

Imagick::clipPathImage — Clips along the named paths from the 8BIM profile

Description

bool Imagick::clipPathImage ( string $pathname , bool $inside )
Warning

This function is currently not documented; only its argument list is available.

Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. It may be a number if preceded with #, to work on a numbered path, e.g., "#1" to use the first path.

Parameters

pathname

The name of the path

inside

If TRUE later operations take effect inside clipping path. Otherwise later operations take effect outside clipping path.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::clipImage
Imagick::clone
The Imagick class


Makes an exact copy of the Imagick object

Imagick::clipPathImage
Imagick::clutImage
The Imagick class
PHP Manual

Imagick::clone

(PECL imagick 2.0.0)

Imagick::clone — Makes an exact copy of the Imagick object

Description

Imagick Imagick::clone ( void )
Warning

This function is currently not documented; only its argument list is available.

Makes an exact copy of the Imagick object.

Return Values

No value is returned.

Imagick::clipPathImage
Imagick::clutImage
The Imagick class


Replaces colors in the image

Imagick::clone
Imagick::coalesceImages
The Imagick class
PHP Manual

Imagick::clutImage

(PECL imagick 2.0.0)

Imagick::clutImage — Replaces colors in the image

Description

bool Imagick::clutImage ( Imagick $lookup_table [, float $channel = Imagick::CHANNEL_DEFAULT ] )

Replaces colors in the image from a color lookup table. Optional second parameter to replace colors in a specific channel. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

lookup_table

Imagick object containing the color lookup table

channel

The Channeltype constant. When not supplied, default channels are replaced.

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::clutImage():

Replace colors in the image from a color lookup table.

<?php
$image = new Imagick('test.jpg');
$clut = new Imagick();
$clut->newImage(1, 1, new ImagickPixel('black'));
$image->clutImage($clut);
$image->writeImage('test_out.jpg');
?>

See Also

  • Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

Imagick::clone
Imagick::coalesceImages
The Imagick class


Composites a set of images

Imagick::clutImage
Imagick::colorFloodfillImage
The Imagick class
PHP Manual

Imagick::coalesceImages

(PECL imagick 2.0.0)

Imagick::coalesceImages — Composites a set of images

Description

Imagick Imagick::coalesceImages ( void )
Warning

This function is currently not documented; only its argument list is available.

Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. Returns a new Imagick object where each image in the sequence is the same size as the first and composited with the next image in the sequence.

Return Values

Returns a new Imagick object on success. Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::clutImage
Imagick::colorFloodfillImage
The Imagick class


Changes the color value of any pixel that matches target

Imagick::coalesceImages
Imagick::colorizeImage
The Imagick class
PHP Manual

Imagick::colorFloodfillImage

(PECL imagick 2.0.0)

Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target

Description

bool Imagick::colorFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Changes the color value of any pixel that matches target and is an immediate neighbor.

Parameters

fill

ImagickPixel object containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.

bordercolor

ImagickPixel object containing the border color

x

X start position of the floodfill

y

Y start position of the floodfill

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as first and third parameter. Previous versions allow only an ImagickPixel object.

Imagick::coalesceImages
Imagick::colorizeImage
The Imagick class


Blends the fill color with the image

Imagick::colorFloodfillImage
Imagick::combineImages
The Imagick class
PHP Manual

Imagick::colorizeImage

(PECL imagick 2.0.0)

Imagick::colorizeImage — Blends the fill color with the image

Description

bool Imagick::colorizeImage ( mixed $colorize , mixed $opacity )
Warning

This function is currently not documented; only its argument list is available.

Blends the fill color with each pixel in the image.

Parameters

colorize

ImagickPixel object or a string containing the colorize color

opacity

ImagickPixel object or an float containing the opacity value. 1.0 is fully opaque and 0.0 is fully transparent.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter and a float representing the opacity value as the second parameter. Previous versions allow only an ImagickPixel objects.

Imagick::colorFloodfillImage
Imagick::combineImages
The Imagick class


Combines one or more images into a single image

Imagick::colorizeImage
Imagick::commentImage
The Imagick class
PHP Manual

Imagick::combineImages

(PECL imagick 2.0.0)

Imagick::combineImages — Combines one or more images into a single image

Description

Imagick Imagick::combineImages ( int $channelType )
Warning

This function is currently not documented; only its argument list is available.

Combines one or more images into a single image. The grayscale value of the pixels of each image in the sequence is assigned in order to the specified channels of the combined image. The typical ordering would be image 1 => Red, 2 => Green, 3 => Blue, etc.

Parameters

channelType

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::colorizeImage
Imagick::commentImage
The Imagick class


Adds a comment to your image

Imagick::combineImages
Imagick::compareImageChannels
The Imagick class
PHP Manual

Imagick::commentImage

(PECL imagick 2.0.0)

Imagick::commentImage — Adds a comment to your image

Description

bool Imagick::commentImage ( string $comment )
Warning

This function is currently not documented; only its argument list is available.

Adds a comment to your image.

Parameters

comment

The comment to add

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::commentImage():

Commenting an image and retrieving the comment:

<?php

/* Create new Imagick object */
$im = new imagick();

/* Create an empty image */
$im->newImage(100, 100, new ImagickPixel("red"));

/* Add comment to the image */
$im->commentImage("Hello World!");

/* Display the comment */
echo $im->getImageProperty("comment");

?>

Imagick::combineImages
Imagick::compareImageChannels
The Imagick class


Returns the difference in one or more images

Imagick::commentImage
Imagick::compareImageLayers
The Imagick class
PHP Manual

Imagick::compareImageChannels

(PECL imagick 2.0.0)

Imagick::compareImageChannels — Returns the difference in one or more images

Description

array Imagick::compareImageChannels ( Imagick $image , int $channelType , int $metricType )
Warning

This function is currently not documented; only its argument list is available.

Compares one or more images and returns the difference image.

Parameters

image

Imagick object containing the image to compare.

channelType

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

metricType

One of the metric type constants.

Return Values

Array consisting of new_wand and distortion.

Errors/Exceptions

Throws ImagickException on error.

Imagick::commentImage
Imagick::compareImageLayers
The Imagick class


Returns the maximum bounding region between images

Imagick::compareImageChannels
Imagick::compareImages
The Imagick class
PHP Manual

Imagick::compareImageLayers

(PECL imagick 2.0.0)

Imagick::compareImageLayers — Returns the maximum bounding region between images

Description

Imagick Imagick::compareImageLayers ( int $method )

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

method

One of the layer method constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::compareImageLayers()

Comparing image layers

<?php
/* create new imagick object */
$im = new Imagick("test.gif");

/* optimize the image layers */
$result = $im->compareImageLayers(imagick::LAYERMETHOD_COALESCE);

/* work on the $result */
?>

See Also

  • Imagick::optimizeImageLayers() - Removes repeated portions of images to optimize
  • Imagick::writeImages() - Writes an image or image sequence
  • Imagick::writeImage() - Writes an image to the specified filename

Imagick::compareImageChannels
Imagick::compareImages
The Imagick class


Compares an image to a reconstructed image

Imagick::compareImageLayers
Imagick::compositeImage
The Imagick class
PHP Manual

Imagick::compareImages

(PECL imagick 2.0.0)

Imagick::compareImages — Compares an image to a reconstructed image

Description

array Imagick::compareImages ( Imagick $compare , int $metric )
Warning

This function is currently not documented; only its argument list is available.

Returns an array containing a reconstructed image and the difference between images.

Parameters

compare

An image to compare to.

metric

Provide a valid metric type constant. Refer to this list of metric constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::compareImages():

Compare images and display the reconstructed image

<?php

$image1 = new imagick("image1.png");
$image2 = new imagick("image2.png");

$result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);
$result[0]->setImageFormat("png");

header("Content-Type: image/png");
echo $result[0];

?>

Imagick::compareImageLayers
Imagick::compositeImage
The Imagick class


Composite one image onto another

Imagick::compareImages
Imagick::__construct
The Imagick class
PHP Manual

Imagick::compositeImage

(PECL imagick 2.0.0)

Imagick::compositeImage — Composite one image onto another

Description

bool Imagick::compositeImage ( Imagick $composite_object , int $composite , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Composite one image onto another at the specified offset.

Parameters

composite_object

Imagick object which holds the composite image

compose

Composite operator. See Composite Operator Constants

x

The column offset of the composited image

y

The row offset of the composited image

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Imagick::compareImages
Imagick::__construct
The Imagick class


The Imagick constructor

Imagick::compositeImage
Imagick::contrastImage
The Imagick class
PHP Manual

Imagick::__construct

(PECL imagick 2.0.0)

Imagick::__construct — The Imagick constructor

Description

Imagick Imagick::__construct ([ mixed $files ] )
Warning

This function is currently not documented; only its argument list is available.

The Imagick constructor

Parameters

files

The path to an image to load or array of paths

Return Values

Returns a new Imagick object on success. Throw an ImagickException on error.

Imagick::compositeImage
Imagick::contrastImage
The Imagick class


Change the contrast of the image

Imagick::__construct
Imagick::contrastStretchImage
The Imagick class
PHP Manual

Imagick::contrastImage

(PECL imagick 2.0.0)

Imagick::contrastImage — Change the contrast of the image

Description

bool Imagick::contrastImage ( bool $sharpen )
Warning

This function is currently not documented; only its argument list is available.

Enhances the intensity differences between the lighter and darker elements of the image. Set sharpen to a value other than 0 to increase the image contrast otherwise the contrast is reduced.

Parameters

sharpen

The sharpen value

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::__construct
Imagick::contrastStretchImage
The Imagick class


Enhances the contrast of a color image

Imagick::contrastImage
Imagick::convolveImage
The Imagick class
PHP Manual

Imagick::contrastStretchImage

(PECL imagick 2.0.0)

Imagick::contrastStretchImage — Enhances the contrast of a color image

Description

bool Imagick::contrastStretchImage ( float $black_point , float $white_point [, int $channel = Imagick::CHANNEL_ALL ] )

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

black_point

The black point.

white_point

The white point.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Imagick::CHANNEL_ALL. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Imagick::contrastImage
Imagick::convolveImage
The Imagick class


Applies a custom convolution kernel to the image

Imagick::contrastStretchImage
Imagick::cropImage
The Imagick class
PHP Manual

Imagick::convolveImage

(PECL imagick 2.0.0)

Imagick::convolveImage — Applies a custom convolution kernel to the image

Description

bool Imagick::convolveImage ( array $kernel [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Applies a custom convolution kernel to the image.

Parameters

kernel

The convolution kernel

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::contrastStretchImage
Imagick::cropImage
The Imagick class


Extracts a region of the image

Imagick::convolveImage
Imagick::cropThumbnailImage
The Imagick class
PHP Manual

Imagick::cropImage

(PECL imagick 2.0.0)

Imagick::cropImage — Extracts a region of the image

Description

bool Imagick::cropImage ( int $width , int $height , int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Extracts a region of the image.

Parameters

width

The width of the crop

height

The height of the crop

x

The X coordinate of the cropped region's top left corner

y

The Y coordinate of the cropped region's top left corner

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::convolveImage
Imagick::cropThumbnailImage
The Imagick class


Creates a crop thumbnail

Imagick::cropImage
Imagick::current
The Imagick class
PHP Manual

Imagick::cropThumbnailImage

(PECL imagick 2.0.0)

Imagick::cropThumbnailImage — Creates a crop thumbnail

Description

bool Imagick::cropThumbnailImage ( int $width , int $height )
Warning

This function is currently not documented; only its argument list is available.

Creates a fixed size thumbnail by first scaling the image up or down and cropping a specified area from the center.

Parameters

width

The width of the thumbnail

height

The Height of the thumbnail

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::cropImage
Imagick::current
The Imagick class


Returns a reference to the current Imagick object

Imagick::cropThumbnailImage
Imagick::cycleColormapImage
The Imagick class
PHP Manual

Imagick::current

(PECL imagick 2.0.0)

Imagick::current — Returns a reference to the current Imagick object

Description

Imagick Imagick::current ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns reference to the current imagick object with image pointer at the correct sequence.

Return Values

Returns self on success. Throw an ImagickException on error.

Imagick::cropThumbnailImage
Imagick::cycleColormapImage
The Imagick class


Displaces an image's colormap

Imagick::current
Imagick::decipherImage
The Imagick class
PHP Manual

Imagick::cycleColormapImage

(PECL imagick 2.0.0)

Imagick::cycleColormapImage — Displaces an image's colormap

Description

bool Imagick::cycleColormapImage ( int $displace )
Warning

This function is currently not documented; only its argument list is available.

Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.

Parameters

displace

The amount to displace the colormap.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::current
Imagick::decipherImage
The Imagick class


Deciphers an image

Imagick::cycleColormapImage
Imagick::deconstructImages
The Imagick class
PHP Manual

Imagick::decipherImage

(No version information available, might only be in SVN)

Imagick::decipherImage — Deciphers an image

Description

bool Imagick::decipherImage ( string $passphrase )

Deciphers image that has been enciphered before. The image must be enciphered using Imagick::encipherImage(). This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer.

Parameters

passphrase

The passphrase

Return Values

Returns TRUE on success.

See Also

  • Imagick::encipherImage() - Enciphers an image

Imagick::cycleColormapImage
Imagick::deconstructImages
The Imagick class


Returns certain pixel differences between images

Imagick::decipherImage
Imagick::deskewImage
The Imagick class
PHP Manual

Imagick::deconstructImages

(PECL imagick 2.0.0)

Imagick::deconstructImages — Returns certain pixel differences between images

Description

bool Imagick::deconstructImages ( void )
Warning

This function is currently not documented; only its argument list is available.

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::decipherImage
Imagick::deskewImage
The Imagick class


Reduces the speckle noise in an image

Imagick::deskewImage
Imagick::destroy
The Imagick class
PHP Manual

Imagick::despeckleImage

(PECL imagick 2.0.0)

Imagick::despeckleImage — Reduces the speckle noise in an image

Description

bool Imagick::despeckleImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Reduces the speckle noise in an image while preserving the edges of the original image.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::deskewImage
Imagick::destroy
The Imagick class


Destroys the Imagick object

Imagick::despeckleImage
Imagick::displayImage
The Imagick class
PHP Manual

Imagick::destroy

(PECL imagick 2.0.0)

Imagick::destroy — Destroys the Imagick object

Description

bool Imagick::destroy ( void )
Warning

This function is currently not documented; only its argument list is available.

Destroys the Imagick object and frees all resources associated with it.

Return Values

Returns TRUE on success.

Imagick::despeckleImage
Imagick::displayImage
The Imagick class


Displays an image

Imagick::destroy
Imagick::displayImages
The Imagick class
PHP Manual

Imagick::displayImage

(PECL imagick 2.0.0)

Imagick::displayImage — Displays an image

Description

bool Imagick::displayImage ( string $servername )
Warning

This function is currently not documented; only its argument list is available.

This method displays an image on a X server.

Parameters

servername

The X server name

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::destroy
Imagick::displayImages
The Imagick class


Displays an image or image sequence

Imagick::displayImage
Imagick::distortImage
The Imagick class
PHP Manual

Imagick::displayImages

(PECL imagick 2.0.0)

Imagick::displayImages — Displays an image or image sequence

Description

bool Imagick::displayImages ( string $servername )
Warning

This function is currently not documented; only its argument list is available.

Displays an image or image sequence on a X server.

Parameters

servername

The X server name

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::displayImage
Imagick::distortImage
The Imagick class


Distorts an image using various distortion methods

Imagick::displayImages
Imagick::drawImage
The Imagick class
PHP Manual

Imagick::distortImage

(PECL imagick 2.0.1)

Imagick::distortImage — Distorts an image using various distortion methods

Description

bool Imagick::distortImage ( int $method , array $arguments , bool $bestfit )

Distorts an image using various distortion methods, by mapping color lookups of the source image to a new destination image usually of the same size as the source image, unless 'bestfit' is set to TRUE.

If 'bestfit' is enabled, and distortion allows it, the destination image is adjusted to ensure the whole source 'image' will just fit within the final destination image, which will be sized and offset accordingly. Also in many cases the virtual offset of the source image will be taken into account in the mapping.

This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

method

The method of image distortion. See distortion constants

arguments

The arguments for this distortion method

bestfit

Attempt to resize destination to fit distorted source

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::distortImage():

Distort an image and display to the browser.

<?php
/* Create new object */
$im = new Imagick();

/* Create new checkerboard pattern */
$im->newPseudoImage(100, 100, "pattern:checkerboard");

/* Set the image format to png */
$im->setImageFormat('png');

/* Fill new visible areas with transparent */
$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);

/* Activate matte */
$im->setImageMatte(true);

/* Control points for the distortion */
$controlPoints = array( 10, 10,
                        10, 5,

                        10, $im->getImageHeight() - 20,
                        10, $im->getImageHeight() - 5,

                        $im->getImageWidth() - 10, 10,
                        $im->getImageWidth() - 10, 20,

                        $im->getImageWidth() - 10, $im->getImageHeight() - 10,
                        $im->getImageWidth() - 10, $im->getImageHeight() - 30);

/* Perform the distortion */
$im->distortImage(Imagick::DISTORTION_PERSPECTIVE, $controlPoints, true);

/* Ouput the image */
header("Content-Type: image/png");
echo $im;
?>

The above example will output something similar to:

Output of example : Using Imagick::distortImage()

See Also

  • Imagick::blurImage() - Adds blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

Imagick::displayImages
Imagick::drawImage
The Imagick class


Renders the ImagickDraw object on the current image

Imagick::distortImage
Imagick::edgeImage
The Imagick class
PHP Manual

Imagick::drawImage

(PECL imagick 2.0.0)

Imagick::drawImage — Renders the ImagickDraw object on the current image

Description

bool Imagick::drawImage ( ImagickDraw $draw )
Warning

This function is currently not documented; only its argument list is available.

Renders the ImagickDraw object on the current image.

Parameters

draw

The drawing operations to render on the image.

Return Values

Returns TRUE on success.

Imagick::distortImage
Imagick::edgeImage
The Imagick class


Enhance edges within the image

Imagick::drawImage
Imagick::embossImage
The Imagick class
PHP Manual

Imagick::edgeImage

(PECL imagick 2.0.0)

Imagick::edgeImage — Enhance edges within the image

Description

bool Imagick::edgeImage ( float $radius )
Warning

This function is currently not documented; only its argument list is available.

Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected.

Parameters

radius

The radius of the operation.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::drawImage
Imagick::embossImage
The Imagick class


Returns a grayscale image with a three-dimensional effect

Imagick::edgeImage
Imagick::encipherImage
The Imagick class
PHP Manual

Imagick::embossImage

(PECL imagick 2.0.0)

Imagick::embossImage — Returns a grayscale image with a three-dimensional effect

Description

bool Imagick::embossImage ( float $radius , float $sigma )
Warning

This function is currently not documented; only its argument list is available.

Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you.

Parameters

radius

The radius of the effect

sigma

The sigma of the effect

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::edgeImage
Imagick::encipherImage
The Imagick class


Enciphers an image

Imagick::embossImage
Imagick::enhanceImage
The Imagick class
PHP Manual

Imagick::encipherImage

(No version information available, might only be in SVN)

Imagick::encipherImage — Enciphers an image

Description

bool Imagick::encipherImage ( string $passphrase )

Converts plain pixels to enciphered pixels. The image is not readable until it has been deciphered using Imagick::decipherImage() This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer.

Parameters

passphrase

The passphrase

Return Values

Returns TRUE on success.

See Also

  • Imagick::decipherImage() - Deciphers an image

Imagick::embossImage
Imagick::enhanceImage
The Imagick class


Improves the quality of a noisy image

Imagick::encipherImage
Imagick::equalizeImage
The Imagick class
PHP Manual

Imagick::enhanceImage

(PECL imagick 2.0.0)

Imagick::enhanceImage — Improves the quality of a noisy image

Description

bool Imagick::enhanceImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Applies a digital filter that improves the quality of a noisy image.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::encipherImage
Imagick::equalizeImage
The Imagick class


Equalizes the image histogram

Imagick::enhanceImage
Imagick::evaluateImage
The Imagick class
PHP Manual

Imagick::equalizeImage

(PECL imagick 2.0.0)

Imagick::equalizeImage — Equalizes the image histogram

Description

bool Imagick::equalizeImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Equalizes the image histogram.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::enhanceImage
Imagick::evaluateImage
The Imagick class


Applies an expression to an image

Imagick::equalizeImage
Imagick::exportImagePixels
The Imagick class
PHP Manual

Imagick::evaluateImage

(PECL imagick 2.0.0)

Imagick::evaluateImage — Applies an expression to an image

Description

bool Imagick::evaluateImage ( int $op , float $constant [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Applys an arithmetic, relational, or logical expression to an image. Use these operators to lighten or darken an image, to increase or decrease contrast in an image, or to produce the "negative" of an image.

Parameters

op

The operator

constant

The value of the operator

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::equalizeImage
Imagick::exportImagePixels
The Imagick class


Set image size

Imagick::exportImagePixels
Imagick::flattenImages
The Imagick class
PHP Manual

Imagick::extentImage

(No version information available, might only be in SVN)

Imagick::extentImage — Set image size

Description

bool Imagick::extentImage ( int $width , int $height , int $x , int $y )

Comfortability method for setting image size. The method sets the image size and allows setting x,y coordinates where the new area begins. This method is available if Imagick has been compiled against ImageMagick version 6.3.1 or newer.

Parameters

width

The new width

height

The new height

x

X position for the new size

y

Y position for the new size

Return Values

Returns TRUE on success.

See Also

  • Imagick::resizeImage() - Scales an image
  • Imagick::thumbnailImage() - Changes the size of an image
  • Imagick::cropImage() - Extracts a region of the image

Imagick::exportImagePixels
Imagick::flattenImages
The Imagick class


Merges a sequence of images

Imagick::extentImage
Imagick::flipImage
The Imagick class
PHP Manual

Imagick::flattenImages

(PECL imagick 2.0.0)

Imagick::flattenImages — Merges a sequence of images

Description

Imagick Imagick::flattenImages ( void )
Warning

This function is currently not documented; only its argument list is available.

Merges a sequence of images. This is useful for combining Photoshop layers into a single image.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::extentImage
Imagick::flipImage
The Imagick class


Creates a vertical mirror image

Imagick::flattenImages
Imagick::floodFillPaintImage
The Imagick class
PHP Manual

Imagick::flipImage

(PECL imagick 2.0.0)

Imagick::flipImage — Creates a vertical mirror image

Description

bool Imagick::flipImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::flattenImages
Imagick::floodFillPaintImage
The Imagick class


Changes the color value of any pixel that matches target

Imagick::flipImage
Imagick::flopImage
The Imagick class
PHP Manual

Imagick::floodFillPaintImage

(No version information available, might only be in SVN)

Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target

Description

bool Imagick::floodFillPaintImage ( mixed $fill , float $fuzz , mixed $target , int $x , int $y , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Changes the color value of any pixel that matches target and is an immediate neighbor. This method is a replacement for deprecated Imagick::paintFloodFillImage(). This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

Parameters

fill

ImagickPixel object or a string containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

target

ImagickPixel object or a string containing the target color to paint

x

X start position of the floodfill

y

Y start position of the floodfill

invert

If TRUE paints any pixel that does not match the target color.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Examples

Example #1 Imagick::floodfillPaintImage example

<?php

/* Create new imagick object */
$im = new Imagick();

/* create red, green and blue images */
$im->newImage(100, 50, "red");
$im->newImage(100, 50, "green");
$im->newImage(100, 50, "blue");

/* Append the images into one */
$im->resetIterator();
$combined = $im->appendImages(true);

/* Save the intermediate image for comparison */
$combined->writeImage("floodfillpaint_intermediate.png");

/* The target pixel to paint */
$x = 1;
$y = 1;

/* Get the color we are painting */
$target = $combined->getImagePixelColor($x, $y);

/* Paints pixel in position 1,1 black and all neighboring
   pixels that match the target color */
$combined->floodfillPaintImage("black", 1, $target, $x, $y, false);

/* Save the result */
$combined->writeImage("floodfillpaint_result.png");
?>

The above example will output something similar to:

Output of example : Imagick::floodfillPaintImage()
Output of example : Imagick::floodfillPaintImage()

Imagick::flipImage
Imagick::flopImage
The Imagick class


Creates a horizontal mirror image

Imagick::floodFillPaintImage
Imagick::frameImage
The Imagick class
PHP Manual

Imagick::flopImage

(PECL imagick 2.0.0)

Imagick::flopImage — Creates a horizontal mirror image

Description

bool Imagick::flopImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::floodFillPaintImage
Imagick::frameImage
The Imagick class


Adds a simulated three-dimensional border

Imagick::flopImage
Imagick::functionImage
The Imagick class
PHP Manual

Imagick::frameImage

(PECL imagick 2.0.0)

Imagick::frameImage — Adds a simulated three-dimensional border

Description

bool Imagick::frameImage ( mixed $matte_color , int $width , int $height , int $inner_bevel , int $outer_bevel )
Warning

This function is currently not documented; only its argument list is available.

Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.

Parameters

matte_color

ImagickPixel object or a string representing the matte color

width

The width of the border

height

The height of the border

inner_bevel

The inner bevel width

outer_bevel

The outer bevel width

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Imagick::flopImage
Imagick::functionImage
The Imagick class


Evaluate expression for each pixel in the image

Imagick::functionImage
Imagick::gammaImage
The Imagick class
PHP Manual

Imagick::fxImage

(PECL imagick 2.0.0)

Imagick::fxImage — Evaluate expression for each pixel in the image

Description

Imagick Imagick::fxImage ( string $expression [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Evaluate expression for each pixel in the image. Consult » The Fx Special Effects Image Operator for more information.

Parameters

expression

The expression.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::functionImage
Imagick::gammaImage
The Imagick class


Gamma-corrects an image

Imagick::fxImage
Imagick::gaussianBlurImage
The Imagick class
PHP Manual

Imagick::gammaImage

(PECL imagick 2.0.0)

Imagick::gammaImage — Gamma-corrects an image

Description

bool Imagick::gammaImage ( float $gamma [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Gamma-corrects an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.

Parameters

gamma

The amount of gamma-correction.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::fxImage
Imagick::gaussianBlurImage
The Imagick class


Blurs an image

Imagick::gammaImage
Imagick::getCompression
The Imagick class
PHP Manual

Imagick::gaussianBlurImage

(PECL imagick 2.0.0)

Imagick::gaussianBlurImage — Blurs an image

Description

bool Imagick::gaussianBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Blurs an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and selects a suitable radius for you.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::gammaImage
Imagick::getCompression
The Imagick class


Gets the object compression type

Imagick::gaussianBlurImage
Imagick::getCompressionQuality
The Imagick class
PHP Manual

Imagick::getCompression

(PECL imagick 2.0.0)

Imagick::getCompression — Gets the object compression type

Description

int Imagick::getCompression ( void )

Gets the object compression type.

Return Values

Returns the compression constant

Imagick::gaussianBlurImage
Imagick::getCompressionQuality
The Imagick class


Gets the object compression quality

Imagick::getCompression
Imagick::getCopyright
The Imagick class
PHP Manual

Imagick::getCompressionQuality

(PECL imagick 2.0.0)

Imagick::getCompressionQuality — Gets the object compression quality

Description

int Imagick::getCompressionQuality ( void )

Gets the object compression quality.

Return Values

Returns integer describing the compression quality

Imagick::getCompression
Imagick::getCopyright
The Imagick class


Returns the ImageMagick API copyright as a string

Imagick::getCompressionQuality
Imagick::getFilename
The Imagick class
PHP Manual

Imagick::getCopyright

(PECL imagick 2.0.0)

Imagick::getCopyright — Returns the ImageMagick API copyright as a string

Description

string Imagick::getCopyright ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the ImageMagick API copyright as a string.

Return Values

Returns a string containing the copyright notice of Imagemagick and Magickwand C API.

Imagick::getCompressionQuality
Imagick::getFilename
The Imagick class


The filename associated with an image sequence

Imagick::getCopyright
Imagick::getFont
The Imagick class
PHP Manual

Imagick::getFilename

(PECL imagick 2.0.0)

Imagick::getFilename — The filename associated with an image sequence

Description

string Imagick::getFilename ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the filename associated with an image sequence.

Return Values

Returns a string on success. Throw an ImagickException on error.

Imagick::getCopyright
Imagick::getFont
The Imagick class


Gets font

Imagick::getFilename
Imagick::getFormat
The Imagick class
PHP Manual

Imagick::getFont

(PECL imagick 2.1.0)

Imagick::getFont — Gets font

Description

string Imagick::getFont ( void )

Returns the objects font property. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Return Values

Returns the string containing the font name or FALSE if not font is set.

See Also

  • Imagick::setFont() - Sets font
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
  • ImagickDraw::getFont() - Returns the font

Imagick::getFilename
Imagick::getFormat
The Imagick class


Returns the format of the Imagick object

Imagick::getFont
Imagick::getGravity
The Imagick class
PHP Manual

Imagick::getFormat

(PECL imagick 2.0.0)

Imagick::getFormat — Returns the format of the Imagick object

Description

string Imagick::getFormat ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the format of the Imagick object.

Return Values

Returns the format of the image. Throw an ImagickException on error.

Imagick::getFont
Imagick::getGravity
The Imagick class


Gets the gravity

Imagick::getFormat
Imagick::getHomeURL
The Imagick class
PHP Manual

Imagick::getGravity

(No version information available, might only be in SVN)

Imagick::getGravity — Gets the gravity

Description

bool Imagick::getGravity ( void )

Gets the global gravity property for the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

Return Values

Returns the gravity property. Refer to the list of gravity constants.

Imagick::getFormat
Imagick::getHomeURL
The Imagick class


Returns the ImageMagick home URL

Imagick::getGravity
Imagick::getImage
The Imagick class
PHP Manual

Imagick::getHomeURL

(PECL imagick 2.0.0)

Imagick::getHomeURL — Returns the ImageMagick home URL

Description

string Imagick::getHomeURL ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the ImageMagick home URL.

Return Values

Returns a link to the imagemagick homepage.

Imagick::getGravity
Imagick::getImage
The Imagick class


Returns a new Imagick object

Imagick::getHomeURL
Imagick::getImageAlphaChannel
The Imagick class
PHP Manual

Imagick::getImage

(PECL imagick 2.0.0)

Imagick::getImage — Returns a new Imagick object

Description

Imagick Imagick::getImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns a new Imagick object with the current image sequence.

Return Values

Returns a new Imagick object with the current image sequence. Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getHomeURL
Imagick::getImageAlphaChannel
The Imagick class


Gets the image alpha channel

Imagick::getImage
Imagick::getImageBackgroundColor
The Imagick class
PHP Manual

Imagick::getImageAlphaChannel

(No version information available, might only be in SVN)

Imagick::getImageAlphaChannel — Gets the image alpha channel

Description

int Imagick::getImageAlphaChannel ( void )

Gets the image alpha channel value. The returned value is one of the alpha channel constants. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

Return Values

Returns a constant defining the current alpha channel value. Refer to this list of alpha channel constants.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImage
Imagick::getImageBackgroundColor
The Imagick class


Returns the image background color

Imagick::getImageAlphaChannel
Imagick::getImageBlob
The Imagick class
PHP Manual

Imagick::getImageBackgroundColor

(PECL imagick 2.0.0)

Imagick::getImageBackgroundColor — Returns the image background color

Description

ImagickPixel Imagick::getImageBackgroundColor ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the image background color.

Return Values

Returns an ImagickPixel set to the background color of the image. Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageAlphaChannel
Imagick::getImageBlob
The Imagick class


Returns the image sequence as a blob

Imagick::getImageBackgroundColor
Imagick::getImageBluePrimary
The Imagick class
PHP Manual

Imagick::getImageBlob

(PECL imagick 2.0.0)

Imagick::getImageBlob — Returns the image sequence as a blob

Description

string Imagick::getImageBlob ( void )
Warning

This function is currently not documented; only its argument list is available.

Implements direct to memory image formats. It returns the image sequence as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().

Return Values

Returns a string containing the image. Throw an ImagickException on error.

Imagick::getImageBackgroundColor
Imagick::getImageBluePrimary
The Imagick class


Returns the chromaticy blue primary point

Imagick::getImageBlob
Imagick::getImageBorderColor
The Imagick class
PHP Manual

Imagick::getImageBluePrimary

(PECL imagick 2.0.0)

Imagick::getImageBluePrimary — Returns the chromaticy blue primary point

Description

array Imagick::getImageBluePrimary ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Returns the chromaticity blue primary point for the image.

Parameters

x

The chromaticity blue primary x-point.

y

The chromaticity blue primary y-point.

Return Values

Array consisting of "x" and "y" coordinates of point.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageBlob
Imagick::getImageBorderColor
The Imagick class


Returns the image border color

Imagick::getImageBluePrimary
Imagick::getImageChannelDepth
The Imagick class
PHP Manual

Imagick::getImageBorderColor

(PECL imagick 2.0.0)

Imagick::getImageBorderColor — Returns the image border color

Description

ImagickPixel Imagick::getImageBorderColor ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the image border color.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageBluePrimary
Imagick::getImageChannelDepth
The Imagick class


Gets the depth for a particular image channel

Imagick::getImageBorderColor
Imagick::getImageChannelDistortion
The Imagick class
PHP Manual

Imagick::getImageChannelDepth

(PECL imagick 2.0.0)

Imagick::getImageChannelDepth — Gets the depth for a particular image channel

Description

int Imagick::getImageChannelDepth ( int $channel )

Gets the depth for a particular image channel.

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Imagick::getImageBorderColor
Imagick::getImageChannelDistortion
The Imagick class


Compares image channels of an image to a reconstructed image

Imagick::getImageChannelDepth
Imagick::getImageChannelDistortions
The Imagick class
PHP Manual

Imagick::getImageChannelDistortion

(PECL imagick 2.0.0)

Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image

Description

float Imagick::getImageChannelDistortion ( Imagick $reference , int $channel , int $metric )
Warning

This function is currently not documented; only its argument list is available.

Compares one or more image channels of an image to a reconstructed image and returns the specified distortion metric.

Parameters

reference

Imagick object to compare to.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

metric

One of the metric type constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageChannelDepth
Imagick::getImageChannelDistortions
The Imagick class


Gets channel distortions

Imagick::getImageChannelDistortion
Imagick::getImageChannelExtrema
The Imagick class
PHP Manual

Imagick::getImageChannelDistortions

(No version information available, might only be in SVN)

Imagick::getImageChannelDistortions — Gets channel distortions

Description

double Imagick::getImageChannelDistortions ( Imagick $reference , int $metric , int $channel )

Compares one or more image channels of an image to a reconstructed image and returns the specified distortion metrics This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer.

Parameters

reference

Imagick object containing the reference image

metric

Refer to this list of metric type constants.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns a double describing the channel distortion.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageChannelDistortion
Imagick::getImageChannelExtrema
The Imagick class


Gets the extrema for one or more image channels

Imagick::getImageChannelDistortions
Imagick::getImageChannelKurtosis
The Imagick class
PHP Manual

Imagick::getImageChannelExtrema

(PECL imagick 2.0.0)

Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels

Description

array Imagick::getImageChannelExtrema ( int $channel )
Warning

This function is currently not documented; only its argument list is available.

Gets the extrema for one or more image channels. Return value is an associative array with the keys "minima" and "maxima".

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageChannelDistortions
Imagick::getImageChannelKurtosis
The Imagick class


Gets the mean and standard deviation

Imagick::getImageChannelKurtosis
Imagick::getImageChannelRange
The Imagick class
PHP Manual

Imagick::getImageChannelMean

(PECL imagick 2.0.0)

Imagick::getImageChannelMean — Gets the mean and standard deviation

Description

array Imagick::getImageChannelMean ( int $channel )
Warning

This function is currently not documented; only its argument list is available.

Gets the mean and standard deviation of one or more image channels. Return value is an associative array with the keys "mean" and "standardDeviation".

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageChannelKurtosis
Imagick::getImageChannelRange
The Imagick class


Gets channel range

Imagick::getImageChannelMean
Imagick::getImageChannelStatistics
The Imagick class
PHP Manual

Imagick::getImageChannelRange

(PECL imagick 2.2.1)

Imagick::getImageChannelRange — Gets channel range

Description

bool Imagick::getImageChannelRange ( int $channel )

Gets the range for one or more image channels. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns an array containing minima and maxima values of the channel(s).

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageChannelMean
Imagick::getImageChannelStatistics
The Imagick class


Returns statistics for each channel in the image

Imagick::getImageChannelRange
Imagick::getImageClipMask
The Imagick class
PHP Manual

Imagick::getImageChannelStatistics

(PECL imagick 2.0.0)

Imagick::getImageChannelStatistics — Returns statistics for each channel in the image

Description

array Imagick::getImageChannelStatistics ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns statistics for each channel in the image. The statistics include the channel depth, its minima and maxima, the mean, and the standard deviation. You can access the red channel mean, for example, like this:

Return Values

Returns TRUE on success.

Imagick::getImageChannelRange
Imagick::getImageClipMask
The Imagick class


Gets image clip mask

Imagick::getImageChannelStatistics
Imagick::getImageColormapColor
The Imagick class
PHP Manual

Imagick::getImageClipMask

(No version information available, might only be in SVN)

Imagick::getImageClipMask — Gets image clip mask

Description

Imagick Imagick::getImageClipMask ( void )

Returns the image clip mask. The clip mask is an Imagick object containing the clip mask. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Return Values

Returns an Imagick object containing the clip mask. Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageChannelStatistics
Imagick::getImageColormapColor
The Imagick class


Returns the color of the specified colormap index

Imagick::getImageClipMask
Imagick::getImageColors
The Imagick class
PHP Manual

Imagick::getImageColormapColor

(PECL imagick 2.0.0)

Imagick::getImageColormapColor — Returns the color of the specified colormap index

Description

ImagickPixel Imagick::getImageColormapColor ( int $index )
Warning

This function is currently not documented; only its argument list is available.

Returns the color of the specified colormap index.

Parameters

index

The offset into the image colormap.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageClipMask
Imagick::getImageColors
The Imagick class


Gets the number of unique colors in the image

Imagick::getImageColormapColor
Imagick::getImageColorspace
The Imagick class
PHP Manual

Imagick::getImageColors

(PECL imagick 2.0.0)

Imagick::getImageColors — Gets the number of unique colors in the image

Description

int Imagick::getImageColors ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the number of unique colors in the image.

Return Values

Returns TRUE on success.

Imagick::getImageColormapColor
Imagick::getImageColorspace
The Imagick class


Gets the image colorspace

Imagick::getImageColors
Imagick::getImageCompose
The Imagick class
PHP Manual

Imagick::getImageColorspace

(PECL imagick 2.0.0)

Imagick::getImageColorspace — Gets the image colorspace

Description

int Imagick::getImageColorspace ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image colorspace.

Return Values

Returns TRUE on success.

Imagick::getImageColors
Imagick::getImageCompose
The Imagick class


Returns the composite operator associated with the image

Imagick::getImageColorspace
Imagick::getImageCompression
The Imagick class
PHP Manual

Imagick::getImageCompose

(PECL imagick 2.0.0)

Imagick::getImageCompose — Returns the composite operator associated with the image

Description

int Imagick::getImageCompose ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the composite operator associated with the image.

Return Values

Returns TRUE on success.

Imagick::getImageColorspace
Imagick::getImageCompression
The Imagick class


Gets the current image's compression type

Imagick::getImageCompose
Imagick::getImageCompressionQuality
The Imagick class
PHP Manual

Imagick::getImageCompression

(PECL imagick 2.2.2)

Imagick::getImageCompression — Gets the current image's compression type

Description

int Imagick::getImageCompression ( void )

Gets the current image's compression type.

Return Values

Returns the compression constant

Imagick::getImageCompose
Imagick::getImageCompressionQuality
The Imagick class


Gets the current image's compression quality

Imagick::getImageCompression
Imagick::getImageDelay
The Imagick class
PHP Manual

Imagick::getImageCompressionQuality

(PECL imagick 2.2.2)

Imagick::getImageCompressionQuality — Gets the current image's compression quality

Description

int Imagick::getCompressionQuality ( void )

Gets the current image's compression quality

Return Values

Returns integer describing the images compression quality

Imagick::getImageCompression
Imagick::getImageDelay
The Imagick class


Gets the image delay

Imagick::getImageCompressionQuality
Imagick::getImageDepth
The Imagick class
PHP Manual

Imagick::getImageDelay

(PECL imagick 2.0.0)

Imagick::getImageDelay — Gets the image delay

Description

int Imagick::getImageDelay ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image delay.

Return Values

Returns the image delay. Throw an ImagickException on error.

Imagick::getImageCompressionQuality
Imagick::getImageDepth
The Imagick class


Gets the image depth

Imagick::getImageDelay
Imagick::getImageDispose
The Imagick class
PHP Manual

Imagick::getImageDepth

(PECL imagick 0.9.1-0.9.9)

Imagick::getImageDepth — Gets the image depth

Description

int Imagick::getImageDepth ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image depth.

Return Values

The image depth.

Imagick::getImageDelay
Imagick::getImageDispose
The Imagick class


Gets the image disposal method

Imagick::getImageDepth
Imagick::getImageDistortion
The Imagick class
PHP Manual

Imagick::getImageDispose

(PECL imagick 2.0.0)

Imagick::getImageDispose — Gets the image disposal method

Description

int Imagick::getImageDispose ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image disposal method.

Return Values

Returns the dispose method on success. Throw an ImagickException on error.

Imagick::getImageDepth
Imagick::getImageDistortion
The Imagick class


Compares an image to a reconstructed image

Imagick::getImageDispose
Imagick::getImageExtrema
The Imagick class
PHP Manual

Imagick::getImageDistortion

(PECL imagick 2.0.0)

Imagick::getImageDistortion — Compares an image to a reconstructed image

Description

float Imagick::getImageDistortion ( MagickWand $reference , int $metric )
Warning

This function is currently not documented; only its argument list is available.

Compares an image to a reconstructed image and returns the specified distortion metric.

Parameters

reference

Imagick object to compare to.

metric

One of the metric type constants.

Return Values

Returns the distortion metric used on the image (or the best guess thereof). Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageDispose
Imagick::getImageExtrema
The Imagick class


Gets the extrema for the image

Imagick::getImageDistortion
Imagick::getImageFilename
The Imagick class
PHP Manual

Imagick::getImageExtrema

(PECL imagick 2.0.0)

Imagick::getImageExtrema — Gets the extrema for the image

Description

array Imagick::getImageExtrema ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the extrema for the image. Returns an associative array with the keys "min" and "max".

Return Values

Returns an associative array with the keys "min" and "max". Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageDistortion
Imagick::getImageFilename
The Imagick class


Returns the filename of a particular image in a sequence

Imagick::getImageExtrema
Imagick::getImageFormat
The Imagick class
PHP Manual

Imagick::getImageFilename

(PECL imagick 2.0.0)

Imagick::getImageFilename — Returns the filename of a particular image in a sequence

Description

string Imagick::getImageFilename ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the filename of a particular image in a sequence.

Return Values

Returns a string with the filename of the image. Throw an ImagickException on error.

Imagick::getImageExtrema
Imagick::getImageFormat
The Imagick class


Returns the format of a particular image in a sequence

Imagick::getImageFilename
Imagick::getImageGamma
The Imagick class
PHP Manual

Imagick::getImageFormat

(PECL imagick 2.0.0)

Imagick::getImageFormat — Returns the format of a particular image in a sequence

Description

string Imagick::getImageFormat ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the format of a particular image in a sequence.

Return Values

Returns a string containing the image format on success. Throw an ImagickException on error.

Imagick::getImageFilename
Imagick::getImageGamma
The Imagick class


Gets the image gamma

Imagick::getImageFormat
Imagick::getImageGeometry
The Imagick class
PHP Manual

Imagick::getImageGamma

(PECL imagick 2.0.0)

Imagick::getImageGamma — Gets the image gamma

Description

float Imagick::getImageGamma ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image gamma.

Return Values

Returns the image gamma on success. Throw an ImagickException on error.

Imagick::getImageFormat
Imagick::getImageGeometry
The Imagick class


Gets the width and height as an associative array

Imagick::getImageGamma
Imagick::getImageGravity
The Imagick class
PHP Manual

Imagick::getImageGeometry

(PECL imagick 2.0.0)

Imagick::getImageGeometry — Gets the width and height as an associative array

Description

array Imagick::getImageGeometry ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the width and height as an associative array.

Return Values

Returns an array with the width/height of the image. Throw an ImagickException on error.

Imagick::getImageGamma
Imagick::getImageGravity
The Imagick class


Gets the image gravity

Imagick::getImageGeometry
Imagick::getImageGreenPrimary
The Imagick class
PHP Manual

Imagick::getImageGravity

(No version information available, might only be in SVN)

Imagick::getImageGravity — Gets the image gravity

Description

bool Imagick::getImageGravity ( void )

Gets the current gravity value of the image. Unlike Imagick::getGravity(), this method returns the gravity defined for the current image sequence. This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer.

Return Values

Returns the images gravity property. Refer to the list of gravity constants.

Imagick::getImageGeometry
Imagick::getImageGreenPrimary
The Imagick class


Returns the chromaticy green primary point

Imagick::getImageGravity
Imagick::getImageHeight
The Imagick class
PHP Manual

Imagick::getImageGreenPrimary

(PECL imagick 2.0.0)

Imagick::getImageGreenPrimary — Returns the chromaticy green primary point

Description

array Imagick::getImageGreenPrimary ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

Return Values

Returns an array with the keys "x" and "y" on success, throws an ImagickException on failure.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageGravity
Imagick::getImageHeight
The Imagick class


Returns the image height

Imagick::getImageGreenPrimary
Imagick::getImageHistogram
The Imagick class
PHP Manual

Imagick::getImageHeight

(PECL imagick 2.0.0)

Imagick::getImageHeight — Returns the image height

Description

int Imagick::getImageHeight ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the image height.

Return Values

Returns the image height in pixels. Throw an ImagickException on error.

Imagick::getImageGreenPrimary
Imagick::getImageHistogram
The Imagick class


Gets the image histogram

Imagick::getImageHeight
Imagick::getImageIndex
The Imagick class
PHP Manual

Imagick::getImageHistogram

(PECL imagick 2.0.0)

Imagick::getImageHistogram — Gets the image histogram

Description

array Imagick::getImageHistogram ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the image histogram as an array of ImagickPixel objects.

Return Values

Returns the image histogram as an array of ImagickPixel objects. Throw an ImagickException on error.

Imagick::getImageHeight
Imagick::getImageIndex
The Imagick class


Gets the index of the current active image

Imagick::getImageHistogram
Imagick::getImageInterlaceScheme
The Imagick class
PHP Manual

Imagick::getImageIndex

(PECL imagick 2.0.0)

Imagick::getImageIndex — Gets the index of the current active image

Description

int Imagick::getImageIndex ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the index of the current active image within the Imagick object. This method has been deprecated. See Imagick::getIteratorIndex

Return Values

Returns an integer containing the index of the image in the stack. Throw an ImagickException on error.

Imagick::getImageHistogram
Imagick::getImageInterlaceScheme
The Imagick class


Gets the image interlace scheme

Imagick::getImageIndex
Imagick::getImageInterpolateMethod
The Imagick class
PHP Manual

Imagick::getImageInterlaceScheme

(PECL imagick 2.0.0)

Imagick::getImageInterlaceScheme — Gets the image interlace scheme

Description

int Imagick::getImageInterlaceScheme ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image interlace scheme.

Return Values

Returns the interlace scheme as an integer on success. Throw an ImagickException on error.

Imagick::getImageIndex
Imagick::getImageInterpolateMethod
The Imagick class


Returns the interpolation method

Imagick::getImageInterlaceScheme
Imagick::getImageIterations
The Imagick class
PHP Manual

Imagick::getImageInterpolateMethod

(PECL imagick 2.0.0)

Imagick::getImageInterpolateMethod — Returns the interpolation method

Description

int Imagick::getImageInterpolateMethod ( void )

Returns the interpolation method for the specified image. The method is one of the Imagick::INTERPOLATE_* constants.

Return Values

Returns the interpolate method on success. Throw an ImagickException on error.

Imagick::getImageInterlaceScheme
Imagick::getImageIterations
The Imagick class


Gets the image iterations

Imagick::getImageInterpolateMethod
Imagick::getImageLength
The Imagick class
PHP Manual

Imagick::getImageIterations

(PECL imagick 2.0.0)

Imagick::getImageIterations — Gets the image iterations

Description

int Imagick::getImageIterations ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image iterations.

Return Values

Returns the image iterations as an integer. Throw an ImagickException on error.

Imagick::getImageInterpolateMethod
Imagick::getImageLength
The Imagick class


Returns the image length in bytes

Imagick::getImageIterations
Imagick::getImageMagickLicense
The Imagick class
PHP Manual

Imagick::getImageLength

(PECL imagick 2.0.0)

Imagick::getImageLength — Returns the image length in bytes

Description

int Imagick::getImageLength ( void )

Returns the image length in bytes

Return Values

Returns an int containing the current image size.

Examples

Example #1 Using Imagick::getImageLength():

Getting image length in bytes

<?php
$image = new Imagick('test.jpg');
echo $image->getImageLength() . ' bytes';
?>

Imagick::getImageIterations
Imagick::getImageMagickLicense
The Imagick class


Returns a string containing the ImageMagick license

Imagick::getImageLength
Imagick::getImageMatte
The Imagick class
PHP Manual

Imagick::getImageMagickLicense

(PECL imagick 2.0.0)

Imagick::getImageMagickLicense — Returns a string containing the ImageMagick license

Description

string Imagick::getImageMagickLicense ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns a string containing the ImageMagick license

Return Values

Returns a string containing the ImageMagick license.

Imagick::getImageLength
Imagick::getImageMatte
The Imagick class


Return if the image has a matte channel

Imagick::getImageMagickLicense
Imagick::getImageMatteColor
The Imagick class
PHP Manual

Imagick::getImageMatte

(PECL imagick 2.0.0)

Imagick::getImageMatte — Return if the image has a matte channel

Description

int Imagick::getImageMatte ( void )

Returns TRUE if the image has a matte channel otherwise false. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns TRUE on success or FALSE on failure.

Imagick::getImageMagickLicense
Imagick::getImageMatteColor
The Imagick class


Returns the image matte color

Imagick::getImageMatte
Imagick::getImageOrientation
The Imagick class
PHP Manual

Imagick::getImageMatteColor

(PECL imagick 2.0.0)

Imagick::getImageMatteColor — Returns the image matte color

Description

ImagickPixel Imagick::getImageMatteColor ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the image matte color.

Return Values

Returns ImagickPixel object on success. Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageMatte
Imagick::getImageOrientation
The Imagick class


Gets the image orientation

Imagick::getImageMatteColor
Imagick::getImagePage
The Imagick class
PHP Manual

Imagick::getImageOrientation

(PECL imagick 2.0.0)

Imagick::getImageOrientation — Gets the image orientation

Description

int Imagick::getImageOrientation ( void )

Gets the image orientation. The return value is one of the orientation constants.

Return Values

Returns an int on success. Throw an ImagickException on error.

Imagick::getImageMatteColor
Imagick::getImagePage
The Imagick class


Returns the page geometry

Imagick::getImageOrientation
Imagick::getImagePixelColor
The Imagick class
PHP Manual

Imagick::getImagePage

(PECL imagick 2.0.0)

Imagick::getImagePage — Returns the page geometry

Description

array Imagick::getImagePage ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

Return Values

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageOrientation
Imagick::getImagePixelColor
The Imagick class


Returns the color of the specified pixel

Imagick::getImagePage
Imagick::getImageProfile
The Imagick class
PHP Manual

Imagick::getImagePixelColor

(PECL imagick 2.0.0)

Imagick::getImagePixelColor — Returns the color of the specified pixel

Description

ImagickPixel Imagick::getImagePixelColor ( int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Returns the color of the specified pixel.

Parameters

x

The x-coordinate of the pixel

y

The y-coordinate of the pixel

Return Values

Returns an ImagickPixel instance for the color at the coordinates given. Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImagePage
Imagick::getImageProfile
The Imagick class


Returns the named image profile

Imagick::getImagePixelColor
Imagick::getImageProfiles
The Imagick class
PHP Manual

Imagick::getImageProfile

(PECL imagick 2.0.0)

Imagick::getImageProfile — Returns the named image profile

Description

string Imagick::getImageProfile ( string $name )
Warning

This function is currently not documented; only its argument list is available.

Returns the named image profile.

Parameters

name

The name of the profile to return.

Return Values

Returns a string containing the image profile. Throw an ImagickException on error.

Imagick::getImagePixelColor
Imagick::getImageProfiles
The Imagick class


Returns the image profiles

Imagick::getImageProfile
Imagick::getImageProperties
The Imagick class
PHP Manual

Imagick::getImageProfiles

(PECL imagick 2.0.0)

Imagick::getImageProfiles — Returns the image profiles

Description

array Imagick::getImageProfiles ([ string $pattern = "*" [, bool $only_names = true ]] )

Returns all associated profiles that match the pattern. If TRUE is passed as second parameter only the profile names are returned. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

pattern

The pattern for profile names.

only_names

Whether to return only profile names. If FALSE then values are returned as well

Return Values

Returns an array containing the image profiles or profile names.

Imagick::getImageProfile
Imagick::getImageProperties
The Imagick class


Returns the image properties

Imagick::getImageProfiles
Imagick::getImageProperty
The Imagick class
PHP Manual

Imagick::getImageProperties

(PECL imagick 2.0.0)

Imagick::getImageProperties — Returns the image properties

Description

array Imagick::getImageProperties ([ string $pattern = "*" [, bool $only_names = true ]] )

Returns all associated properties that match the pattern. If TRUE is passed as second parameter only the property names are returned. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

pattern

The pattern for property names.

only_names

Whether to return only property names. If FALSE then also the values are returned

Return Values

Returns an array containing the image properties or property names.

Examples

Example #1 Using Imagick::getImageProperties():

An example of extracting EXIF information.

<?php

/* Create the object */
$im = new imagick("/path/to/example.jpg");

/* Get the EXIF information */
$exifArray = $im->getImageProperties("exif:*");

/* Loop trough the EXIF properties */
foreach ($exifArray as $name => $property)
{
    echo "{$name} => {$property}<br />\n";
}

?>

Imagick::getImageProfiles
Imagick::getImageProperty
The Imagick class


Returns the named image property

Imagick::getImageProperties
Imagick::getImageRedPrimary
The Imagick class
PHP Manual

Imagick::getImageProperty

(PECL imagick 2.0.0)

Imagick::getImageProperty — Returns the named image property

Description

string Imagick::getImageProperty ( string $name )

Returns the named image property. This method is available if Imagick has been compiled against ImageMagick version 6.3.2 or newer.

Parameters

name

name of the property (for example Exif:DateTime)

Examples

Example #1 Using Imagick::getImageProperty():

Setting and getting image property

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");

$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>

See Also

  • Imagick::setImageProperty() - Sets an image property

Return Values

Returns a string containing the image property, false if a property with the given name does not exist.

Imagick::getImageProperties
Imagick::getImageRedPrimary
The Imagick class


Returns the chromaticity red primary point

Imagick::getImageProperty
Imagick::getImageRegion
The Imagick class
PHP Manual

Imagick::getImageRedPrimary

(PECL imagick 2.0.0)

Imagick::getImageRedPrimary — Returns the chromaticity red primary point

Description

array Imagick::getImageRedPrimary ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Return Values

Returns the chromaticity red primary point as an array with the keys "x" and "y". Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageProperty
Imagick::getImageRegion
The Imagick class


Extracts a region of the image

Imagick::getImageRedPrimary
Imagick::getImageRenderingIntent
The Imagick class
PHP Manual

Imagick::getImageRegion

(PECL imagick 2.0.0)

Imagick::getImageRegion — Extracts a region of the image

Description

Imagick Imagick::getImageRegion ( int $width , int $height , int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Extracts a region of the image and returns it as a new Imagick object.

Parameters

width

The width of the extracted region.

height

The height of the extracted region.

x

X-coordinate of the top-left corner of the extracted region.

y

Y-coordinate of the top-left corner of the extracted region.

Return Values

Extracts a region of the image and returns it as a new wand. Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageRedPrimary
Imagick::getImageRenderingIntent
The Imagick class


Gets the image rendering intent

Imagick::getImageRegion
Imagick::getImageResolution
The Imagick class
PHP Manual

Imagick::getImageRenderingIntent

(PECL imagick 2.0.0)

Imagick::getImageRenderingIntent — Gets the image rendering intent

Description

int Imagick::getImageRenderingIntent ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image rendering intent.

Return Values

Returns the image rendering intent. Throw an ImagickException on error.

Imagick::getImageRegion
Imagick::getImageResolution
The Imagick class


Gets the image X and Y resolution

Imagick::getImageRenderingIntent
Imagick::getImagesBlob
The Imagick class
PHP Manual

Imagick::getImageResolution

(PECL imagick 2.0.0)

Imagick::getImageResolution — Gets the image X and Y resolution

Description

array Imagick::getImageResolution ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image X and Y resolution.

Return Values

Returns the resolution as an array. Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageRenderingIntent
Imagick::getImagesBlob
The Imagick class


Returns all image sequences as a blob

Imagick::getImageResolution
Imagick::getImageScene
The Imagick class
PHP Manual

Imagick::getImagesBlob

(PECL imagick 2.0.0)

Imagick::getImagesBlob — Returns all image sequences as a blob

Description

string Imagick::getImagesBlob ( void )
Warning

This function is currently not documented; only its argument list is available.

Implements direct to memory image formats. It returns all image sequences as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().

Return Values

Returns a string containing the images. On failure, throws ImagickException.

Imagick::getImageResolution
Imagick::getImageScene
The Imagick class


Gets the image scene

Imagick::getImagesBlob
Imagick::getImageSignature
The Imagick class
PHP Manual

Imagick::getImageScene

(PECL imagick 2.0.0)

Imagick::getImageScene — Gets the image scene

Description

int Imagick::getImageScene ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image scene.

Return Values

Returns the image scene. Throw an ImagickException on error.

Imagick::getImagesBlob
Imagick::getImageSignature
The Imagick class


Generates an SHA-256 message digest

Imagick::getImageScene
Imagick::getImageSize
The Imagick class
PHP Manual

Imagick::getImageSignature

(PECL imagick 2.0.0)

Imagick::getImageSignature — Generates an SHA-256 message digest

Description

string Imagick::getImageSignature ( void )
Warning

This function is currently not documented; only its argument list is available.

Generates an SHA-256 message digest for the image pixel stream.

Return Values

Returns a string containing the SHA-256 hash of the file. Throw an ImagickException on error.

Imagick::getImageScene
Imagick::getImageSize
The Imagick class


Returns the image length in bytes

Imagick::getImageSignature
Imagick::getImageTicksPerSecond
The Imagick class
PHP Manual

Imagick::getImageSize

(PECL imagick 2.0.0)

Imagick::getImageSize — Returns the image length in bytes

Description

int Imagick::getImageSize ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the image length in bytes

Return Values

Returns an int containing the current image size.

Imagick::getImageSignature
Imagick::getImageTicksPerSecond
The Imagick class


Gets the image ticks-per-second

Imagick::getImageSize
Imagick::getImageTotalInkDensity
The Imagick class
PHP Manual

Imagick::getImageTicksPerSecond

(PECL imagick 2.0.0)

Imagick::getImageTicksPerSecond — Gets the image ticks-per-second

Description

int Imagick::getImageTicksPerSecond ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image ticks-per-second.

Return Values

Returns the image ticks-per-second. Throw an ImagickException on error.

Imagick::getImageSize
Imagick::getImageTotalInkDensity
The Imagick class


Gets the image total ink density

Imagick::getImageTicksPerSecond
Imagick::getImageType
The Imagick class
PHP Manual

Imagick::getImageTotalInkDensity

(PECL imagick 2.0.0)

Imagick::getImageTotalInkDensity — Gets the image total ink density

Description

float Imagick::getImageTotalInkDensity ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image total ink density.

Return Values

Returns the image total ink density of the image. Throw an ImagickException on error.

Imagick::getImageTicksPerSecond
Imagick::getImageType
The Imagick class


Gets the potential image type

Imagick::getImageTotalInkDensity
Imagick::getImageUnits
The Imagick class
PHP Manual

Imagick::getImageType

(PECL imagick 0.9.10-0.9.9)

Imagick::getImageType — Gets the potential image type

Description

int Imagick::getImageType ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the potential image type.

Return Values

Returns the potential image type. Throw an ImagickException on error.

Imagick::getImageTotalInkDensity
Imagick::getImageUnits
The Imagick class


Gets the image units of resolution

Imagick::getImageType
Imagick::getImageVirtualPixelMethod
The Imagick class
PHP Manual

Imagick::getImageUnits

(PECL imagick 2.0.0)

Imagick::getImageUnits — Gets the image units of resolution

Description

int Imagick::getImageUnits ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the image units of resolution.

Return Values

Returns the image units of resolution. Throw an ImagickException on error.

Imagick::getImageType
Imagick::getImageVirtualPixelMethod
The Imagick class


Returns the virtual pixel method

Imagick::getImageUnits
Imagick::getImageWhitePoint
The Imagick class
PHP Manual

Imagick::getImageVirtualPixelMethod

(PECL imagick 2.0.0)

Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method

Description

int Imagick::getImageVirtualPixelMethod ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the virtual pixel method for the specified image.

Return Values

Returns the virtual pixel method on success. Throw an ImagickException on error.

Imagick::getImageUnits
Imagick::getImageWhitePoint
The Imagick class


Returns the chromaticity white point

Imagick::getImageVirtualPixelMethod
Imagick::getImageWidth
The Imagick class
PHP Manual

Imagick::getImageWhitePoint

(PECL imagick 2.0.0)

Imagick::getImageWhitePoint — Returns the chromaticity white point

Description

array Imagick::getImageWhitePoint ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Return Values

Returns the chromaticity white point as an associative array with the keys "x" and "y". Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageVirtualPixelMethod
Imagick::getImageWidth
The Imagick class


Returns the image width

Imagick::getImageWhitePoint
Imagick::getInterlaceScheme
The Imagick class
PHP Manual

Imagick::getImageWidth

(PECL imagick 2.0.0)

Imagick::getImageWidth — Returns the image width

Description

int Imagick::getImageWidth ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the image width.

Return Values

Returns the image width. Throw an ImagickException on error.

Imagick::getImageWhitePoint
Imagick::getInterlaceScheme
The Imagick class


Gets the object interlace scheme

Imagick::getImageWidth
Imagick::getIteratorIndex
The Imagick class
PHP Manual

Imagick::getInterlaceScheme

(PECL imagick 2.0.0)

Imagick::getInterlaceScheme — Gets the object interlace scheme

Description

int Imagick::getInterlaceScheme ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the object interlace scheme.

Return Values

Gets the wand interlace scheme. Throw an ImagickException on error.

Imagick::getImageWidth
Imagick::getIteratorIndex
The Imagick class


Gets the index of the current active image

Imagick::getInterlaceScheme
Imagick::getNumberImages
The Imagick class
PHP Manual

Imagick::getIteratorIndex

(PECL imagick 2.0.0)

Imagick::getIteratorIndex — Gets the index of the current active image

Description

int Imagick::getIteratorIndex ( void )

Returns the index of the current active image within the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns an integer containing the index of the image in the stack. Throw an ImagickException on error.

Examples

Example #1 Using Imagick::getIteratorIndex():

Create images, set and get the iterator index

<?php
$im = new Imagick();
$im->newImage(100, 100, new ImagickPixel("red"));
$im->newImage(100, 100, new ImagickPixel("green"));
$im->newImage(100, 100, new ImagickPixel("blue"));

$im->setIteratorIndex(1);
echo $im->getIteratorIndex();
?>

See Also

  • Imagick::setIteratorIndex() - Set the iterator position
  • Imagick::getImageIndex() - Gets the index of the current active image
  • Imagick::setImageIndex() - Set the iterator position

Imagick::getInterlaceScheme
Imagick::getNumberImages
The Imagick class


Returns the number of images in the object

Imagick::getIteratorIndex
Imagick::getOption
The Imagick class
PHP Manual

Imagick::getNumberImages

(PECL imagick 2.0.0)

Imagick::getNumberImages — Returns the number of images in the object

Description

int Imagick::getNumberImages ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the number of images associated with Imagick object.

Return Values

Returns the number of images associated with Imagick object. Throw an ImagickException on error.

Imagick::getIteratorIndex
Imagick::getOption
The Imagick class


Returns a value associated with the specified key

Imagick::getNumberImages
Imagick::getPackageName
The Imagick class
PHP Manual

Imagick::getOption

(PECL imagick 2.0.0)

Imagick::getOption — Returns a value associated with the specified key

Description

string Imagick::getOption ( string $key )
Warning

This function is currently not documented; only its argument list is available.

Returns a value associated within the object for the specified key.

Parameters

key

The name of the option

Return Values

Returns a value associated with a wand and the specified key. Throw an ImagickException on error.

Imagick::getNumberImages
Imagick::getPackageName
The Imagick class


Returns the ImageMagick package name

Imagick::getOption
Imagick::getPage
The Imagick class
PHP Manual

Imagick::getPackageName

(PECL imagick 2.0.0)

Imagick::getPackageName — Returns the ImageMagick package name

Description

string Imagick::getPackageName ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the ImageMagick package name.

Return Values

Returns the ImageMagick package name as a string. Throw an ImagickException on error.

Imagick::getOption
Imagick::getPage
The Imagick class


Returns the page geometry

Imagick::getPackageName
Imagick::getPixelIterator
The Imagick class
PHP Manual

Imagick::getPage

(PECL imagick 2.0.0)

Imagick::getPage — Returns the page geometry

Description

array Imagick::getPage ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y".

Return Values

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y", throwing ImagickException on error.

Imagick::getPackageName
Imagick::getPixelIterator
The Imagick class


Returns a MagickPixelIterator

Imagick::getPage
Imagick::getPixelRegionIterator
The Imagick class
PHP Manual

Imagick::getPixelIterator

(PECL imagick 2.0.0)

Imagick::getPixelIterator — Returns a MagickPixelIterator

Description

ImagickPixelIterator Imagick::getPixelIterator ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns a MagickPixelIterator.

Return Values

Returns an ImagickPixelIterator on success. Throw an ImagickException on error.

Imagick::getPage
Imagick::getPixelRegionIterator
The Imagick class


Get an ImagickPixelIterator for an image section

Imagick::getPixelIterator
Imagick::getPointSize
The Imagick class
PHP Manual

Imagick::getPixelRegionIterator

(PECL imagick 2.0.0)

Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section

Description

ImagickPixelIterator Imagick::getPixelRegionIterator ( int $x , int $y , int $columns , int $rows )
Warning

This function is currently not documented; only its argument list is available.

Get an ImagickPixelIterator for an image section.

Parameters

x

The x-coordinate of the region.

y

The y-coordinate of the region.

columns

The width of the region.

rows

The height of the region.

Return Values

Returns an ImagickPixelIterator for an image section. Throw an ImagickException on error.

Imagick::getPixelIterator
Imagick::getPointSize
The Imagick class


Gets point size

Imagick::getPixelRegionIterator
Imagick::getQuantumDepth
The Imagick class
PHP Manual

Imagick::getPointSize

(No version information available, might only be in SVN)

Imagick::getPointSize — Gets point size

Description

string Imagick::getPointSize ( void )

Returns the objects point size property. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Return Values

Returns a float containing the point size.

See Also

  • Imagick::setPointSize() - Sets point size

Imagick::getPixelRegionIterator
Imagick::getQuantumDepth
The Imagick class


Gets the quantum depth

Imagick::getPointSize
Imagick::getQuantumRange
The Imagick class
PHP Manual

Imagick::getQuantumDepth

(PECL imagick 2.0.0)

Imagick::getQuantumDepth — Gets the quantum depth

Description

array Imagick::getQuantumDepth ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the Imagick quantum depth as a string.

Return Values

Returns the Imagick quantum depth as a string. Throw an ImagickException on error.

Imagick::getPointSize
Imagick::getQuantumRange
The Imagick class


Returns the Imagick quantum range

Imagick::getQuantumDepth
Imagick::getReleaseDate
The Imagick class
PHP Manual

Imagick::getQuantumRange

(PECL imagick 2.0.0)

Imagick::getQuantumRange — Returns the Imagick quantum range

Description

array Imagick::getQuantumRange ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the Imagick quantum range as a string.

Return Values

Returns the Imagick quantum range as a string. Throw an ImagickException on error.

Imagick::getQuantumDepth
Imagick::getReleaseDate
The Imagick class


Returns the ImageMagick release date

Imagick::getQuantumRange
Imagick::getResource
The Imagick class
PHP Manual

Imagick::getReleaseDate

(PECL imagick 2.0.0)

Imagick::getReleaseDate — Returns the ImageMagick release date

Description

string Imagick::getReleaseDate ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the ImageMagick release date as a string.

Return Values

Returns the ImageMagick release date as a string. Throw an ImagickException on error.

Imagick::getQuantumRange
Imagick::getResource
The Imagick class


Returns the specified resource's memory usage

Imagick::getReleaseDate
Imagick::getResourceLimit
The Imagick class
PHP Manual

Imagick::getResource

(PECL imagick 2.0.0)

Imagick::getResource — Returns the specified resource's memory usage

Description

int Imagick::getResource ( int $type )
Warning

This function is currently not documented; only its argument list is available.

Returns the specified resource's memory usage in megabytes.

Parameters

type

Refer to the list of resourcetype constants.

Return Values

Returns the specified resource's memory usage in megabytes. Throw an ImagickException on error.

Imagick::getReleaseDate
Imagick::getResourceLimit
The Imagick class


Returns the specified resource limit

Imagick::getResource
Imagick::getSamplingFactors
The Imagick class
PHP Manual

Imagick::getResourceLimit

(PECL imagick 2.0.0)

Imagick::getResourceLimit — Returns the specified resource limit

Description

int Imagick::getResourceLimit ( int $type )
Warning

This function is currently not documented; only its argument list is available.

Returns the specified resource limit in megabytes.

Parameters

type

Refer to the list of resourcetype constants.

Return Values

Returns the specified resource limit in megabytes. Throw an ImagickException on error.

Imagick::getResource
Imagick::getSamplingFactors
The Imagick class


Gets the horizontal and vertical sampling factor

Imagick::getResourceLimit
Imagick::getSize
The Imagick class
PHP Manual

Imagick::getSamplingFactors

(PECL imagick 2.0.0)

Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor

Description

array Imagick::getSamplingFactors ( void )
Warning

This function is currently not documented; only its argument list is available.

Gets the horizontal and vertical sampling factor.

Return Values

Returns an associative array with the horizontal and vertical sampling factors of the image. Throw an ImagickException on error.

Imagick::getResourceLimit
Imagick::getSize
The Imagick class


Returns the size associated with the Imagick object

Imagick::getSamplingFactors
Imagick::getSizeOffset
The Imagick class
PHP Manual

Imagick::getSize

(PECL imagick 2.0.0)

Imagick::getSize — Returns the size associated with the Imagick object

Description

array Imagick::getSize ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the size associated with the Imagick object as an array with the keys "columns" and "rows".

Return Values

Returns the size associated with the Imagick object as an array with the keys "columns" and "rows".

Imagick::getSamplingFactors
Imagick::getSizeOffset
The Imagick class


Returns the size offset

Imagick::getSize
Imagick::getVersion
The Imagick class
PHP Manual

Imagick::getSizeOffset

(PECL imagick 2.0.0)

Imagick::getSizeOffset — Returns the size offset

Description

int Imagick::getSizeOffset ( void )

Returns the size offset associated with the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns the size offset associated with the Imagick object. Throw an ImagickException on error.

Imagick::getSize
Imagick::getVersion
The Imagick class


Returns the ImageMagick API version

Imagick::getSizeOffset
Imagick::haldClutImage
The Imagick class
PHP Manual

Imagick::getVersion

(PECL imagick 2.0.0)

Imagick::getVersion — Returns the ImageMagick API version

Description

array Imagick::getVersion ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the ImageMagick API version as a string and as a number.

Return Values

Returns the ImageMagick API version as a string and as a number. Throw an ImagickException on error.

Imagick::getSizeOffset
Imagick::haldClutImage
The Imagick class


Checks if the object has more images

Imagick::haldClutImage
Imagick::hasPreviousImage
The Imagick class
PHP Manual

Imagick::hasNextImage

(PECL imagick 2.0.0)

Imagick::hasNextImage — Checks if the object has more images

Description

bool Imagick::hasNextImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns TRUE if the object has more images when traversing the list in the forward direction.

Return Values

Returns TRUE if the object has more images when traversing the list in the forward direction, returns FALSE if there are none.

Imagick::haldClutImage
Imagick::hasPreviousImage
The Imagick class


Checks if the object has a previous image

Imagick::hasNextImage
Imagick::identifyImage
The Imagick class
PHP Manual

Imagick::hasPreviousImage

(PECL imagick 2.0.0)

Imagick::hasPreviousImage — Checks if the object has a previous image

Description

bool Imagick::hasPreviousImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns TRUE if the object has more images when traversing the list in the reverse direction

Return Values

Returns TRUE if the object has more images when traversing the list in the reverse direction, returns FALSE if there are none.

Imagick::hasNextImage
Imagick::identifyImage
The Imagick class


Identifies an image and fetches attributes

Imagick::hasPreviousImage
Imagick::implodeImage
The Imagick class
PHP Manual

Imagick::identifyImage

(PECL imagick 2.0.0)

Imagick::identifyImage — Identifies an image and fetches attributes

Description

array Imagick::identifyImage ([ bool $appendRawOutput = false ] )
Warning

This function is currently not documented; only its argument list is available.

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

Parameters

appendRawOutput

Return Values

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others. Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Imagick::hasPreviousImage
Imagick::implodeImage
The Imagick class


Creates a new image as a copy

Imagick::identifyImage
Imagick::importImagePixels
The Imagick class
PHP Manual

Imagick::implodeImage

(PECL imagick 2.0.0)

Imagick::implodeImage — Creates a new image as a copy

Description

bool Imagick::implodeImage ( float $radius )
Warning

This function is currently not documented; only its argument list is available.

Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage.

Parameters

radius

The radius of the implode

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::identifyImage
Imagick::importImagePixels
The Imagick class


Adds a label to an image

Imagick::importImagePixels
Imagick::levelImage
The Imagick class
PHP Manual

Imagick::labelImage

(PECL imagick 2.0.0)

Imagick::labelImage — Adds a label to an image

Description

bool Imagick::labelImage ( string $label )
Warning

This function is currently not documented; only its argument list is available.

Adds a label to an image.

Parameters

label

The label to add

Return Values

Returns TRUE on success.

Imagick::importImagePixels
Imagick::levelImage
The Imagick class


Adjusts the levels of an image

Imagick::labelImage
Imagick::linearStretchImage
The Imagick class
PHP Manual

Imagick::levelImage

(PECL imagick 2.0.0)

Imagick::levelImage — Adjusts the levels of an image

Description

bool Imagick::levelImage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.

Parameters

blackPoint

The image black point

gamma

The gamma value

whitePoint

The image white point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::labelImage
Imagick::linearStretchImage
The Imagick class


Stretches with saturation the image intensity

Imagick::levelImage
Imagick::liquidRescaleImage
The Imagick class
PHP Manual

Imagick::linearStretchImage

(PECL imagick 2.0.0)

Imagick::linearStretchImage — Stretches with saturation the image intensity

Description

bool Imagick::linearStretchImage ( float $blackPoint , float $whitePoint )

Stretches with saturation the image intensity.

Parameters

blackPoint

The image black point

whitePoint

The image white point

Return Values

Returns TRUE on success.

Imagick::levelImage
Imagick::liquidRescaleImage
The Imagick class


Animates an image or images

Imagick::linearStretchImage
Imagick::magnifyImage
The Imagick class
PHP Manual

Imagick::liquidRescaleImage

(No version information available, might only be in SVN)

Imagick::liquidRescaleImage — Animates an image or images

Description

bool Imagick::liquidRescaleImage ( int $width , int $height , float $delta_x , float $rigidity )

This method scales the images using liquid rescaling method. This method is an implementation of a technique called seam carving. In order for this method to work as expected ImageMagick must be compiled with liblqr support. This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer.

Parameters

width

The width of the target size

height

The height of the target size

delta_x

How much the seam can traverse on x-axis. Passing 0 causes the seams to be straight.

rigidity

Introduces a bias for non-straight seams. This parameter is typically 0.

Return Values

Returns TRUE on success.

See Also

  • Imagick::resizeImage() - Scales an image

Imagick::linearStretchImage
Imagick::magnifyImage
The Imagick class


Scales an image proportionally 2x

Imagick::liquidRescaleImage
Imagick::mapImage
The Imagick class
PHP Manual

Imagick::magnifyImage

(PECL imagick 2.0.0)

Imagick::magnifyImage — Scales an image proportionally 2x

Description

bool Imagick::magnifyImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Is a convenience method that scales an image proportionally to twice its original size.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::liquidRescaleImage
Imagick::mapImage
The Imagick class


Replaces the colors of an image with the closest color from a reference image.

Imagick::magnifyImage
Imagick::matteFloodfillImage
The Imagick class
PHP Manual

Imagick::mapImage

(PECL imagick 2.0.0)

Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image.

Description

bool Imagick::mapImage ( Imagick $map , bool $dither )
Warning

This function is currently not documented; only its argument list is available.

Parameters

map

dither

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::magnifyImage
Imagick::matteFloodfillImage
The Imagick class


Changes the transparency value of a color

Imagick::mapImage
Imagick::medianFilterImage
The Imagick class
PHP Manual

Imagick::matteFloodfillImage

(PECL imagick 2.0.0)

Imagick::matteFloodfillImage — Changes the transparency value of a color

Description

bool Imagick::matteFloodfillImage ( float $alpha , float $fuzz , mixed $bordercolor , int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Changes the transparency value of any pixel that matches target and is an immediate neighbor. If the method FillToBorderMethod is specified, the transparency value is changed for any neighbor pixel that does not match the bordercolor member of image.

Parameters

alpha

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

bordercolor

An ImagickPixel object or string representing the border color.

x

The starting x coordinate of the operation.

y

The starting y coordinate of the operation.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.

Imagick::mapImage
Imagick::medianFilterImage
The Imagick class


Applies a digital filter

Imagick::matteFloodfillImage
Imagick::mergeImageLayers
The Imagick class
PHP Manual

Imagick::medianFilterImage

(PECL imagick 2.0.0)

Imagick::medianFilterImage — Applies a digital filter

Description

bool Imagick::medianFilterImage ( float $radius )
Warning

This function is currently not documented; only its argument list is available.

Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.

Parameters

radius

The radius of the pixel neighborhood.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::matteFloodfillImage
Imagick::mergeImageLayers
The Imagick class


Merges image layers

Imagick::medianFilterImage
Imagick::minifyImage
The Imagick class
PHP Manual

Imagick::mergeImageLayers

(PECL imagick 2.1.0)

Imagick::mergeImageLayers — Merges image layers

Description

bool Imagick::mergeImageLayers ( int $layer_method )

Merges image layers into one. This method is useful when working with image formats that use multiple layers such as PSD. The merging is controlled using the layer_method which defines how the layers are merged. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Parameters

layer_method

One of the Imagick::LAYERMETHOD_* constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

See Also

  • Imagick::flattenImages() - Merges a sequence of images

Imagick::medianFilterImage
Imagick::minifyImage
The Imagick class


Scales an image proportionally to half its size

Imagick::mergeImageLayers
Imagick::modulateImage
The Imagick class
PHP Manual

Imagick::minifyImage

(PECL imagick 2.0.0)

Imagick::minifyImage — Scales an image proportionally to half its size

Description

bool Imagick::minifyImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Is a convenience method that scales an image proportionally to one-half its original size

Return Values

Returns TRUE on success.

Imagick::mergeImageLayers
Imagick::modulateImage
The Imagick class


Control the brightness, saturation, and hue

Imagick::minifyImage
Imagick::montageImage
The Imagick class
PHP Manual

Imagick::modulateImage

(PECL imagick 2.0.0)

Imagick::modulateImage — Control the brightness, saturation, and hue

Description

bool Imagick::modulateImage ( float $brightness , float $saturation , float $hue )
Warning

This function is currently not documented; only its argument list is available.

Lets you control the brightness, saturation, and hue of an image. Hue is the percentage of absolute rotation from the current position. For example 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a clockwise rotation of 90 degrees, with 0 and 200 both resulting in a rotation of 180 degrees.

Parameters

brightness

saturation

hue

Return Values

Returns TRUE on success.

Imagick::minifyImage
Imagick::montageImage
The Imagick class


Creates a composite image

Imagick::modulateImage
Imagick::morphImages
The Imagick class
PHP Manual

Imagick::montageImage

(PECL imagick 2.0.0)

Imagick::montageImage — Creates a composite image

Description

Imagick Imagick::montageImage ( ImagickDraw $draw , string $tile_geometry , string $thumbnail_geometry , int $mode , string $frame )
Warning

This function is currently not documented; only its argument list is available.

Creates a composite image by combining several separate images. The images are tiled on the composite image with the name of the image optionally appearing just below the individual tile.

Parameters

draw

The font name, size, and color are obtained from this object.

tile_geometry

The number of tiles per row and page (e.g. 6x4+0+0).

thumbnail_geometry

Preferred image size and border size of each thumbnail (e.g. 120x120+4+3>).

mode

Thumbnail framing mode, see Montage Mode constants.

frame

Surround the image with an ornamental border (e.g. 15x15+3+3). The frame color is that of the thumbnail's matte color.

Return Values

Returns TRUE on success.

Imagick::modulateImage
Imagick::morphImages
The Imagick class


Method morphs a set of images

Imagick::montageImage
Imagick::mosaicImages
The Imagick class
PHP Manual

Imagick::morphImages

(PECL imagick 2.0.0)

Imagick::morphImages — Method morphs a set of images

Description

Imagick Imagick::morphImages ( int $number_frames )
Warning

This function is currently not documented; only its argument list is available.

Method morphs a set of images. Both the image pixels and size are linearly interpolated to give the appearance of a meta-morphosis from one image to the next.

Parameters

number_frames

The number of in-between images to generate.

Return Values

This method returns a new Imagick object on success. Throw an ImagickException on error.

Imagick::montageImage
Imagick::mosaicImages
The Imagick class


Forms a mosaic from images

Imagick::morphImages
Imagick::motionBlurImage
The Imagick class
PHP Manual

Imagick::mosaicImages

(PECL imagick 2.0.0)

Imagick::mosaicImages — Forms a mosaic from images

Description

Imagick Imagick::mosaicImages ( void )
Warning

This function is currently not documented; only its argument list is available.

Inlays an image sequence to form a single coherent picture. It returns a wand with each image in the sequence composited at the location defined by the page offset of the image.

Return Values

Returns TRUE on success.

Imagick::morphImages
Imagick::motionBlurImage
The Imagick class


Simulates motion blur

Imagick::mosaicImages
Imagick::negateImage
The Imagick class
PHP Manual

Imagick::motionBlurImage

(PECL imagick 2.0.0)

Imagick::motionBlurImage — Simulates motion blur

Description

bool Imagick::motionBlurImage ( float $radius , float $sigma , float $angle [, int $channel = Imagick::CHANNEL_DEFAULT ] )
Warning

This function is currently not documented; only its argument list is available.

Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage() selects a suitable radius for you. Angle gives the angle of the blurring motion.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants. The channel argument affects only if Imagick is compiled against ImageMagick version 6.4.4 or greater.

Return Values

Returns TRUE on success.

Imagick::mosaicImages
Imagick::negateImage
The Imagick class


Negates the colors in the reference image

Imagick::motionBlurImage
Imagick::newImage
The Imagick class
PHP Manual

Imagick::negateImage

(PECL imagick 2.0.0)

Imagick::negateImage — Negates the colors in the reference image

Description

bool Imagick::negateImage ( bool $gray [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Negates the colors in the reference image. The Grayscale option means that only grayscale values within the image are negated.

Parameters

gray

Whether to only negate grayscale pixels within the image.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::motionBlurImage
Imagick::newImage
The Imagick class


Creates a new image

Imagick::negateImage
Imagick::newPseudoImage
The Imagick class
PHP Manual

Imagick::newImage

(PECL imagick 2.0.0)

Imagick::newImage — Creates a new image

Description

bool Imagick::newImage ( int $cols , int $rows , mixed $background [, string $format ] )
Warning

This function is currently not documented; only its argument list is available.

Creates a new image and associates ImagickPixel value as background color

Parameters

cols

Columns in the new image

rows

Rows in the new image

background

The background color used for this image

format

Image format. This parameter was added in Imagick version 2.0.1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.

Examples

Example #1 Using Imagick::newImage():

Create a new image and display it.

<?php

$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');

header('Content-type: image/png');
echo $image;

?>

Imagick::negateImage
Imagick::newPseudoImage
The Imagick class


Creates a new image

Imagick::newImage
Imagick::nextImage
The Imagick class
PHP Manual

Imagick::newPseudoImage

(PECL imagick 2.0.0)

Imagick::newPseudoImage — Creates a new image

Description

bool Imagick::newPseudoImage ( int $columns , int $rows , string $pseudoString )
Warning

This function is currently not documented; only its argument list is available.

Creates a new image using ImageMagick pseudo-formats.

Parameters

columns

columns in the new image

rows

rows in the new image

pseudoString

string containing pseudo image definition.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::newImage
Imagick::nextImage
The Imagick class


Moves to the next image

Imagick::newPseudoImage
Imagick::normalizeImage
The Imagick class
PHP Manual

Imagick::nextImage

(PECL imagick 2.0.0)

Imagick::nextImage — Moves to the next image

Description

bool Imagick::nextImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Associates the next image in the image list with an Imagick object.

Return Values

Returns TRUE on success.

Imagick::newPseudoImage
Imagick::normalizeImage
The Imagick class


Enhances the contrast of a color image

Imagick::nextImage
Imagick::oilPaintImage
The Imagick class
PHP Manual

Imagick::normalizeImage

(PECL imagick 2.0.0)

Imagick::normalizeImage — Enhances the contrast of a color image

Description

bool Imagick::normalizeImage ([ int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Imagick::nextImage
Imagick::oilPaintImage
The Imagick class


Simulates an oil painting

Imagick::normalizeImage
Imagick::opaquePaintImage
The Imagick class
PHP Manual

Imagick::oilPaintImage

(PECL imagick 2.0.0)

Imagick::oilPaintImage — Simulates an oil painting

Description

bool Imagick::oilPaintImage ( float $radius )
Warning

This function is currently not documented; only its argument list is available.

Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

Parameters

radius

The radius of the circular neighborhood.

Return Values

Returns TRUE on success.

Imagick::normalizeImage
Imagick::opaquePaintImage
The Imagick class


Changes the color value of any pixel that matches target

Imagick::oilPaintImage
Imagick::optimizeImageLayers
The Imagick class
PHP Manual

Imagick::opaquePaintImage

(No version information available, might only be in SVN)

Imagick::opaquePaintImage — Changes the color value of any pixel that matches target

Description

bool Imagick::opaquePaintImage ( mixed $target , mixed $fill , float $fuzz , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Changes any pixel that matches color with the color defined by fill. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

Parameters

target

ImagickPixel object or a string containing the color to change

fill

The replacement color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

invert

If TRUE paints any pixel that does not match the target color.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Imagick::oilPaintImage
Imagick::optimizeImageLayers
The Imagick class


Removes repeated portions of images to optimize

Imagick::opaquePaintImage
Imagick::orderedPosterizeImage
The Imagick class
PHP Manual

Imagick::optimizeImageLayers

(PECL imagick 2.0.0)

Imagick::optimizeImageLayers — Removes repeated portions of images to optimize

Description

bool Imagick::optimizeImageLayers ( void )

Compares each image the GIF disposed forms of the previous image in the sequence. From this it attempts to select the smallest cropped image to replace each frame, while preserving the results of the animation. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::optimizeImageLayers()

Reading, optimizing and writing a GIF image

<?php
/* create new imagick object */
$im = new Imagick("test.gif");

/* optimize the image layers */
$im->optimizeImageLayers();

/* write the image back */
$im->writeImages("test_optimized.gif", true);
?>

See Also

  • Imagick::compareImageLayers() - Returns the maximum bounding region between images
  • Imagick::writeImages() - Writes an image or image sequence
  • Imagick::writeImage() - Writes an image to the specified filename

Imagick::opaquePaintImage
Imagick::orderedPosterizeImage
The Imagick class


Performs an ordered dither

Imagick::optimizeImageLayers
Imagick::paintFloodfillImage
The Imagick class
PHP Manual

Imagick::orderedPosterizeImage

(PECL imagick 2.2.2)

Imagick::orderedPosterizeImage — Performs an ordered dither

Description

bool Imagick::orderedPosterizeImage ( string $threshold_map [, int $channel = Imagick::CHANNEL_ALL ] )

Performs an ordered dither based on a number of pre-defined dithering threshold maps, but over multiple intensity levels, which can be different for different channels, according to the input arguments. This method is available if Imagick has been compiled against ImageMagick version 6.3.1 or newer.

Parameters

threshold_map

A string containing the name of the threshold dither map to use

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::optimizeImageLayers
Imagick::paintFloodfillImage
The Imagick class


Changes the color value of any pixel that matches target

Imagick::orderedPosterizeImage
Imagick::paintOpaqueImage
The Imagick class
PHP Manual

Imagick::paintFloodfillImage

(PECL imagick 2.1.0)

Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target

Description

bool Imagick::paintFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )

Changes the color value of any pixel that matches target and is an immediate neighbor. As of ImageMagick 6.3.8 this method has been deprecated and Imagick::floodfillPaintImage() should be used instead.

Parameters

fill

ImagickPixel object or a string containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.

bordercolor

ImagickPixel object or a string containing the border color

x

X start position of the floodfill

y

Y start position of the floodfill

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Imagick::orderedPosterizeImage
Imagick::paintOpaqueImage
The Imagick class


Change any pixel that matches color

Imagick::paintFloodfillImage
Imagick::paintTransparentImage
The Imagick class
PHP Manual

Imagick::paintOpaqueImage

(PECL imagick 2.0.0)

Imagick::paintOpaqueImage — Change any pixel that matches color

Description

bool Imagick::paintOpaqueImage ( mixed $target , mixed $fill , float $fuzz [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Changes any pixel that matches color with the color defined by fill.

Parameters

target

Change this target color to the fill color within the image. An ImagickPixel object or a string representing the target color.

fill

An ImagickPixel object or a string representing the fill color.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as first and second parameter. Previous versions allow only an ImagickPixel object.

Imagick::paintFloodfillImage
Imagick::paintTransparentImage
The Imagick class


Changes any pixel that matches color with the color defined by fill

Imagick::paintOpaqueImage
Imagick::pingImage
The Imagick class
PHP Manual

Imagick::paintTransparentImage

(PECL imagick 2.0.0)

Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill

Description

bool Imagick::paintTransparentImage ( mixed $target , float $alpha , float $fuzz )
Warning

This function is currently not documented; only its argument list is available.

Changes any pixel that matches color with the color defined by fill.

Parameters

target

Change this target color to specified opacity value within the image.

alpha

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Imagick::paintOpaqueImage
Imagick::pingImage
The Imagick class


Fetch basic attributes about the image

Imagick::paintTransparentImage
Imagick::pingImageBlob
The Imagick class
PHP Manual

Imagick::pingImage

(PECL imagick 2.0.0)

Imagick::pingImage — Fetch basic attributes about the image

Description

bool Imagick::pingImage ( string $filename )
Warning

This function is currently not documented; only its argument list is available.

This method can be used to query image width, height, size, and format without reading the whole image in to memory.

Parameters

filename

The filename to read the information from.

Return Values

Returns TRUE on success.

Imagick::paintTransparentImage
Imagick::pingImageBlob
The Imagick class


Quickly fetch attributes

Imagick::pingImage
Imagick::pingImageFile
The Imagick class
PHP Manual

Imagick::pingImageBlob

(PECL imagick 2.0.0)

Imagick::pingImageBlob — Quickly fetch attributes

Description

bool Imagick::pingImageBlob ( string $image )

This method can be used to query image width, height, size, and format without reading the whole image to memory. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

image

A string containing the image.

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::pingImageBlob()

Pinging an image from a string

<?php
/* read image contents */
$image = file_get_contents("test.jpg");

/* create new imagick object */
$im = new Imagick();

/* pass the string to the imagick object */
$im->pingImageBlob($image);

/* output image width and height */
echo $im->getImageWidth() . 'x' . $im->getImageHeight();
?>

See Also

  • Imagick::pingImage() - Fetch basic attributes about the image
  • Imagick::pingImageFile() - Get basic image attributes in a lightweight manner
  • Imagick::readImage() - Reads image from filename
  • Imagick::readImageBlob() - Reads image from a binary string
  • Imagick::readImageFile() - Reads image from open filehandle

Imagick::pingImage
Imagick::pingImageFile
The Imagick class


Get basic image attributes in a lightweight manner

Imagick::pingImageBlob
Imagick::polaroidImage
The Imagick class
PHP Manual

Imagick::pingImageFile

(PECL imagick 2.0.0)

Imagick::pingImageFile — Get basic image attributes in a lightweight manner

Description

bool Imagick::pingImageFile ( resource $filehandle [, string $fileName ] )

This method can be used to query image width, height, size, and format without reading the whole image to memory. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

filehandle

An open filehandle to the image.

fileName

Optional filename for this image.

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::pingImageFile()

Opening a remote location

<?php
/* fopen a remote location */
$fp = fopen("http://example.com/test.jpg");

/* create new imagick object */
$im = new Imagick();

/* pass the handle to imagick */
$im->pingImageFile($fp);
?>

See Also

  • Imagick::pingImage() - Fetch basic attributes about the image
  • Imagick::pingImageBlob() - Quickly fetch attributes
  • Imagick::readImage() - Reads image from filename
  • Imagick::readImageBlob() - Reads image from a binary string
  • Imagick::readImageFile() - Reads image from open filehandle

Imagick::pingImageBlob
Imagick::polaroidImage
The Imagick class


Simulates a Polaroid picture

Imagick::pingImageFile
Imagick::posterizeImage
The Imagick class
PHP Manual

Imagick::polaroidImage

(PECL imagick 2.0.0)

Imagick::polaroidImage — Simulates a Polaroid picture

Description

bool Imagick::polaroidImage ( ImagickDraw $properties , float $angle )

Simulates a Polaroid picture. This method is available if Imagick has been compiled against ImageMagick version 6.3.2 or newer.

Parameters

properties

The polaroid properties

angle

The polaroid angle

Return Values

Returns TRUE on success.

Examples

Example #1 A Imagick::polaroidImage() example

An example of using Imagick::polaroidImage()

<?php
/* Create the object */
$image = new Imagick('source.png');

/* Set the opacity */
$image->polaroidImage(new ImagickDraw(), 25);

/* output the image */
header('Content-type: image/png');
echo $image;

?>

Imagick::pingImageFile
Imagick::posterizeImage
The Imagick class


Reduces the image to a limited number of color level

Imagick::polaroidImage
Imagick::previewImages
The Imagick class
PHP Manual

Imagick::posterizeImage

(PECL imagick 2.0.0)

Imagick::posterizeImage — Reduces the image to a limited number of color level

Description

bool Imagick::posterizeImage ( int $levels , bool $dither )
Warning

This function is currently not documented; only its argument list is available.

Reduces the image to a limited number of color level.

Parameters

levels

dither

Return Values

Returns TRUE on success.

Imagick::polaroidImage
Imagick::previewImages
The Imagick class


Quickly pin-point appropriate parameters for image processing

Imagick::posterizeImage
Imagick::previousImage
The Imagick class
PHP Manual

Imagick::previewImages

(PECL imagick 2.0.0)

Imagick::previewImages — Quickly pin-point appropriate parameters for image processing

Description

bool Imagick::previewImages ( int $preview )
Warning

This function is currently not documented; only its argument list is available.

Tiles 9 thumbnails of the specified image with an image processing operation applied at varying strengths. This is helpful to quickly pin-point an appropriate parameter for an image processing operation.

Parameters

preview

Preview type. See Preview type constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::posterizeImage
Imagick::previousImage
The Imagick class


Move to the previous image in the object

Imagick::previewImages
Imagick::profileImage
The Imagick class
PHP Manual

Imagick::previousImage

(PECL imagick 2.0.0)

Imagick::previousImage — Move to the previous image in the object

Description

bool Imagick::previousImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Assocates the previous image in an image list with the Imagick object.

Return Values

Returns TRUE on success.

Imagick::previewImages
Imagick::profileImage
The Imagick class


Adds or removes a profile from an image

Imagick::previousImage
Imagick::quantizeImage
The Imagick class
PHP Manual

Imagick::profileImage

(PECL imagick 2.0.0)

Imagick::profileImage — Adds or removes a profile from an image

Description

bool Imagick::profileImage ( string $name , string $profile )
Warning

This function is currently not documented; only its argument list is available.

Adds or removes a ICC, IPTC, or generic profile from an image. If the profile is NULL, it is removed from the image otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.

Parameters

name

profile

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::previousImage
Imagick::quantizeImage
The Imagick class


Analyzes the colors within a reference image

Imagick::profileImage
Imagick::quantizeImages
The Imagick class
PHP Manual

Imagick::quantizeImage

(PECL imagick 2.0.0)

Imagick::quantizeImage — Analyzes the colors within a reference image

Description

bool Imagick::quantizeImage ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )
Warning

This function is currently not documented; only its argument list is available.

Parameters

numberColors

colorspace

treedepth

dither

measureError

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::profileImage
Imagick::quantizeImages
The Imagick class


Analyzes the colors within a sequence of images

Imagick::quantizeImage
Imagick::queryFontMetrics
The Imagick class
PHP Manual

Imagick::quantizeImages

(PECL imagick 2.0.0)

Imagick::quantizeImages — Analyzes the colors within a sequence of images

Description

bool Imagick::quantizeImages ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )
Warning

This function is currently not documented; only its argument list is available.

Parameters

numberColors

colorspace

treedepth

dither

measureError

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::quantizeImage
Imagick::queryFontMetrics
The Imagick class


Returns an array representing the font metrics

Imagick::quantizeImages
Imagick::queryFonts
The Imagick class
PHP Manual

Imagick::queryFontMetrics

(PECL imagick 2.0.0)

Imagick::queryFontMetrics — Returns an array representing the font metrics

Description

array Imagick::queryFontMetrics ( ImagickDraw $properties , string $text [, bool $multiline ] )
Warning

This function is currently not documented; only its argument list is available.

Returns a multi-dimensional array representing the font metrics.

Parameters

properties

ImagickDraw object containing font properties

text

The text

multiline

Multiline parameter. If left empty it is autodetected

Return Values

Returns a multi-dimensional array representing the font metrics. Throw an ImagickException on error.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::queryFontMetrics():

Query the metrics for the text and dump the results on the screen.

<?php
/* Create a new Imagick object */
$im = new Imagick();

/* Create an ImagickDraw object */
$draw = new ImagickDraw();

/* Set the font */
$draw->setFont('/path/to/font.ttf');

/* Dump the font metrics, autodetect multiline */
var_dump($im->queryFontMetrics($draw, "Hello World!"));
?>

Imagick::quantizeImages
Imagick::queryFonts
The Imagick class


Returns the configured fonts

Imagick::queryFontMetrics
Imagick::queryFormats
The Imagick class
PHP Manual

Imagick::queryFonts

(PECL imagick 2.0.0)

Imagick::queryFonts — Returns the configured fonts

Description

array Imagick::queryFonts ([ string $pattern = "*" ] )
Warning

This function is currently not documented; only its argument list is available.

Returns the configured fonts.

Parameters

pattern

The query pattern

Return Values

Returns an array containing the configured fonts. Throw an ImagickException on error.

Imagick::queryFontMetrics
Imagick::queryFormats
The Imagick class


Returns formats supported by Imagick

Imagick::queryFonts
Imagick::radialBlurImage
The Imagick class
PHP Manual

Imagick::queryFormats

(PECL imagick 2.0.0)

Imagick::queryFormats — Returns formats supported by Imagick

Description

array Imagick::queryFormats ([ string $pattern = "*" ] )
Warning

This function is currently not documented; only its argument list is available.

Returns formats supported by Imagick.

Parameters

pattern

Return Values

Returns an array containing the formats supported by Imagick. Throw an ImagickException on error.

Imagick::queryFonts
Imagick::radialBlurImage
The Imagick class


Radial blurs an image

Imagick::queryFormats
Imagick::raiseImage
The Imagick class
PHP Manual

Imagick::radialBlurImage

(PECL imagick 2.0.0)

Imagick::radialBlurImage — Radial blurs an image

Description

bool Imagick::radialBlurImage ( float $angle [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Radial blurs an image.

Parameters

angle

channel

Return Values

Returns TRUE on success.

Imagick::queryFormats
Imagick::raiseImage
The Imagick class


Creates a simulated 3d button-like effect

Imagick::radialBlurImage
Imagick::randomThresholdImage
The Imagick class
PHP Manual

Imagick::raiseImage

(PECL imagick 2.0.0)

Imagick::raiseImage — Creates a simulated 3d button-like effect

Description

bool Imagick::raiseImage ( int $width , int $height , int $x , int $y , bool $raise )
Warning

This function is currently not documented; only its argument list is available.

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.

Parameters

width

height

x

y

raise

Return Values

Returns TRUE on success.

Imagick::radialBlurImage
Imagick::randomThresholdImage
The Imagick class


Creates a high-contrast, two-color image

Imagick::raiseImage
Imagick::readImage
The Imagick class
PHP Manual

Imagick::randomThresholdImage

(PECL imagick 2.0.0)

Imagick::randomThresholdImage — Creates a high-contrast, two-color image

Description

bool Imagick::randomThresholdImage ( float $low , float $high [, int $channel = Imagick::CHANNEL_ALL ] )

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

low

The low point

high

The high point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Returns TRUE on success.

Imagick::raiseImage
Imagick::readImage
The Imagick class


Reads image from filename

Imagick::randomThresholdImage
Imagick::readImageBlob
The Imagick class
PHP Manual

Imagick::readImage

(PECL imagick 0.9.0-0.9.9)

Imagick::readImage — Reads image from filename

Description

bool Imagick::readImage ( string $filename )
Warning

This function is currently not documented; only its argument list is available.

Reads image from filename

Parameters

filename

Return Values

Returns TRUE on success.

Imagick::randomThresholdImage
Imagick::readImageBlob
The Imagick class


Reads image from a binary string

Imagick::readImage
Imagick::readImageFile
The Imagick class
PHP Manual

Imagick::readImageBlob

(PECL imagick 2.0.0)

Imagick::readImageBlob — Reads image from a binary string

Description

bool Imagick::readImageBlob ( string $image [, string $filename ] )
Warning

This function is currently not documented; only its argument list is available.

Reads image from a binary string

Parameters

image

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::readImage
Imagick::readImageFile
The Imagick class


Reads image from open filehandle

Imagick::readImageBlob
Imagick::recolorImage
The Imagick class
PHP Manual

Imagick::readImageFile

(PECL imagick 2.0.0)

Imagick::readImageFile — Reads image from open filehandle

Description

bool Imagick::readImageFile ( resource $filehandle [, string $fileName ] )
Warning

This function is currently not documented; only its argument list is available.

Reads image from open filehandle

Parameters

filehandle

fileName

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::readImageBlob
Imagick::recolorImage
The Imagick class


Recolors image

Imagick::readImageFile
Imagick::reduceNoiseImage
The Imagick class
PHP Manual

Imagick::recolorImage

(No version information available, might only be in SVN)

Imagick::recolorImage — Recolors image

Description

bool Imagick::animateImages ( array $matrix )

Translate, scale, shear, or rotate image colors. This method supports variable sized matrices but normally 5x5 matrix is used for RGBA and 6x6 is used for CMYK. The last row should contain the normalized values. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

matrix

The matrix containing the color values

Return Values

Returns TRUE on success.

See Also

  • Imagick::displayImage() - Displays an image

Imagick::readImageFile
Imagick::reduceNoiseImage
The Imagick class


Smooths the contours of an image

Imagick::recolorImage
Imagick::remapImage
The Imagick class
PHP Manual

Imagick::reduceNoiseImage

(PECL imagick 2.0.0)

Imagick::reduceNoiseImage — Smooths the contours of an image

Description

bool Imagick::reduceNoiseImage ( float $radius )
Warning

This function is currently not documented; only its argument list is available.

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and Imagick::reduceNoiseImage() selects a suitable radius for you.

Parameters

radius

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::recolorImage
Imagick::remapImage
The Imagick class


Removes an image from the image list

Imagick::remapImage
Imagick::removeImageProfile
The Imagick class
PHP Manual

Imagick::removeImage

(PECL imagick 2.0.0)

Imagick::removeImage — Removes an image from the image list

Description

bool Imagick::removeImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Removes an image from the image list.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::remapImage
Imagick::removeImageProfile
The Imagick class


Removes the named image profile and returns it

Imagick::removeImage
Imagick::render
The Imagick class
PHP Manual

Imagick::removeImageProfile

(PECL imagick 2.0.0)

Imagick::removeImageProfile — Removes the named image profile and returns it

Description

string Imagick::removeImageProfile ( string $name )
Warning

This function is currently not documented; only its argument list is available.

Removes the named image profile and returns it.

Parameters

name

Return Values

Returns a string containing the profile of the image. Throw an ImagickException on error.

Imagick::removeImage
Imagick::render
The Imagick class


Renders all preceding drawing commands

Imagick::removeImageProfile
Imagick::resampleImage
The Imagick class
PHP Manual

Imagick::render

(PECL imagick 2.0.0)

Imagick::render — Renders all preceding drawing commands

Description

bool Imagick::render ( void )
Warning

This function is currently not documented; only its argument list is available.

Renders all preceding drawing commands.

Return Values

Returns TRUE on success.

Imagick::removeImageProfile
Imagick::resampleImage
The Imagick class


Resample image to desired resolution

Imagick::render
Imagick::resetImagePage
The Imagick class
PHP Manual

Imagick::resampleImage

(PECL imagick 2.0.0)

Imagick::resampleImage — Resample image to desired resolution

Description

bool Imagick::resampleImage ( float $x_resolution , float $y_resolution , int $filter , float $blur )
Warning

This function is currently not documented; only its argument list is available.

Resample image to desired resolution.

Parameters

x_resolution

y_resolution

filter

blur

Return Values

Returns TRUE on success.

Imagick::render
Imagick::resetImagePage
The Imagick class


Reset image page

Imagick::resampleImage
Imagick::resizeImage
The Imagick class
PHP Manual

Imagick::resetImagePage

(No version information available, might only be in SVN)

Imagick::resetImagePage — Reset image page

Description

bool Imagick::resetImagePage ( string $page )

The page definition as a string. The string is in format WxH+x+y. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

page

The page definition. For example 7168x5147+0+0

Return Values

Returns TRUE on success.

Imagick::resampleImage
Imagick::resizeImage
The Imagick class


Scales an image

Imagick::resetImagePage
Imagick::rollImage
The Imagick class
PHP Manual

Imagick::resizeImage

(PECL imagick 2.0.0)

Imagick::resizeImage — Scales an image

Description

bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )
Warning

This function is currently not documented; only its argument list is available.

Scales an image to the desired dimensions with a filter.

Note: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parameters

columns

Width of the image

rows

Height of the image

filter

Refer to the list of filter constants.

blur

The blur factor where > 1 is blurry, < 1 is sharp.

bestfit

Optional fit parameter.

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

Imagick::resetImagePage
Imagick::rollImage
The Imagick class


Offsets an image

Imagick::resizeImage
Imagick::rotateImage
The Imagick class
PHP Manual

Imagick::rollImage

(PECL imagick 2.0.0)

Imagick::rollImage — Offsets an image

Description

bool Imagick::rollImage ( int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Offsets an image as defined by x and y.

Parameters

x

The X offset.

y

The Y offset.

Return Values

Returns TRUE on success.

Imagick::resizeImage
Imagick::rotateImage
The Imagick class


Rotates an image

Imagick::rollImage
Imagick::roundCorners
The Imagick class
PHP Manual

Imagick::rotateImage

(PECL imagick 2.0.0)

Imagick::rotateImage — Rotates an image

Description

bool Imagick::rotateImage ( mixed $background , float $degrees )
Warning

This function is currently not documented; only its argument list is available.

Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.

Parameters

background

The background color

degrees

The number of degrees to rotate the image

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Imagick::rollImage
Imagick::roundCorners
The Imagick class


Rounds image corners

Imagick::rotateImage
Imagick::sampleImage
The Imagick class
PHP Manual

Imagick::roundCorners

(PECL imagick 2.0.0)

Imagick::roundCorners — Rounds image corners

Description

bool Imagick::roundCorners ( float $x_rounding , float $y_rounding [, float $stroke_width = 10 [, float $displace = 5 [, float $size_correction = -6 ]]] )
Warning

This function is currently not documented; only its argument list is available.

Rounds image corners. The first two parameters control the amount of rounding and the three last parameters can be used to fine-tune the rounding process. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

x_rounding

x rounding

y_rounding

y rounding

stroke_width

stroke width

displace

image displace

size_correction

size correction

Examples

Example #1 Using Imagick::roundCorners():

Rounds the image corners

<?php

$image = new Imagick();
$image->newPseudoImage(100, 100, "magick:rose");
$image->setImageFormat("png");

$image->roundCorners(5,3);
$image->writeImage("rounded.png");
?>

Return Values

Returns TRUE on success.

Imagick::rotateImage
Imagick::sampleImage
The Imagick class


Scales an image with pixel sampling

Imagick::roundCorners
Imagick::scaleImage
The Imagick class
PHP Manual

Imagick::sampleImage

(PECL imagick 2.0.0)

Imagick::sampleImage — Scales an image with pixel sampling

Description

bool Imagick::sampleImage ( int $columns , int $rows )
Warning

This function is currently not documented; only its argument list is available.

Scales an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this method does not introduce any additional color into the scaled image.

Parameters

columns

rows

Return Values

Returns TRUE on success.

Imagick::roundCorners
Imagick::scaleImage
The Imagick class


Scales the size of an image

Imagick::sampleImage
Imagick::segmentImage
The Imagick class
PHP Manual

Imagick::scaleImage

(PECL imagick 2.0.0)

Imagick::scaleImage — Scales the size of an image

Description

bool Imagick::scaleImage ( int $cols , int $rows [, bool $bestfit = false ] )
Warning

This function is currently not documented; only its argument list is available.

Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param.

Note: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parameters

cols

rows

bestfit

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

Imagick::sampleImage
Imagick::segmentImage
The Imagick class


Separates a channel from the image

Imagick::segmentImage
Imagick::sepiaToneImage
The Imagick class
PHP Manual

Imagick::separateImageChannel

(PECL imagick 2.0.0)

Imagick::separateImageChannel — Separates a channel from the image

Description

bool Imagick::separateImageChannel ( int $channel )
Warning

This function is currently not documented; only its argument list is available.

Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.

Parameters

channel

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::segmentImage
Imagick::sepiaToneImage
The Imagick class


Sepia tones an image

Imagick::separateImageChannel
Imagick::setBackgroundColor
The Imagick class
PHP Manual

Imagick::sepiaToneImage

(PECL imagick 2.0.0)

Imagick::sepiaToneImage — Sepia tones an image

Description

bool Imagick::sepiaToneImage ( float $threshold )
Warning

This function is currently not documented; only its argument list is available.

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by sepia toning. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the sepia toning. A threshold of 80 is a good starting point for a reasonable tone.

Parameters

threshold

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::separateImageChannel
Imagick::setBackgroundColor
The Imagick class


Sets the object's default background color

Imagick::sepiaToneImage
Imagick::setCompression
The Imagick class
PHP Manual

Imagick::setBackgroundColor

(PECL imagick 2.0.0)

Imagick::setBackgroundColor — Sets the object's default background color

Description

bool Imagick::setBackgroundColor ( mixed $background )
Warning

This function is currently not documented; only its argument list is available.

Sets the object's default background color.

Parameters

background

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

Imagick::sepiaToneImage
Imagick::setCompression
The Imagick class


Sets the object's default compression type

Imagick::setBackgroundColor
Imagick::setCompressionQuality
The Imagick class
PHP Manual

Imagick::setCompression

(PECL imagick 2.0.0)

Imagick::setCompression — Sets the object's default compression type

Description

bool Imagick::setCompression ( int $compression )
Warning

This function is currently not documented; only its argument list is available.

Sets the object's default compression type

Parameters

compression

Return Values

Returns TRUE on success.

Imagick::setBackgroundColor
Imagick::setCompressionQuality
The Imagick class


Sets the object's default compression quality

Imagick::setCompression
Imagick::setFilename
The Imagick class
PHP Manual

Imagick::setCompressionQuality

(PECL imagick 0.9.10-0.9.9)

Imagick::setCompressionQuality — Sets the object's default compression quality

Description

bool Imagick::setCompressionQuality ( int $quality )
Warning

This function is currently not documented; only its argument list is available.

Sets the object's default compression quality.

Parameters

quality

Return Values

Returns TRUE on success.

Imagick::setCompression
Imagick::setFilename
The Imagick class


Sets the filename before you read or write the image

Imagick::setCompressionQuality
Imagick::setFirstIterator
The Imagick class
PHP Manual

Imagick::setFilename

(PECL imagick 2.0.0)

Imagick::setFilename — Sets the filename before you read or write the image

Description

bool Imagick::setFilename ( string $filename )
Warning

This function is currently not documented; only its argument list is available.

Sets the filename before you read or write an image file.

Parameters

filename

Return Values

Returns TRUE on success.

Imagick::setCompressionQuality
Imagick::setFirstIterator
The Imagick class


Sets the Imagick iterator to the first image

Imagick::setFilename
Imagick::setFont
The Imagick class
PHP Manual

Imagick::setFirstIterator

(PECL imagick 2.0.0)

Imagick::setFirstIterator — Sets the Imagick iterator to the first image

Description

bool Imagick::setFirstIterator ( void )
Warning

This function is currently not documented; only its argument list is available.

Sets the Imagick iterator to the first image.

Return Values

Returns TRUE on success.

Imagick::setFilename
Imagick::setFont
The Imagick class


Sets font

Imagick::setFirstIterator
Imagick::setFormat
The Imagick class
PHP Manual

Imagick::setFont

(PECL imagick 2.1.0)

Imagick::setFont — Sets font

Description

bool Imagick::setFont ( string $font )

Sets object's font property. This method can be used for example to set font for caption: pseudo-format. The font needs to be configured in ImageMagick confiration or a file by the name of font must exist. This method should not be confused with ImagickDraw::setFont() which sets the font for a specific ImagickDraw object. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Parameters

font

Font name or a filename

Return Values

Returns TRUE on success.

See Also

  • Imagick::getFont() - Gets font
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
  • ImagickDraw::getFont() - Returns the font

Examples

Example #1 A Imagick::setFont() example

Example of using Imagick::setFont

<?php
/* Create new imagick object */
$im = new Imagick();

/* Set the font for the object */
$im->setFont("example.ttf");

/* Create new caption */
$im->newPseudoImage(100, 100, "caption:Hello");

/* Do something with the image */
?>

Imagick::setFirstIterator
Imagick::setFormat
The Imagick class


Sets the format of the Imagick object

Imagick::setFont
Imagick::setGravity
The Imagick class
PHP Manual

Imagick::setFormat

(PECL imagick 2.0.0)

Imagick::setFormat — Sets the format of the Imagick object

Description

bool Imagick::setFormat ( string $format )
Warning

This function is currently not documented; only its argument list is available.

Sets the format of the Imagick object.

Parameters

format

Return Values

Returns TRUE on success.

Imagick::setFont
Imagick::setGravity
The Imagick class


Sets the gravity

Imagick::setFormat
Imagick::setImage
The Imagick class
PHP Manual

Imagick::setGravity

(No version information available, might only be in SVN)

Imagick::setGravity — Sets the gravity

Description

bool Imagick::setGravity ( int $gravity )

Sets the global gravity property for the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

Parameters

gravity

The gravity property. Refer to the list of gravity constants.

Return Values

No value is returned.

Imagick::setFormat
Imagick::setImage
The Imagick class


Replaces image in the object

Imagick::setGravity
Imagick::setImageAlphaChannel
The Imagick class
PHP Manual

Imagick::setImage

(PECL imagick 2.0.0)

Imagick::setImage — Replaces image in the object

Description

bool Imagick::setImage ( Imagick $replace )
Warning

This function is currently not documented; only its argument list is available.

Replaces the current image sequence with the image from replace object.

Parameters

replace

The replace Imagick object

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 A Imagick::setImage() example

An example of using Imagick::setImage()

<?php
/* Create the objects */
$image = new Imagick('source.jpg');
$replace = new Imagick('replace.jpg');

/* source.jpg is replaced with replace.jpg */
$image->setImage($replace);

/* output the image */
header('Content-type: image/jpeg');
echo $image;

?>

Imagick::setGravity
Imagick::setImageAlphaChannel
The Imagick class


Sets image alpha channel

Imagick::setImage
Imagick::setImageBackgroundColor
The Imagick class
PHP Manual

Imagick::setImageAlphaChannel

(No version information available, might only be in SVN)

Imagick::setImageAlphaChannel — Sets image alpha channel

Description

bool Imagick::setImageAlphaChannel ( int $mode )

Activate or deactivate image alpha channel. The mode is one of the Imagick::ALPHACHANNEL_* constants. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

Parameters

mode

One of the Imagick::ALPHACHANNEL_* constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

See Also

  • Imagick::setImageMatte() - Sets the image matte channel

Imagick::setImage
Imagick::setImageBackgroundColor
The Imagick class


Sets the image background color

Imagick::setImageAlphaChannel
Imagick::setImageBias
The Imagick class
PHP Manual

Imagick::setImageBackgroundColor

(PECL imagick 2.0.0)

Imagick::setImageBackgroundColor — Sets the image background color

Description

bool Imagick::setImageBackgroundColor ( mixed $background )
Warning

This function is currently not documented; only its argument list is available.

Sets the image background color.

Parameters

background

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

Imagick::setImageAlphaChannel
Imagick::setImageBias
The Imagick class


Sets the image bias for any method that convolves an image

Imagick::setImageBackgroundColor
Imagick::setImageBluePrimary
The Imagick class
PHP Manual

Imagick::setImageBias

(PECL imagick 2.0.0)

Imagick::setImageBias — Sets the image bias for any method that convolves an image

Description

bool Imagick::setImageBias ( float $bias )
Warning

This function is currently not documented; only its argument list is available.

Sets the image bias for any method that convolves an image (e.g. Imagick::ConvolveImage()).

Parameters

bias

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageBackgroundColor
Imagick::setImageBluePrimary
The Imagick class


Sets the image chromaticity blue primary point

Imagick::setImageBias
Imagick::setImageBorderColor
The Imagick class
PHP Manual

Imagick::setImageBluePrimary

(PECL imagick 2.0.0)

Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point

Description

bool Imagick::setImageBluePrimary ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Sets the image chromaticity blue primary point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageBias
Imagick::setImageBorderColor
The Imagick class


Sets the image border color

Imagick::setImageBluePrimary
Imagick::setImageChannelDepth
The Imagick class
PHP Manual

Imagick::setImageBorderColor

(PECL imagick 2.0.0)

Imagick::setImageBorderColor — Sets the image border color

Description

bool Imagick::setImageBorderColor ( mixed $border )
Warning

This function is currently not documented; only its argument list is available.

Sets the image border color.

Parameters

border

The border color

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

Imagick::setImageBluePrimary
Imagick::setImageChannelDepth
The Imagick class


Sets the depth of a particular image channel

Imagick::setImageBorderColor
Imagick::setImageClipMask
The Imagick class
PHP Manual

Imagick::setImageChannelDepth

(PECL imagick 2.0.0)

Imagick::setImageChannelDepth — Sets the depth of a particular image channel

Description

bool Imagick::setImageChannelDepth ( int $channel , int $depth )
Warning

This function is currently not documented; only its argument list is available.

Sets the depth of a particular image channel.

Parameters

channel

depth

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageBorderColor
Imagick::setImageClipMask
The Imagick class


Sets image clip mask

Imagick::setImageChannelDepth
Imagick::setImageColormapColor
The Imagick class
PHP Manual

Imagick::setImageClipMask

(No version information available, might only be in SVN)

Imagick::setImageClipMask — Sets image clip mask

Description

bool Imagick::setImageClipMask ( Imagick $clip_mask )

Sets image clip mask from another Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

clip_mask

The Imagick object containing the clip mask

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageChannelDepth
Imagick::setImageColormapColor
The Imagick class


Sets the color of the specified colormap index

Imagick::setImageClipMask
Imagick::setImageColorspace
The Imagick class
PHP Manual

Imagick::setImageColormapColor

(PECL imagick 2.0.0)

Imagick::setImageColormapColor — Sets the color of the specified colormap index

Description

bool Imagick::setImageColormapColor ( int $index , ImagickPixel $color )
Warning

This function is currently not documented; only its argument list is available.

Sets the color of the specified colormap index.

Parameters

index

color

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageClipMask
Imagick::setImageColorspace
The Imagick class


Sets the image colorspace

Imagick::setImageColormapColor
Imagick::setImageCompose
The Imagick class
PHP Manual

Imagick::setImageColorspace

(PECL imagick 2.0.0)

Imagick::setImageColorspace — Sets the image colorspace

Description

bool Imagick::setImageColorspace ( int $colorspace )
Warning

This function is currently not documented; only its argument list is available.

Sets the image colorspace.

Parameters

colorspace

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageColormapColor
Imagick::setImageCompose
The Imagick class


Sets the image composite operator

Imagick::setImageColorspace
Imagick::setImageCompression
The Imagick class
PHP Manual

Imagick::setImageCompose

(PECL imagick 2.0.0)

Imagick::setImageCompose — Sets the image composite operator

Description

bool Imagick::setImageCompose ( int $compose )
Warning

This function is currently not documented; only its argument list is available.

Sets the image composite operator, useful for specifying how to composite the image thumbnail when using the Imagick::montageImage() method.

Parameters

compose

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageColorspace
Imagick::setImageCompression
The Imagick class


Sets the image compression

Imagick::setImageCompose
Imagick::setImageCompressionQuality
The Imagick class
PHP Manual

Imagick::setImageCompression

(PECL imagick 2.0.0)

Imagick::setImageCompression — Sets the image compression

Description

bool Imagick::setImageCompression ( int $compression )

Parameters

compression

One of the COMPRESSION constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageCompose
Imagick::setImageCompressionQuality
The Imagick class


Sets the image compression quality

Imagick::setImageCompression
Imagick::setImageDelay
The Imagick class
PHP Manual

Imagick::setImageCompressionQuality

(No version information available, might only be in SVN)

Imagick::setImageCompressionQuality — Sets the image compression quality

Description

bool Imagick::setImageCompressionQuality ( int $quality )

Sets the image compression quality.

Parameters

quality

The image compression quality as an integer

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageCompression
Imagick::setImageDelay
The Imagick class


Sets the image delay

Imagick::setImageCompressionQuality
Imagick::setImageDepth
The Imagick class
PHP Manual

Imagick::setImageDelay

(PECL imagick 2.0.0)

Imagick::setImageDelay — Sets the image delay

Description

bool Imagick::setImageDelay ( int $delay )
Warning

This function is currently not documented; only its argument list is available.

Sets the image delay.

Parameters

delay

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageCompressionQuality
Imagick::setImageDepth
The Imagick class


Sets the image depth

Imagick::setImageDelay
Imagick::setImageDispose
The Imagick class
PHP Manual

Imagick::setImageDepth

(PECL imagick 2.0.0)

Imagick::setImageDepth — Sets the image depth

Description

bool Imagick::setImageDepth ( int $depth )
Warning

This function is currently not documented; only its argument list is available.

Sets the image depth.

Parameters

depth

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageDelay
Imagick::setImageDispose
The Imagick class


Sets the image disposal method

Imagick::setImageDepth
Imagick::setImageExtent
The Imagick class
PHP Manual

Imagick::setImageDispose

(PECL imagick 2.0.0)

Imagick::setImageDispose — Sets the image disposal method

Description

bool Imagick::setImageDispose ( int $dispose )
Warning

This function is currently not documented; only its argument list is available.

Sets the image disposal method.

Parameters

dispose

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageDepth
Imagick::setImageExtent
The Imagick class


Sets the image size

Imagick::setImageDispose
Imagick::setImageFilename
The Imagick class
PHP Manual

Imagick::setImageExtent

(PECL imagick 2.0.0)

Imagick::setImageExtent — Sets the image size

Description

bool Imagick::setImageExtent ( int $columns , int $rows )
Warning

This function is currently not documented; only its argument list is available.

Sets the image size (i.e. columns & rows).

Parameters

columns

rows

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageDispose
Imagick::setImageFilename
The Imagick class


Sets the filename of a particular image

Imagick::setImageExtent
Imagick::setImageFormat
The Imagick class
PHP Manual

Imagick::setImageFilename

(PECL imagick 2.0.0)

Imagick::setImageFilename — Sets the filename of a particular image

Description

bool Imagick::setImageFilename ( string $filename )
Warning

This function is currently not documented; only its argument list is available.

Sets the filename of a particular image in a sequence.

Parameters

filename

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageExtent
Imagick::setImageFormat
The Imagick class


Sets the format of a particular image

Imagick::setImageFilename
Imagick::setImageGamma
The Imagick class
PHP Manual

Imagick::setImageFormat

(PECL imagick 2.0.0)

Imagick::setImageFormat — Sets the format of a particular image

Description

bool Imagick::setImageFormat ( string $format )
Warning

This function is currently not documented; only its argument list is available.

Sets the format of a particular image in a sequence.

Parameters

format

String presentation of the image format. Format support depends on the ImageMagick installation.

Return Values

Returns TRUE on success.

Imagick::setImageFilename
Imagick::setImageGamma
The Imagick class


Sets the image gamma

Imagick::setImageFormat
Imagick::setImageGravity
The Imagick class
PHP Manual

Imagick::setImageGamma

(PECL imagick 2.0.0)

Imagick::setImageGamma — Sets the image gamma

Description

bool Imagick::setImageGamma ( float $gamma )
Warning

This function is currently not documented; only its argument list is available.

Sets the image gamma.

Parameters

gamma

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageFormat
Imagick::setImageGravity
The Imagick class


Sets the image gravity

Imagick::setImageGamma
Imagick::setImageGreenPrimary
The Imagick class
PHP Manual

Imagick::setImageGravity

(No version information available, might only be in SVN)

Imagick::setImageGravity — Sets the image gravity

Description

bool Imagick::setImageGravity ( int $gravity )

Sets the gravity property for the current image. This method can be used to set the gravity property for a single image sequence. This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer.

Parameters

gravity

The gravity property. Refer to the list of gravity constants.

Return Values

No value is returned.

Imagick::setImageGamma
Imagick::setImageGreenPrimary
The Imagick class


Sets the image chromaticity green primary point

Imagick::setImageGravity
Imagick::setImageIndex
The Imagick class
PHP Manual

Imagick::setImageGreenPrimary

(PECL imagick 2.0.0)

Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point

Description

bool Imagick::setImageGreenPrimary ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Sets the image chromaticity green primary point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageGravity
Imagick::setImageIndex
The Imagick class


Set the iterator position

Imagick::setImageGreenPrimary
Imagick::setImageInterlaceScheme
The Imagick class
PHP Manual

Imagick::setImageIndex

(PECL imagick 2.0.0)

Imagick::setImageIndex — Set the iterator position

Description

bool Imagick::setImageIndex ( int $index )
Warning

This function is currently not documented; only its argument list is available.

Set the iterator to the position in the image list specified with the index parameter.

This method has been deprecated. See Imagick::setIteratorIndex

Parameters

index

The position to set the iterator to

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageGreenPrimary
Imagick::setImageInterlaceScheme
The Imagick class


Sets the image compression

Imagick::setImageIndex
Imagick::setImageInterpolateMethod
The Imagick class
PHP Manual

Imagick::setImageInterlaceScheme

(PECL imagick 2.0.0)

Imagick::setImageInterlaceScheme — Sets the image compression

Description

bool Imagick::setImageInterlaceScheme ( int $interlace_scheme )
Warning

This function is currently not documented; only its argument list is available.

Sets the image compression.

Parameters

interlace_scheme

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageIndex
Imagick::setImageInterpolateMethod
The Imagick class


Sets the image interpolate pixel method

Imagick::setImageInterlaceScheme
Imagick::setImageIterations
The Imagick class
PHP Manual

Imagick::setImageInterpolateMethod

(PECL imagick 2.0.0)

Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method

Description

bool Imagick::setImageInterpolateMethod ( int $method )

Sets the image interpolate pixel method.

Parameters

method

The method is one of the Imagick::INTERPOLATE_* constants

Return Values

Returns TRUE on success.

Imagick::setImageInterlaceScheme
Imagick::setImageIterations
The Imagick class


Sets the image iterations

Imagick::setImageInterpolateMethod
Imagick::setImageMatte
The Imagick class
PHP Manual

Imagick::setImageIterations

(PECL imagick 2.0.0)

Imagick::setImageIterations — Sets the image iterations

Description

bool Imagick::setImageIterations ( int $iterations )
Warning

This function is currently not documented; only its argument list is available.

Sets the image iterations.

Parameters

iterations

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageInterpolateMethod
Imagick::setImageMatte
The Imagick class


Sets the image matte channel

Imagick::setImageIterations
Imagick::setImageMatteColor
The Imagick class
PHP Manual

Imagick::setImageMatte

(PECL imagick 2.0.0)

Imagick::setImageMatte — Sets the image matte channel

Description

bool Imagick::setImageMatte ( bool $matte )

Sets the image matte channel. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

matte

True activates the matte channel and false disables it.

Return Values

Returns TRUE on success.

Imagick::setImageIterations
Imagick::setImageMatteColor
The Imagick class


Sets the image matte color

Imagick::setImageMatte
Imagick::setImageOpacity
The Imagick class
PHP Manual

Imagick::setImageMatteColor

(PECL imagick 2.0.0)

Imagick::setImageMatteColor — Sets the image matte color

Description

bool Imagick::setImageMatteColor ( mixed $matte )
Warning

This function is currently not documented; only its argument list is available.

Sets the image matte color.

Parameters

matte

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

Imagick::setImageMatte
Imagick::setImageOpacity
The Imagick class


Sets the image opacity level

Imagick::setImageMatteColor
Imagick::setImageOrientation
The Imagick class
PHP Manual

Imagick::setImageOpacity

(PECL imagick 2.0.0)

Imagick::setImageOpacity — Sets the image opacity level

Description

bool Imagick::setImageOpacity ( float $opacity )

Sets the image to the specified opacity level. This method is available if Imagick has been compiled against ImageMagick version 6.3.1 or newer.

Parameters

opacity

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

Return Values

Returns TRUE on success.

Examples

Example #1 A Imagick::setImageOpacity() example

An example of using Imagick::setImageOpacity()

<?php
/* Create the object */
$image = new Imagick('source.png');

/* Set the opacity */
$image->setImageOpacity(0.7);

/* output the image */
header('Content-type: image/png');
echo $image;

?>

Imagick::setImageMatteColor
Imagick::setImageOrientation
The Imagick class


Sets the image orientation

Imagick::setImageOpacity
Imagick::setImagePage
The Imagick class
PHP Manual

Imagick::setImageOrientation

(PECL imagick 2.0.0)

Imagick::setImageOrientation — Sets the image orientation

Description

bool Imagick::setImageOrientation ( int $orientation )

Sets the image orientation.

Parameters

orientation

One of the orientation constants

Return Values

Returns TRUE on success.

Imagick::setImageOpacity
Imagick::setImagePage
The Imagick class


Sets the page geometry of the image

Imagick::setImageOrientation
Imagick::setImageProfile
The Imagick class
PHP Manual

Imagick::setImagePage

(PECL imagick 2.0.0)

Imagick::setImagePage — Sets the page geometry of the image

Description

bool Imagick::setImagePage ( int $width , int $height , int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Sets the page geometry of the image.

Parameters

width

height

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageOrientation
Imagick::setImageProfile
The Imagick class


Adds a named profile to the Imagick object

Imagick::setImagePage
Imagick::setImageProperty
The Imagick class
PHP Manual

Imagick::setImageProfile

(PECL imagick 2.0.0)

Imagick::setImageProfile — Adds a named profile to the Imagick object

Description

bool Imagick::setImageProfile ( string $name , string $profile )
Warning

This function is currently not documented; only its argument list is available.

Adds a named profile to the Imagick object. If a profile with the same name already exists, it is replaced. This method differs from the Imagick::ProfileImage() method in that it does not apply any CMS color profiles.

Parameters

name

profile

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImagePage
Imagick::setImageProperty
The Imagick class


Sets an image property

Imagick::setImageProfile
Imagick::setImageRedPrimary
The Imagick class
PHP Manual

Imagick::setImageProperty

(PECL imagick 2.0.0)

Imagick::setImageProperty — Sets an image property

Description

bool Imagick::setImageProperty ( string $name , string $value )

Sets a named property to the image. This method is available if Imagick has been compiled against ImageMagick version 6.3.2 or newer.

Parameters

name

value

Examples

Example #1 Using Imagick::setImageProperty():

Setting and getting image properties

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");

$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>

See Also

  • Imagick::getImageProperty() - Returns the named image property

Return Values

Returns TRUE on success.

Imagick::setImageProfile
Imagick::setImageRedPrimary
The Imagick class


Sets the image chromaticity red primary point

Imagick::setImageProperty
Imagick::setImageRenderingIntent
The Imagick class
PHP Manual

Imagick::setImageRedPrimary

(PECL imagick 2.0.0)

Imagick::setImageRedPrimary — Sets the image chromaticity red primary point

Description

bool Imagick::setImageRedPrimary ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Sets the image chromaticity red primary point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageProperty
Imagick::setImageRenderingIntent
The Imagick class


Sets the image rendering intent

Imagick::setImageRedPrimary
Imagick::setImageResolution
The Imagick class
PHP Manual

Imagick::setImageRenderingIntent

(PECL imagick 2.0.0)

Imagick::setImageRenderingIntent — Sets the image rendering intent

Description

bool Imagick::setImageRenderingIntent ( int $rendering_intent )
Warning

This function is currently not documented; only its argument list is available.

Sets the image rendering intent.

Parameters

rendering_intent

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageRedPrimary
Imagick::setImageResolution
The Imagick class


Sets the image resolution

Imagick::setImageRenderingIntent
Imagick::setImageScene
The Imagick class
PHP Manual

Imagick::setImageResolution

(PECL imagick 2.0.0)

Imagick::setImageResolution — Sets the image resolution

Description

bool Imagick::setImageResolution ( float $x_resolution , float $y_resolution )
Warning

This function is currently not documented; only its argument list is available.

Sets the image resolution.

Parameters

x_resolution

y_resolution

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageRenderingIntent
Imagick::setImageScene
The Imagick class


Sets the image scene

Imagick::setImageResolution
Imagick::setImageTicksPerSecond
The Imagick class
PHP Manual

Imagick::setImageScene

(PECL imagick 2.0.0)

Imagick::setImageScene — Sets the image scene

Description

bool Imagick::setImageScene ( int $scene )
Warning

This function is currently not documented; only its argument list is available.

Sets the image scene.

Parameters

scene

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageResolution
Imagick::setImageTicksPerSecond
The Imagick class


Sets the image ticks-per-second

Imagick::setImageScene
Imagick::setImageType
The Imagick class
PHP Manual

Imagick::setImageTicksPerSecond

(PECL imagick 2.0.0)

Imagick::setImageTicksPerSecond — Sets the image ticks-per-second

Description

bool Imagick::setImageTicksPerSecond ( int $ticks_per-second )
Warning

This function is currently not documented; only its argument list is available.

Sets the image ticks-per-second.

Parameters

ticks_per-second

Return Values

Returns TRUE on success.

Imagick::setImageScene
Imagick::setImageType
The Imagick class


Sets the image type

Imagick::setImageTicksPerSecond
Imagick::setImageUnits
The Imagick class
PHP Manual

Imagick::setImageType

(PECL imagick 2.0.0)

Imagick::setImageType — Sets the image type

Description

bool Imagick::setImageType ( int $image_type )
Warning

This function is currently not documented; only its argument list is available.

Sets the image type.

Parameters

image_type

Return Values

Returns TRUE on success.

Imagick::setImageTicksPerSecond
Imagick::setImageUnits
The Imagick class


Sets the image units of resolution

Imagick::setImageType
Imagick::setImageVirtualPixelMethod
The Imagick class
PHP Manual

Imagick::setImageUnits

(PECL imagick 2.0.0)

Imagick::setImageUnits — Sets the image units of resolution

Description

bool Imagick::setImageUnits ( int $units )
Warning

This function is currently not documented; only its argument list is available.

Sets the image units of resolution.

Parameters

units

Return Values

Returns TRUE on success.

Imagick::setImageType
Imagick::setImageVirtualPixelMethod
The Imagick class


Sets the image virtual pixel method

Imagick::setImageUnits
Imagick::setImageWhitePoint
The Imagick class
PHP Manual

Imagick::setImageVirtualPixelMethod

(PECL imagick 2.0.0)

Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method

Description

bool Imagick::setImageVirtualPixelMethod ( int $method )
Warning

This function is currently not documented; only its argument list is available.

Sets the image virtual pixel method.

Parameters

method

Return Values

Returns TRUE on success.

Imagick::setImageUnits
Imagick::setImageWhitePoint
The Imagick class


Sets the image chromaticity white point

Imagick::setImageVirtualPixelMethod
Imagick::setInterlaceScheme
The Imagick class
PHP Manual

Imagick::setImageWhitePoint

(PECL imagick 2.0.0)

Imagick::setImageWhitePoint — Sets the image chromaticity white point

Description

bool Imagick::setImageWhitePoint ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Sets the image chromaticity white point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::setImageVirtualPixelMethod
Imagick::setInterlaceScheme
The Imagick class


Sets the image compression

Imagick::setImageWhitePoint
Imagick::setIteratorIndex
The Imagick class
PHP Manual

Imagick::setInterlaceScheme

(PECL imagick 2.0.0)

Imagick::setInterlaceScheme — Sets the image compression

Description

bool Imagick::setInterlaceScheme ( int $interlace_scheme )
Warning

This function is currently not documented; only its argument list is available.

Sets the image compression.

Parameters

interlace_scheme

Return Values

Returns TRUE on success.

Imagick::setImageWhitePoint
Imagick::setIteratorIndex
The Imagick class


Set the iterator position

Imagick::setInterlaceScheme
Imagick::setLastIterator
The Imagick class
PHP Manual

Imagick::setIteratorIndex

(PECL imagick 2.0.0)

Imagick::setIteratorIndex — Set the iterator position

Description

bool Imagick::setIteratorIndex ( int $index )

Set the iterator to the position in the image list specified with the index parameter. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

index

The position to set the iterator to

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::setIteratorIndex():

Create images, set and get the iterator index

<?php
$im = new Imagick();
$im->newImage(100, 100, new ImagickPixel("red"));
$im->newImage(100, 100, new ImagickPixel("green"));
$im->newImage(100, 100, new ImagickPixel("blue"));

$im->setIteratorIndex(1);
echo $im->getIteratorIndex();
?>

See Also

  • Imagick::getIteratorIndex() - Gets the index of the current active image
  • Imagick::getImageIndex() - Gets the index of the current active image
  • Imagick::setImageIndex() - Set the iterator position

Imagick::setInterlaceScheme
Imagick::setLastIterator
The Imagick class


Sets the Imagick iterator to the last image

Imagick::setIteratorIndex
Imagick::setOption
The Imagick class
PHP Manual

Imagick::setLastIterator

(PECL imagick 2.0.1)

Imagick::setLastIterator — Sets the Imagick iterator to the last image

Description

bool Imagick::setLastIterator ( void )
Warning

This function is currently not documented; only its argument list is available.

Sets the Imagick iterator to the last image.

Return Values

Returns TRUE on success.

Imagick::setIteratorIndex
Imagick::setOption
The Imagick class


Set an option

Imagick::setLastIterator
Imagick::setPage
The Imagick class
PHP Manual

Imagick::setOption

(PECL imagick 2.0.0)

Imagick::setOption — Set an option

Description

bool Imagick::setOption ( string $key , string $value )
Warning

This function is currently not documented; only its argument list is available.

Associates one or more options with the wand.

Parameters

key

value

Return Values

Returns TRUE on success.

Imagick::setLastIterator
Imagick::setPage
The Imagick class


Sets the page geometry of the Imagick object

Imagick::setOption
Imagick::setPointSize
The Imagick class
PHP Manual

Imagick::setPage

(PECL imagick 2.0.0)

Imagick::setPage — Sets the page geometry of the Imagick object

Description

bool Imagick::setPage ( int $width , int $height , int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Sets the page geometry of the Imagick object.

Parameters

width

height

x

y

Return Values

Returns TRUE on success.

Imagick::setOption
Imagick::setPointSize
The Imagick class


Sets point size

Imagick::setPage
Imagick::setResolution
The Imagick class
PHP Manual

Imagick::setPointSize

(PECL imagick 2.1.0)

Imagick::setPointSize — Sets point size

Description

bool Imagick::setPointSize ( float $point_size )

Sets object's point size property. This method can be used for example to set font size for caption: pseudo-format. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Parameters

point_size

Point size

Return Values

Returns TRUE on success.

See Also

  • Imagick::getPointSize() - Gets point size

Examples

Example #1 A Imagick::setPointSize() example

Example of using Imagick::setPointSize

<?php
/* Create new imagick object */
$im = new Imagick();

/* Set the font for the object */
$im->setFont("example.ttf");

/* Set the point size */
$im->setPointSize(12);

/* Create new caption */
$im->newPseudoImage(100, 100, "caption:Hello");

/* Do something with the image */
?>

Imagick::setPage
Imagick::setResolution
The Imagick class


Sets the image resolution

Imagick::setPointSize
Imagick::setResourceLimit
The Imagick class
PHP Manual

Imagick::setResolution

(PECL imagick 2.0.0)

Imagick::setResolution — Sets the image resolution

Description

bool Imagick::setResolution ( float $x_resolution , float $y_resolution )
Warning

This function is currently not documented; only its argument list is available.

Sets the image resolution.

Parameters

x_resolution

y_resolution

Return Values

Returns TRUE on success.

Imagick::setPointSize
Imagick::setResourceLimit
The Imagick class


Sets the limit for a particular resource in megabytes

Imagick::setResolution
Imagick::setSamplingFactors
The Imagick class
PHP Manual

Imagick::setResourceLimit

(PECL imagick 2.0.0)

Imagick::setResourceLimit — Sets the limit for a particular resource in megabytes

Description

bool Imagick::setResourceLimit ( int $type , int $limit )
Warning

This function is currently not documented; only its argument list is available.

Sets the limit for a particular resource in megabytes.

Parameters

type

limit

Return Values

Returns TRUE on success.

Imagick::setResolution
Imagick::setSamplingFactors
The Imagick class


Sets the image sampling factors

Imagick::setResourceLimit
Imagick::setSize
The Imagick class
PHP Manual

Imagick::setSamplingFactors

(PECL imagick 2.0.0)

Imagick::setSamplingFactors — Sets the image sampling factors

Description

bool Imagick::setSamplingFactors ( array $factors )
Warning

This function is currently not documented; only its argument list is available.

Sets the image sampling factors.

Parameters

factors

Return Values

Returns TRUE on success.

Imagick::setResourceLimit
Imagick::setSize
The Imagick class


Sets the size of the Imagick object

Imagick::setSamplingFactors
Imagick::setSizeOffset
The Imagick class
PHP Manual

Imagick::setSize

(PECL imagick 2.0.0)

Imagick::setSize — Sets the size of the Imagick object

Description

bool Imagick::setSize ( int $columns , int $rows )
Warning

This function is currently not documented; only its argument list is available.

Sets the size of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK.

Parameters

columns

rows

Return Values

Returns TRUE on success.

Imagick::setSamplingFactors
Imagick::setSizeOffset
The Imagick class


Sets the size and offset of the Imagick object

Imagick::setSize
Imagick::setType
The Imagick class
PHP Manual

Imagick::setSizeOffset

(PECL imagick 2.0.0)

Imagick::setSizeOffset — Sets the size and offset of the Imagick object

Description

bool Imagick::setSizeOffset ( int $columns , int $rows , int $offset )
Warning

This function is currently not documented; only its argument list is available.

Sets the size and offset of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

columns

The width in pixels.

rows

The height in pixels.

offset

The image offset.

Return Values

Returns TRUE on success.

Imagick::setSize
Imagick::setType
The Imagick class


Sets the image type attribute

Imagick::setSizeOffset
Imagick::shadeImage
The Imagick class
PHP Manual

Imagick::setType

(PECL imagick 2.0.0)

Imagick::setType — Sets the image type attribute

Description

bool Imagick::setType ( int $image_type )
Warning

This function is currently not documented; only its argument list is available.

Sets the image type attribute.

Parameters

image_type

Return Values

Returns TRUE on success.

Imagick::setSizeOffset
Imagick::shadeImage
The Imagick class


Creates a 3D effect

Imagick::setType
Imagick::shadowImage
The Imagick class
PHP Manual

Imagick::shadeImage

(PECL imagick 2.0.0)

Imagick::shadeImage — Creates a 3D effect

Description

bool Imagick::shadeImage ( bool $gray , float $azimuth , float $elevation )

Shines a distant light on an image to create a three-dimensional effect. You control the positioning of the light with azimuth and elevation; azimuth is measured in degrees off the x axis and elevation is measured in pixels above the Z axis. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

gray

A value other than zero shades the intensity of each pixel.

azimuth

Defines the light source direction.

elevation

Defines the light source direction.

Return Values

Returns TRUE on success.

Imagick::setType
Imagick::shadowImage
The Imagick class


Simulates an image shadow

Imagick::shadeImage
Imagick::sharpenImage
The Imagick class
PHP Manual

Imagick::shadowImage

(PECL imagick 2.0.0)

Imagick::shadowImage — Simulates an image shadow

Description

bool Imagick::shadowImage ( float $opacity , float $sigma , int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Simulates an image shadow.

Parameters

opacity

sigma

x

y

Return Values

Returns TRUE on success.

Imagick::shadeImage
Imagick::sharpenImage
The Imagick class


Sharpens an image

Imagick::shadowImage
Imagick::shaveImage
The Imagick class
PHP Manual

Imagick::sharpenImage

(PECL imagick 2.0.0)

Imagick::sharpenImage — Sharpens an image

Description

bool Imagick::sharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and selects a suitable radius for you.

Parameters

radius

sigma

channel

Return Values

Returns TRUE on success.

Imagick::shadowImage
Imagick::shaveImage
The Imagick class


Shaves pixels from the image edges

Imagick::sharpenImage
Imagick::shearImage
The Imagick class
PHP Manual

Imagick::shaveImage

(PECL imagick 2.0.0)

Imagick::shaveImage — Shaves pixels from the image edges

Description

bool Imagick::shaveImage ( int $columns , int $rows )
Warning

This function is currently not documented; only its argument list is available.

Shaves pixels from the image edges. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.

Parameters

columns

rows

Return Values

Returns TRUE on success.

Imagick::sharpenImage
Imagick::shearImage
The Imagick class


Creating a parallelogram

Imagick::shaveImage
Imagick::sigmoidalContrastImage
The Imagick class
PHP Manual

Imagick::shearImage

(PECL imagick 2.0.0)

Imagick::shearImage — Creating a parallelogram

Description

bool Imagick::shearImage ( mixed $background , float $x_shear , float $y_shear )
Warning

This function is currently not documented; only its argument list is available.

Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

Parameters

background

The background color

x_shear

The number of degrees to shear on the x axis

y_shear

The number of degrees to shear on the y axis

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Imagick::shaveImage
Imagick::sigmoidalContrastImage
The Imagick class


Adjusts the contrast of an image

Imagick::shearImage
Imagick::sketchImage
The Imagick class
PHP Manual

Imagick::sigmoidalContrastImage

(PECL imagick 2.0.0)

Imagick::sigmoidalContrastImage — Adjusts the contrast of an image

Description

bool Imagick::sigmoidalContrastImage ( bool $sharpen , float $alpha , float $beta [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Adjusts the contrast of an image with a non-linear sigmoidal contrast algorithm. Increase the contrast of the image using a sigmoidal transfer function without saturating highlights or shadows. Contrast indicates how much to increase the contrast (0 is none; 3 is typical; 20 is pushing it); mid-point indicates where midtones fall in the resultant image (0 is white; 50 is middle-gray; 100 is black). Set sharpen to TRUE to increase the image contrast otherwise the contrast is reduced.

Parameters

sharpen

alpha

beta

channel

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::shearImage
Imagick::sketchImage
The Imagick class


Simulates a pencil sketch

Imagick::sigmoidalContrastImage
Imagick::solarizeImage
The Imagick class
PHP Manual

Imagick::sketchImage

(PECL imagick 2.0.0)

Imagick::sketchImage — Simulates a pencil sketch

Description

bool Imagick::sketchImage ( float $radius , float $sigma , float $angle )

Simulates a pencil sketch. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::sketchImage() selects a suitable radius for you. Angle gives the angle of the blurring motion. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

Return Values

Returns TRUE on success.

Imagick::sigmoidalContrastImage
Imagick::solarizeImage
The Imagick class


Applies a solarizing effect to the image

Imagick::sketchImage
Imagick::sparseColorImage
The Imagick class
PHP Manual

Imagick::solarizeImage

(PECL imagick 2.0.0)

Imagick::solarizeImage — Applies a solarizing effect to the image

Description

bool Imagick::solarizeImage ( int $threshold )
Warning

This function is currently not documented; only its argument list is available.

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization.

Parameters

threshold

Return Values

Returns TRUE on success.

Imagick::sketchImage
Imagick::sparseColorImage
The Imagick class


Splices a solid color into the image

Imagick::sparseColorImage
Imagick::spreadImage
The Imagick class
PHP Manual

Imagick::spliceImage

(PECL imagick 2.0.0)

Imagick::spliceImage — Splices a solid color into the image

Description

bool Imagick::spliceImage ( int $width , int $height , int $x , int $y )
Warning

This function is currently not documented; only its argument list is available.

Splices a solid color into the image.

Parameters

width

height

x

y

Return Values

Returns TRUE on success.

Imagick::sparseColorImage
Imagick::spreadImage
The Imagick class


Randomly displaces each pixel in a block

Imagick::spliceImage
Imagick::steganoImage
The Imagick class
PHP Manual

Imagick::spreadImage

(PECL imagick 2.0.0)

Imagick::spreadImage — Randomly displaces each pixel in a block

Description

bool Imagick::spreadImage ( float $radius )
Warning

This function is currently not documented; only its argument list is available.

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

Parameters

radius

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::spliceImage
Imagick::steganoImage
The Imagick class


Hides a digital watermark within the image

Imagick::spreadImage
Imagick::stereoImage
The Imagick class
PHP Manual

Imagick::steganoImage

(PECL imagick 2.0.0)

Imagick::steganoImage — Hides a digital watermark within the image

Description

Imagick Imagick::steganoImage ( Imagick $watermark_wand , int $offset )
Warning

This function is currently not documented; only its argument list is available.

Hides a digital watermark within the image. Recover the hidden watermark later to prove that the authenticity of an image. Offset defines the start position within the image to hide the watermark.

Parameters

watermark_wand

offset

Return Values

Returns TRUE on success.

Imagick::spreadImage
Imagick::stereoImage
The Imagick class


Composites two images

Imagick::steganoImage
Imagick::stripImage
The Imagick class
PHP Manual

Imagick::stereoImage

(PECL imagick 2.0.0)

Imagick::stereoImage — Composites two images

Description

bool Imagick::stereoImage ( Imagick $offset_wand )
Warning

This function is currently not documented; only its argument list is available.

Composites two images and produces a single image that is the composite of a left and right image of a stereo pair.

Parameters

offset_wand

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::steganoImage
Imagick::stripImage
The Imagick class


Strips an image of all profiles and comments

Imagick::stereoImage
Imagick::swirlImage
The Imagick class
PHP Manual

Imagick::stripImage

(PECL imagick 2.0.0)

Imagick::stripImage — Strips an image of all profiles and comments

Description

bool Imagick::stripImage ( void )
Warning

This function is currently not documented; only its argument list is available.

Strips an image of all profiles and comments.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::stereoImage
Imagick::swirlImage
The Imagick class


Swirls the pixels about the center of the image

Imagick::stripImage
Imagick::textureImage
The Imagick class
PHP Manual

Imagick::swirlImage

(PECL imagick 2.0.0)

Imagick::swirlImage — Swirls the pixels about the center of the image

Description

bool Imagick::swirlImage ( float $degrees )
Warning

This function is currently not documented; only its argument list is available.

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

Parameters

degrees

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::stripImage
Imagick::textureImage
The Imagick class


Repeatedly tiles the texture image

Imagick::swirlImage
Imagick::thresholdImage
The Imagick class
PHP Manual

Imagick::textureImage

(PECL imagick 2.0.0)

Imagick::textureImage — Repeatedly tiles the texture image

Description

bool Imagick::textureImage ( Imagick $texture_wand )
Warning

This function is currently not documented; only its argument list is available.

Repeatedly tiles the texture image across and down the image canvas.

Parameters

texture_wand

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::swirlImage
Imagick::thresholdImage
The Imagick class


Changes the value of individual pixels based on a threshold

Imagick::textureImage
Imagick::thumbnailImage
The Imagick class
PHP Manual

Imagick::thresholdImage

(PECL imagick 2.0.0)

Imagick::thresholdImage — Changes the value of individual pixels based on a threshold

Description

bool Imagick::thresholdImage ( float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.

Parameters

threshold

channel

Return Values

Returns TRUE on success.

Imagick::textureImage
Imagick::thumbnailImage
The Imagick class


Changes the size of an image

Imagick::thresholdImage
Imagick::tintImage
The Imagick class
PHP Manual

Imagick::thumbnailImage

(PECL imagick 2.0.0)

Imagick::thumbnailImage — Changes the size of an image

Description

bool Imagick::thumbnailImage ( int $columns , int $rows [, bool $bestfit = false ] )
Warning

This function is currently not documented; only its argument list is available.

Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small low cost thumbnail images suited for display on the Web. If TRUE is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until the match or are smaller than the parameter given for the side.

Note: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parameters

columns

Image width

rows

Image height

bestfit

Whether to force maximum values

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::thresholdImage
Imagick::tintImage
The Imagick class


Applies a color vector to each pixel in the image

Imagick::thumbnailImage
Imagick::transformImage
The Imagick class
PHP Manual

Imagick::tintImage

(PECL imagick 2.0.0)

Imagick::tintImage — Applies a color vector to each pixel in the image

Description

bool Imagick::tintImage ( mixed $tint , mixed $opacity )
Warning

This function is currently not documented; only its argument list is available.

Applies a color vector to each pixel in the image. The length of the vector is 0 for black and white and at its maximum for the midtones. The vector weighing function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))).

Parameters

tint

opacity

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as the first parameter and a float representing the opacity value as the second parameter. Previous versions allow only an ImagickPixel objects.

Imagick::thumbnailImage
Imagick::transformImage
The Imagick class


Convenience method for setting crop size and the image geometry

Imagick::tintImage
Imagick::transparentPaintImage
The Imagick class
PHP Manual

Imagick::transformImage

(PECL imagick 2.0.0)

Imagick::transformImage — Convenience method for setting crop size and the image geometry

Description

Imagick Imagick::transformImage ( string $crop , string $geometry )

A convenience method for setting crop size and the image geometry from strings. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

crop

A crop geometry string. This geometry defines a subregion of the image to crop.

geometry

An image geometry string. This geometry defines the final size of the image.

Return Values

Returns TRUE on success.

Examples

Example #1 Using Imagick::transformImage():

The example creates a 100x100 black image.

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");
$new_image = $image->transformImage("100x100", "100x100");
$new_image->writeImage('test_out.jpg');
?>

See Also

  • Imagick::cropImage() - Extracts a region of the image
  • Imagick::resizeImage() - Scales an image
  • Imagick::thumbnailImage() - Changes the size of an image

Imagick::tintImage
Imagick::transparentPaintImage
The Imagick class


Paints pixels transparent

Imagick::transformImage
Imagick::transposeImage
The Imagick class
PHP Manual

Imagick::transparentPaintImage

(No version information available, might only be in SVN)

Imagick::transparentPaintImage — Paints pixels transparent

Description

bool Imagick::transparentPaintImage ( mixed $target , float $alpha , float $fuzz , bool $invert )

Paints pixels matching the target color transparent. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.

Parameters

target

The target color to paint

alpha

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

invert

If TRUE paints any pixel that does not match the target color.

Return Values

Returns TRUE on success.

Imagick::transformImage
Imagick::transposeImage
The Imagick class


Creates a vertical mirror image

Imagick::transparentPaintImage
Imagick::transverseImage
The Imagick class
PHP Manual

Imagick::transposeImage

(PECL imagick 2.0.0)

Imagick::transposeImage — Creates a vertical mirror image

Description

bool Imagick::transposeImage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis while rotating them 90-degrees. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns TRUE on success.

See Also

  • Imagick::transverseImage() - Creates a horizontal mirror image

Imagick::transparentPaintImage
Imagick::transverseImage
The Imagick class


Creates a horizontal mirror image

Imagick::transposeImage
Imagick::trimImage
The Imagick class
PHP Manual

Imagick::transverseImage

(PECL imagick 2.0.0)

Imagick::transverseImage — Creates a horizontal mirror image

Description

bool Imagick::transverseImage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis while rotating them 270-degrees. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns TRUE on success.

See Also

  • Imagick::transposeImage() - Creates a vertical mirror image

Imagick::transposeImage
Imagick::trimImage
The Imagick class


Remove edges from the image

Imagick::transverseImage
Imagick::uniqueImageColors
The Imagick class
PHP Manual

Imagick::trimImage

(PECL imagick 2.0.0)

Imagick::trimImage — Remove edges from the image

Description

bool Imagick::trimImage ( float $fuzz )

Remove edges that are the background color from the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

fuzz

By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Using Imagick::trimImage():

Trim an image, then display to the browser.

<?php
/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image. */
$im->trimImage(0);

/* Ouput the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>

See Also

  • Imagick::getQuantumDepth() - Gets the quantum depth
  • Imagick::getQuantumRange() - Returns the Imagick quantum range

Imagick::transverseImage
Imagick::uniqueImageColors
The Imagick class


Discards all but one of any pixel color

Imagick::trimImage
Imagick::unsharpMaskImage
The Imagick class
PHP Manual

Imagick::uniqueImageColors

(PECL imagick 2.0.0)

Imagick::uniqueImageColors — Discards all but one of any pixel color

Description

bool Imagick::uniqueImageColors ( void )

Discards all but one of any pixel color. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Return Values

Returns TRUE on success.

Imagick::trimImage
Imagick::unsharpMaskImage
The Imagick class


Sharpens an image

Imagick::uniqueImageColors
Imagick::valid
The Imagick class
PHP Manual

Imagick::unsharpMaskImage

(PECL imagick 2.0.0)

Imagick::unsharpMaskImage — Sharpens an image

Description

bool Imagick::unsharpMaskImage ( float $radius , float $sigma , float $amount , float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )
Warning

This function is currently not documented; only its argument list is available.

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::UnsharpMaskImage() selects a suitable radius for you.

Parameters

radius

sigma

amount

threshold

channel

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::uniqueImageColors
Imagick::valid
The Imagick class


Checks if the current item is valid

Imagick::unsharpMaskImage
Imagick::vignetteImage
The Imagick class
PHP Manual

Imagick::valid

(PECL imagick 2.0.0)

Imagick::valid — Checks if the current item is valid

Description

bool Imagick::valid ( void )
Warning

This function is currently not documented; only its argument list is available.

Checks if the current item is valid.

Return Values

Returns TRUE on success.

Imagick::unsharpMaskImage
Imagick::vignetteImage
The Imagick class


Adds vignette filter to the image

Imagick::valid
Imagick::waveImage
The Imagick class
PHP Manual

Imagick::vignetteImage

(PECL imagick 2.0.0)

Imagick::vignetteImage — Adds vignette filter to the image

Description

bool Imagick::vignetteImage ( float $blackPoint , float $whitePoint , int $x , int $y )

Softens the edges of the image in vignette style. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

blackPoint

The black point.

whitePoint

The white point

x

X offset of the ellipse

y

Y offset of the ellipse

Return Values

Returns TRUE on success.

See Also

  • Imagick::waveImage() - Applies wave filter to the image
  • Imagick::swirlImage() - Swirls the pixels about the center of the image

Imagick::valid
Imagick::waveImage
The Imagick class


Applies wave filter to the image

Imagick::vignetteImage
Imagick::whiteThresholdImage
The Imagick class
PHP Manual

Imagick::waveImage

(PECL imagick 2.0.0)

Imagick::waveImage — Applies wave filter to the image

Description

bool Imagick::waveImage ( float $amplitude , float $length )

Applies a wave filter to the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.

Parameters

amplitude

The amplitude of the wave.

length

The length of the wave.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

See Also

  • Imagick::solarizeImage() - Applies a solarizing effect to the image
  • Imagick::oilpaintImage() - Simulates an oil painting
  • Imagick::embossImage() - Returns a grayscale image with a three-dimensional effect
  • Imagick::addNoiseImage() - Adds random noise to the image
  • Imagick::swirlImage() - Swirls the pixels about the center of the image

Imagick::vignetteImage
Imagick::whiteThresholdImage
The Imagick class


Force all pixels above the threshold into white

Imagick::waveImage
Imagick::writeImage
The Imagick class
PHP Manual

Imagick::whiteThresholdImage

(PECL imagick 2.0.0)

Imagick::whiteThresholdImage — Force all pixels above the threshold into white

Description

bool Imagick::whiteThresholdImage ( mixed $threshold )
Warning

This function is currently not documented; only its argument list is available.

Is like Imagick::ThresholdImage() but force all pixels above the threshold into white while leaving all pixels below the threshold unchanged.

Parameters

threshold

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

Imagick::waveImage
Imagick::writeImage
The Imagick class


Writes an image to the specified filename

Imagick::whiteThresholdImage
Imagick::writeImageFile
The Imagick class
PHP Manual

Imagick::writeImage

(PECL imagick 0.9.0-0.9.9)

Imagick::writeImage — Writes an image to the specified filename

Description

bool Imagick::writeImage ([ string $filename ] )
Warning

This function is currently not documented; only its argument list is available.

Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Imagick::ReadImage() or Imagick::SetImageFilename().

Parameters

filename

Return Values

Returns TRUE on success.

Imagick::whiteThresholdImage
Imagick::writeImageFile
The Imagick class


Writes an image to a filehandle

Imagick::writeImage
Imagick::writeImages
The Imagick class
PHP Manual

Imagick::writeImageFile

(No version information available, might only be in SVN)

Imagick::writeImageFile — Writes an image to a filehandle

Description

bool Imagick::writeImageFile ( resource $filehandle )

Writes the image sequence to an open filehandle. The handle must be opened with for example fopen. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

filehandle

Filehandle where to write the image

Return Values

Returns TRUE on success.

Imagick::writeImage
Imagick::writeImages
The Imagick class


Writes an image or image sequence

Imagick::writeImageFile
Imagick::writeImagesFile
The Imagick class
PHP Manual

Imagick::writeImages

(PECL imagick 0.9.0-0.9.9)

Imagick::writeImages — Writes an image or image sequence

Description

bool Imagick::writeImages ( string $filename , bool $adjoin )
Warning

This function is currently not documented; only its argument list is available.

Writes an image or image sequence.

Parameters

filename

adjoin

Return Values

Returns TRUE on success.

Imagick::writeImageFile
Imagick::writeImagesFile
The Imagick class


Writes frames to a filehandle

Imagick::writeImages
The ImagickDraw class
The Imagick class
PHP Manual

Imagick::writeImagesFile

(No version information available, might only be in SVN)

Imagick::writeImagesFile — Writes frames to a filehandle

Description

bool Imagick::writeImagesFile ( resource $filehandle )

Writes all image frames into an open filehandle. This method can be used to write animated gifs or other multiframe images into open filehandle. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer.

Parameters

filehandle

Filehandle where to write the images

Return Values

Returns TRUE on success.

Imagick::writeImages
The ImagickDraw class
The Imagick class


Adjusts the current affine transformation matrix

The ImagickDraw class
ImagickDraw::annotation
The ImagickDraw class
PHP Manual

ImagickDraw::affine

(PECL imagick 2.0.0)

ImagickDraw::affine — Adjusts the current affine transformation matrix

Description

bool ImagickDraw::affine ( array $affine )
Warning

This function is currently not documented; only its argument list is available.

Adjusts the current affine transformation matrix with the specified affine transformation matrix.

Parameters

affine

Affine matrix parameters

Return Values

No value is returned.

The ImagickDraw class
ImagickDraw::annotation
The ImagickDraw class


Draws text on the image

ImagickDraw::affine
ImagickDraw::arc
The ImagickDraw class
PHP Manual

ImagickDraw::annotation

(PECL imagick 2.0.0)

ImagickDraw::annotation — Draws text on the image

Description

bool ImagickDraw::annotation ( float $x , float $y , string $text )
Warning

This function is currently not documented; only its argument list is available.

Draws text on the image.

Parameters

x

The x coordinate where text is drawn

y

The y coordinate where text is drawn

text

The text to draw on the image

Return Values

No value is returned.

ImagickDraw::affine
ImagickDraw::arc
The ImagickDraw class


Draws an arc

ImagickDraw::annotation
ImagickDraw::bezier
The ImagickDraw class
PHP Manual

ImagickDraw::arc

(PECL imagick 2.0.0)

ImagickDraw::arc — Draws an arc

Description

bool ImagickDraw::arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )
Warning

This function is currently not documented; only its argument list is available.

Draws an arc falling within a specified bounding rectangle on the image.

Parameters

sx

Starting x ordinate of bounding rectangle

sy

starting y ordinate of bounding rectangle

ex

ending x ordinate of bounding rectangle

ey

ending y ordinate of bounding rectangle

sd

starting degrees of rotation

ed

ending degrees of rotation

Return Values

No value is returned.

ImagickDraw::annotation
ImagickDraw::bezier
The ImagickDraw class


Draws a bezier curve

ImagickDraw::arc
ImagickDraw::circle
The ImagickDraw class
PHP Manual

ImagickDraw::bezier

(PECL imagick 2.0.0)

ImagickDraw::bezier — Draws a bezier curve

Description

bool ImagickDraw::bezier ( array $coordinates )
Warning

This function is currently not documented; only its argument list is available.

Draws a bezier curve through a set of points on the image.

Parameters

coordinates

Multidimensional array like array( array( 'x' => 1, 'y' => 2 ), array( 'x' => 3, 'y' => 4 ) )

Return Values

No value is returned.

ImagickDraw::arc
ImagickDraw::circle
The ImagickDraw class


Draws a circle

ImagickDraw::bezier
ImagickDraw::clear
The ImagickDraw class
PHP Manual

ImagickDraw::circle

(PECL imagick 2.0.0)

ImagickDraw::circle — Draws a circle

Description

bool ImagickDraw::circle ( float $ox , float $oy , float $px , float $py )
Warning

This function is currently not documented; only its argument list is available.

Draws a circle on the image.

Parameters

ox

origin x coordinate

oy

origin y coordinate

px

perimeter x coordinate

py

perimeter y coordinate

Return Values

No value is returned.

ImagickDraw::bezier
ImagickDraw::clear
The ImagickDraw class


Clears the ImagickDraw

ImagickDraw::circle
ImagickDraw::clone
The ImagickDraw class
PHP Manual

ImagickDraw::clear

(PECL imagick 2.0.0)

ImagickDraw::clear — Clears the ImagickDraw

Description

bool ImagickDraw::clear ( void )
Warning

This function is currently not documented; only its argument list is available.

Clears the ImagickDraw object of any accumulated commands, and resets the settings it contains to their defaults.

Return Values

Returns an ImagickDraw object.

ImagickDraw::circle
ImagickDraw::clone
The ImagickDraw class


Makes an exact copy of the specified ImagickDraw object

ImagickDraw::clear
ImagickDraw::color
The ImagickDraw class
PHP Manual

ImagickDraw::clone

(PECL imagick 2.0.0)

ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object

Description

ImagickDraw ImagickDraw::clone ( void )
Warning

This function is currently not documented; only its argument list is available.

Makes an exact copy of the specified ImagickDraw object.

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

ImagickDraw::clear
ImagickDraw::color
The ImagickDraw class


Draws color on image

ImagickDraw::clone
ImagickDraw::comment
The ImagickDraw class
PHP Manual

ImagickDraw::color

(PECL imagick 2.0.0)

ImagickDraw::color — Draws color on image

Description

bool ImagickDraw::color ( float $x , float $y , int $paintMethod )
Warning

This function is currently not documented; only its argument list is available.

Draws color on image using the current fill color, starting at specified position, and using specified paint method.

Parameters

x

x coordinate of the paint

y

y coordinate of the paint

paintMethod

one of the PAINT_ constants

Return Values

No value is returned.

ImagickDraw::clone
ImagickDraw::comment
The ImagickDraw class


Adds a comment

ImagickDraw::color
ImagickDraw::composite
The ImagickDraw class
PHP Manual

ImagickDraw::comment

(PECL imagick 2.0.0)

ImagickDraw::comment — Adds a comment

Description

bool ImagickDraw::comment ( string $comment )
Warning

This function is currently not documented; only its argument list is available.

Adds a comment to a vector output stream.

Parameters

comment

The comment string to add to vector output stream

Return Values

No value is returned.

ImagickDraw::color
ImagickDraw::composite
The ImagickDraw class


Composites an image onto the current image

ImagickDraw::comment
ImagickDraw::__construct
The ImagickDraw class
PHP Manual

ImagickDraw::composite

(PECL imagick 2.0.0)

ImagickDraw::composite — Composites an image onto the current image

Description

bool ImagickDraw::composite ( int $compose , float $x , float $y , float $width , float $height , Imagick $compositeWand )
Warning

This function is currently not documented; only its argument list is available.

Composites an image onto the current image, using the specified composition operator, specified position, and at the specified size.

Parameters

compose

composition operator. One of COMPOSITE_ constants

x

x coordinate of the top left corner

y

y coordinate of the top left corner

width

width of the composition image

height

height of the composition image

compositeWand

the Imagick object where composition image is taken from

Return Values

Returns TRUE on success.

ImagickDraw::comment
ImagickDraw::__construct
The ImagickDraw class


The ImagickDraw constructor

ImagickDraw::composite
ImagickDraw::destroy
The ImagickDraw class
PHP Manual

ImagickDraw::__construct

(PECL imagick 2.0.0)

ImagickDraw::__construct — The ImagickDraw constructor

Description

ImagickDraw ImagickDraw::__construct ( void )
Warning

This function is currently not documented; only its argument list is available.

The ImagickDraw constructor

Return Values

No value is returned.

ImagickDraw::composite
ImagickDraw::destroy
The ImagickDraw class


Frees all associated resources

ImagickDraw::__construct
ImagickDraw::ellipse
The ImagickDraw class
PHP Manual

ImagickDraw::destroy

(PECL imagick 2.0.0)

ImagickDraw::destroy — Frees all associated resources

Description

bool ImagickDraw::destroy ( void )
Warning

This function is currently not documented; only its argument list is available.

Frees all resources associated with the ImagickDraw object.

Return Values

No value is returned.

ImagickDraw::__construct
ImagickDraw::ellipse
The ImagickDraw class


Draws an ellipse on the image

ImagickDraw::destroy
ImagickDraw::getClipPath
The ImagickDraw class
PHP Manual

ImagickDraw::ellipse

(PECL imagick 2.0.0)

ImagickDraw::ellipse — Draws an ellipse on the image

Description

bool ImagickDraw::ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )
Warning

This function is currently not documented; only its argument list is available.

Draws an ellipse on the image.

Parameters

ox

oy

rx

ry

start

end

Return Values

No value is returned.

ImagickDraw::destroy
ImagickDraw::getClipPath
The ImagickDraw class


Obtains the current clipping path ID

ImagickDraw::ellipse
ImagickDraw::getClipRule
The ImagickDraw class
PHP Manual

ImagickDraw::getClipPath

(PECL imagick 2.0.0)

ImagickDraw::getClipPath — Obtains the current clipping path ID

Description

string ImagickDraw::getClipPath ( void )
Warning

This function is currently not documented; only its argument list is available.

Obtains the current clipping path ID.

Return Values

Returns a string containing the clip path ID or false if no clip path exists.

ImagickDraw::ellipse
ImagickDraw::getClipRule
The ImagickDraw class


Returns the current polygon fill rule

ImagickDraw::getClipPath
ImagickDraw::getClipUnits
The ImagickDraw class
PHP Manual

ImagickDraw::getClipRule

(PECL imagick 2.0.0)

ImagickDraw::getClipRule — Returns the current polygon fill rule

Description

int ImagickDraw::getClipRule ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the current polygon fill rule to be used by the clipping path.

Return Values

Returns one of the FILLRULE_ constants.

ImagickDraw::getClipPath
ImagickDraw::getClipUnits
The ImagickDraw class


Returns the interpretation of clip path units

ImagickDraw::getClipRule
ImagickDraw::getFillColor
The ImagickDraw class
PHP Manual

ImagickDraw::getClipUnits

(PECL imagick 2.0.0)

ImagickDraw::getClipUnits — Returns the interpretation of clip path units

Description

int ImagickDraw::getClipUnits ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the interpretation of clip path units.

Return Values

Returns an int on success.

ImagickDraw::getClipRule
ImagickDraw::getFillColor
The ImagickDraw class


Returns the fill color

ImagickDraw::getClipUnits
ImagickDraw::getFillOpacity
The ImagickDraw class
PHP Manual

ImagickDraw::getFillColor

(PECL imagick 2.0.0)

ImagickDraw::getFillColor — Returns the fill color

Description

ImagickPixel ImagickDraw::getFillColor ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the fill color used for drawing filled objects.

Return Values

Returns an ImagickPixel object.

ImagickDraw::getClipUnits
ImagickDraw::getFillOpacity
The ImagickDraw class


Returns the opacity used when drawing

ImagickDraw::getFillColor
ImagickDraw::getFillRule
The ImagickDraw class
PHP Manual

ImagickDraw::getFillOpacity

(PECL imagick 2.0.0)

ImagickDraw::getFillOpacity — Returns the opacity used when drawing

Description

float ImagickDraw::getFillOpacity ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

Return Values

The opacity.

ImagickDraw::getFillColor
ImagickDraw::getFillRule
The ImagickDraw class


Returns the fill rule

ImagickDraw::getFillOpacity
ImagickDraw::getFont
The ImagickDraw class
PHP Manual

ImagickDraw::getFillRule

(PECL imagick 2.0.0)

ImagickDraw::getFillRule — Returns the fill rule

Description

int ImagickDraw::getFillRule ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the fill rule used while drawing polygons.

Return Values

Returns a FILLRULE_ constant

ImagickDraw::getFillOpacity
ImagickDraw::getFont
The ImagickDraw class


Returns the font

ImagickDraw::getFillRule
ImagickDraw::getFontFamily
The ImagickDraw class
PHP Manual

ImagickDraw::getFont

(PECL imagick 2.0.0)

ImagickDraw::getFont — Returns the font

Description

string ImagickDraw::getFont ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns a string specifying the font used when annotating with text.

Return Values

Returns a string on success and false if no font is set.

ImagickDraw::getFillRule
ImagickDraw::getFontFamily
The ImagickDraw class


Returns the font family

ImagickDraw::getFont
ImagickDraw::getFontSize
The ImagickDraw class
PHP Manual

ImagickDraw::getFontFamily

(PECL imagick 2.0.0)

ImagickDraw::getFontFamily — Returns the font family

Description

string ImagickDraw::getFontFamily ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the font family to use when annotating with text.

Return Values

Returns the font family currently selected or false if font family is not set.

ImagickDraw::getFont
ImagickDraw::getFontSize
The ImagickDraw class


Returns the font pointsize

ImagickDraw::getFontFamily
ImagickDraw::getFontStyle
The ImagickDraw class
PHP Manual

ImagickDraw::getFontSize

(PECL imagick 2.0.0)

ImagickDraw::getFontSize — Returns the font pointsize

Description

float ImagickDraw::getFontSize ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the font pointsize used when annotating with text.

Return Values

Returns the font size associated with the current ImagickDraw object.

ImagickDraw::getFontFamily
ImagickDraw::getFontStyle
The ImagickDraw class


Returns the font style

ImagickDraw::getFontSize
ImagickDraw::getFontWeight
The ImagickDraw class
PHP Manual

ImagickDraw::getFontStyle

(PECL imagick 2.0.0)

ImagickDraw::getFontStyle — Returns the font style

Description

int ImagickDraw::getFontStyle ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the font style used when annotating with text.

Return Values

Returns the font style constant (STYLE_) associated with the ImagickDraw object or 0 if no style is set.

ImagickDraw::getFontSize
ImagickDraw::getFontWeight
The ImagickDraw class


Returns the font weight

ImagickDraw::getFontStyle
ImagickDraw::getGravity
The ImagickDraw class
PHP Manual

ImagickDraw::getFontWeight

(PECL imagick 2.0.0)

ImagickDraw::getFontWeight — Returns the font weight

Description

int ImagickDraw::getFontWeight ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the font weight used when annotating with text.

Return Values

Returns an int on success and 0 if no weight is set.

ImagickDraw::getFontStyle
ImagickDraw::getGravity
The ImagickDraw class


Returns the text placement gravity

ImagickDraw::getFontWeight
ImagickDraw::getStrokeAntialias
The ImagickDraw class
PHP Manual

ImagickDraw::getGravity

(PECL imagick 2.0.0)

ImagickDraw::getGravity — Returns the text placement gravity

Description

int ImagickDraw::getGravity ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the text placement gravity used when annotating with text.

Return Values

Returns a GRAVITY_ constant on success and 0 if no gravity is set.

ImagickDraw::getFontWeight
ImagickDraw::getStrokeAntialias
The ImagickDraw class


Returns the current stroke antialias setting

ImagickDraw::getGravity
ImagickDraw::getStrokeColor
The ImagickDraw class
PHP Manual

ImagickDraw::getStrokeAntialias

(PECL imagick 2.0.0)

ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting

Description

bool ImagickDraw::getStrokeAntialias ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the current stroke antialias setting. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

Return Values

Returns TRUE if antialiasing is on and false if it is off.

ImagickDraw::getGravity
ImagickDraw::getStrokeColor
The ImagickDraw class


Returns the color used for stroking object outlines

ImagickDraw::getStrokeAntialias
ImagickDraw::getStrokeDashArray
The ImagickDraw class
PHP Manual

ImagickDraw::getStrokeColor

(PECL imagick 2.0.0)

ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines

Description

ImagickPixel ImagickDraw::getStrokeColor ( ImagickPixel $stroke_color )
Warning

This function is currently not documented; only its argument list is available.

Returns the color used for stroking object outlines.

Parameters

stroke_color

Return Values

Returns an ImagickPixel object which describes the color.

ImagickDraw::getStrokeAntialias
ImagickDraw::getStrokeDashArray
The ImagickDraw class


Returns an array representing the pattern of dashes and gaps used to stroke paths

ImagickDraw::getStrokeColor
ImagickDraw::getStrokeDashOffset
The ImagickDraw class
PHP Manual

ImagickDraw::getStrokeDashArray

(PECL imagick 2.0.0)

ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths

Description

array ImagickDraw::getStrokeDashArray ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns an array representing the pattern of dashes and gaps used to stroke paths.

Return Values

Returns an array on success and empty array if not set.

ImagickDraw::getStrokeColor
ImagickDraw::getStrokeDashOffset
The ImagickDraw class


Returns the offset into the dash pattern to start the dash

ImagickDraw::getStrokeDashArray
ImagickDraw::getStrokeLineCap
The ImagickDraw class
PHP Manual

ImagickDraw::getStrokeDashOffset

(PECL imagick 2.0.0)

ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash

Description

float ImagickDraw::getStrokeDashOffset ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the offset into the dash pattern to start the dash.

Return Values

Returns a float representing the offset and 0 if it's not set.

ImagickDraw::getStrokeDashArray
ImagickDraw::getStrokeLineCap
The ImagickDraw class


Returns the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::getStrokeDashOffset
ImagickDraw::getStrokeLineJoin
The ImagickDraw class
PHP Manual

ImagickDraw::getStrokeLineCap

(PECL imagick 2.0.0)

ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked

Description

int ImagickDraw::getStrokeLineCap ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the shape to be used at the end of open subpaths when they are stroked.

Return Values

Returns one of the LINECAP_ constants or 0 if stroke linecap is not set.

ImagickDraw::getStrokeDashOffset
ImagickDraw::getStrokeLineJoin
The ImagickDraw class


Returns the shape to be used at the corners of paths when they are stroked

ImagickDraw::getStrokeLineCap
ImagickDraw::getStrokeMiterLimit
The ImagickDraw class
PHP Manual

ImagickDraw::getStrokeLineJoin

(PECL imagick 2.0.0)

ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked

Description

int ImagickDraw::getStrokeLineJoin ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

Return Values

Returns one of the LINEJOIN_ constants or 0 if stroke line join is not set.

ImagickDraw::getStrokeLineCap
ImagickDraw::getStrokeMiterLimit
The ImagickDraw class


Returns the stroke miter limit

ImagickDraw::getStrokeLineJoin
ImagickDraw::getStrokeOpacity
The ImagickDraw class
PHP Manual

ImagickDraw::getStrokeMiterLimit

(PECL imagick 2.0.0)

ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit

Description

int ImagickDraw::getStrokeMiterLimit ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The 'miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'.

Return Values

Returns an int describing the miter limit and 0 if no miter limit is set.

ImagickDraw::getStrokeLineJoin
ImagickDraw::getStrokeOpacity
The ImagickDraw class


Returns the opacity of stroked object outlines

ImagickDraw::getStrokeMiterLimit
ImagickDraw::getStrokeWidth
The ImagickDraw class
PHP Manual

ImagickDraw::getStrokeOpacity

(PECL imagick 2.0.0)

ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines

Description

float ImagickDraw::getStrokeOpacity ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the opacity of stroked object outlines.

Return Values

Returns a double describing the opacity.

ImagickDraw::getStrokeMiterLimit
ImagickDraw::getStrokeWidth
The ImagickDraw class


Returns the width of the stroke used to draw object outlines

ImagickDraw::getStrokeOpacity
ImagickDraw::getTextAlignment
The ImagickDraw class
PHP Manual

ImagickDraw::getStrokeWidth

(PECL imagick 2.0.0)

ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines

Description

float ImagickDraw::getStrokeWidth ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the width of the stroke used to draw object outlines.

Return Values

Returns a double describing the stroke width.

ImagickDraw::getStrokeOpacity
ImagickDraw::getTextAlignment
The ImagickDraw class


Returns the text alignment

ImagickDraw::getStrokeWidth
ImagickDraw::getTextAntialias
The ImagickDraw class
PHP Manual

ImagickDraw::getTextAlignment

(PECL imagick 2.0.0)

ImagickDraw::getTextAlignment — Returns the text alignment

Description

int ImagickDraw::getTextAlignment ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the alignment applied when annotating with text.

Return Values

Returns one of the ALIGN_ constants and 0 if no align is set.

ImagickDraw::getStrokeWidth
ImagickDraw::getTextAntialias
The ImagickDraw class


Returns the current text antialias setting

ImagickDraw::getTextAlignment
ImagickDraw::getTextDecoration
The ImagickDraw class
PHP Manual

ImagickDraw::getTextAntialias

(PECL imagick 2.0.0)

ImagickDraw::getTextAntialias — Returns the current text antialias setting

Description

bool ImagickDraw::getTextAntialias ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the current text antialias setting, which determines whether text is antialiased. Text is antialiased by default.

Return Values

Returns TRUE if text is antialiased and false if not.

ImagickDraw::getTextAlignment
ImagickDraw::getTextDecoration
The ImagickDraw class


Returns the text decoration

ImagickDraw::getTextAntialias
ImagickDraw::getTextEncoding
The ImagickDraw class
PHP Manual

ImagickDraw::getTextDecoration

(PECL imagick 2.0.0)

ImagickDraw::getTextDecoration — Returns the text decoration

Description

int ImagickDraw::getTextDecoration ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the decoration applied when annotating with text.

Return Values

Returns one of the DECORATION_ constants and 0 if no decoration is set.

ImagickDraw::getTextAntialias
ImagickDraw::getTextEncoding
The ImagickDraw class


Returns the code set used for text annotations

ImagickDraw::getTextDecoration
ImagickDraw::getTextUnderColor
The ImagickDraw class
PHP Manual

ImagickDraw::getTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::getTextEncoding — Returns the code set used for text annotations

Description

string ImagickDraw::getTextEncoding ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns a string which specifies the code set used for text annotations.

Return Values

Returns a string specifying the code set or false if text encoding is not set.

ImagickDraw::getTextDecoration
ImagickDraw::getTextUnderColor
The ImagickDraw class


Returns the text under color

ImagickDraw::getTextEncoding
ImagickDraw::getVectorGraphics
The ImagickDraw class
PHP Manual

ImagickDraw::getTextUnderColor

(PECL imagick 2.0.0)

ImagickDraw::getTextUnderColor — Returns the text under color

Description

ImagickPixel ImagickDraw::getTextUnderColor ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the color of a background rectangle to place under text annotations.

Return Values

Returns an ImagickPixel object describing the color.

ImagickDraw::getTextEncoding
ImagickDraw::getVectorGraphics
The ImagickDraw class


Returns a string containing vector graphics

ImagickDraw::getTextUnderColor
ImagickDraw::line
The ImagickDraw class
PHP Manual

ImagickDraw::getVectorGraphics

(PECL imagick 2.0.0)

ImagickDraw::getVectorGraphics — Returns a string containing vector graphics

Description

string ImagickDraw::getVectorGraphics ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns a string which specifies the vector graphics generated by any graphics calls made since the ImagickDraw object was instantiated.

Return Values

Returns a string containing the vector graphics.

ImagickDraw::getTextUnderColor
ImagickDraw::line
The ImagickDraw class


Draws a line

ImagickDraw::getVectorGraphics
ImagickDraw::matte
The ImagickDraw class
PHP Manual

ImagickDraw::line

(PECL imagick 2.0.0)

ImagickDraw::line — Draws a line

Description

bool ImagickDraw::line ( float $sx , float $sy , float $ex , float $ey )
Warning

This function is currently not documented; only its argument list is available.

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

Parameters

sx

starting x coordinate

sy

starting y coordinate

ex

ending x coordinate

ey

ending y coordinate

Return Values

No value is returned.

ImagickDraw::getVectorGraphics
ImagickDraw::matte
The ImagickDraw class


Paints on the image's opacity channel

ImagickDraw::line
ImagickDraw::pathClose
The ImagickDraw class
PHP Manual

ImagickDraw::matte

(PECL imagick 2.0.0)

ImagickDraw::matte — Paints on the image's opacity channel

Description

bool ImagickDraw::matte ( float $x , float $y , int $paintMethod )
Warning

This function is currently not documented; only its argument list is available.

Paints on the image's opacity channel in order to set effected pixels to transparent, to influence the opacity of pixels.

Parameters

x

x coordinate of the matte

y

y coordinate of the matte

paintMethod

PAINT_ constant

Return Values

Returns TRUE on success or FALSE on failure.

ImagickDraw::line
ImagickDraw::pathClose
The ImagickDraw class


Adds a path element to the current path

ImagickDraw::matte
ImagickDraw::pathCurveToAbsolute
The ImagickDraw class
PHP Manual

ImagickDraw::pathClose

(PECL imagick 2.0.0)

ImagickDraw::pathClose — Adds a path element to the current path

Description

bool ImagickDraw::pathClose ( void )
Warning

This function is currently not documented; only its argument list is available.

Adds a path element to the current path which closes the current subpath by drawing a straight line from the current point to the current subpath's most recent starting point (usually, the most recent moveto point).

Return Values

No value is returned.

ImagickDraw::matte
ImagickDraw::pathCurveToAbsolute
The ImagickDraw class


Draws a cubic Bezier curve

ImagickDraw::pathClose
ImagickDraw::pathCurveToQuadraticBezierAbsolute
The ImagickDraw class
PHP Manual

ImagickDraw::pathCurveToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve

Description

bool ImagickDraw::pathCurveToAbsolute ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using absolute coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x1

x coordinate of the first control point

y1

y coordinate of the first control point

x2

x coordinate of the second control point

y2

y coordinate of the first control point

x

x coordinate of the curve end

y

y coordinate of the curve end

Return Values

No value is returned.

ImagickDraw::pathClose
ImagickDraw::pathCurveToQuadraticBezierAbsolute
The ImagickDraw class


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToAbsolute
ImagickDraw::pathCurveToQuadraticBezierRelative
The ImagickDraw class
PHP Manual

ImagickDraw::pathCurveToQuadraticBezierAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve

Description

bool ImagickDraw::pathCurveToQuadraticBezierAbsolute ( float $x1 , float $y1 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using absolute coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x1

x coordinate of the control point

y1

y coordinate of the control point

x

x coordinate of the end point

y

y coordinate of the end point

Return Values

No value is returned.

ImagickDraw::pathCurveToAbsolute
ImagickDraw::pathCurveToQuadraticBezierRelative
The ImagickDraw class


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierAbsolute
ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
The ImagickDraw class
PHP Manual

ImagickDraw::pathCurveToQuadraticBezierRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve

Description

bool ImagickDraw::pathCurveToQuadraticBezierRelative ( float $x1 , float $y1 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x1

starting x coordinate

y1

starting y coordinate

x

ending x coordinate

y

ending y coordinate

Return Values

No value is returned.

ImagickDraw::pathCurveToQuadraticBezierAbsolute
ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
The ImagickDraw class


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierRelative
ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
The ImagickDraw class
PHP Manual

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve

Description

bool ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve (using absolute coordinates) from the current point to (x,y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point.). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x

ending x coordinate

y

ending y coordinate

Return Values

No value is returned.

ImagickDraw::pathCurveToQuadraticBezierRelative
ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
The ImagickDraw class


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
ImagickDraw::pathCurveToRelative
The ImagickDraw class
PHP Manual

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve

Description

bool ImagickDraw::pathCurveToQuadraticBezierSmoothRelative ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a quadratic Bezier curve (using relative coordinates) from the current point to (x, y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point). At the end of the command, the new current point becomes the final (x, y) coordinate pair used in the polybezier.

Parameters

x

ending x coordinate

y

ending y coordinate

Return Values

No value is returned.

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
ImagickDraw::pathCurveToRelative
The ImagickDraw class


Draws a cubic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
ImagickDraw::pathCurveToSmoothAbsolute
The ImagickDraw class
PHP Manual

ImagickDraw::pathCurveToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve

Description

bool ImagickDraw::pathCurveToRelative ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x1

x coordinate of starting control point

y1

y coordinate of starting control point

x2

x coordinate of ending control point

y2

y coordinate of ending control point

x

ending x coordinate

y

ending y coordinate

Return Values

No value is returned.

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
ImagickDraw::pathCurveToSmoothAbsolute
The ImagickDraw class


Draws a cubic Bezier curve

ImagickDraw::pathCurveToRelative
ImagickDraw::pathCurveToSmoothRelative
The ImagickDraw class
PHP Manual

ImagickDraw::pathCurveToSmoothAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve

Description

bool ImagickDraw::pathCurveToSmoothAbsolute ( float $x2 , float $y2 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using absolute coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x2

x coordinate of the second control point

y2

y coordinate of the second control point

x

x coordinate of the ending point

y

y coordinate of the ending point

Return Values

No value is returned.

ImagickDraw::pathCurveToRelative
ImagickDraw::pathCurveToSmoothRelative
The ImagickDraw class


Draws a cubic Bezier curve

ImagickDraw::pathCurveToSmoothAbsolute
ImagickDraw::pathEllipticArcAbsolute
The ImagickDraw class
PHP Manual

ImagickDraw::pathCurveToSmoothRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve

Description

bool ImagickDraw::pathCurveToSmoothRelative ( float $x2 , float $y2 , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a cubic Bezier curve from the current point to (x,y) using relative coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parameters

x2

x coordinate of the second control point

y2

y coordinate of the second control point

x

x coordinate of the ending point

y

y coordinate of the ending point

Return Values

No value is returned.

ImagickDraw::pathCurveToSmoothAbsolute
ImagickDraw::pathEllipticArcAbsolute
The ImagickDraw class


Draws an elliptical arc

ImagickDraw::pathCurveToSmoothRelative
ImagickDraw::pathEllipticArcRelative
The ImagickDraw class
PHP Manual

ImagickDraw::pathEllipticArcAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc

Description

bool ImagickDraw::pathEllipticArcAbsolute ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws an elliptical arc from the current point to (x, y) using absolute coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If largeArcFlag is TRUE then draw the larger of the available arcs. If sweepFlag is true, then draw the arc matching a clock-wise rotation.

Parameters

rx

x radius

ry

y radius

x_axis_rotation

x axis rotation

large_arc_flag

large arc flag

sweep_flag

sweep flag

x

x coordinate

y

y coordinate

Return Values

No value is returned.

ImagickDraw::pathCurveToSmoothRelative
ImagickDraw::pathEllipticArcRelative
The ImagickDraw class


Draws an elliptical arc

ImagickDraw::pathEllipticArcAbsolute
ImagickDraw::pathFinish
The ImagickDraw class
PHP Manual

ImagickDraw::pathEllipticArcRelative

(PECL imagick 2.0.0)

ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc

Description

bool ImagickDraw::pathEllipticArcRelative ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws an elliptical arc from the current point to (x, y) using relative coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If largeArcFlag is TRUE then draw the larger of the available arcs. If sweepFlag is true, then draw the arc matching a clock-wise rotation.

Parameters

rx

x radius

ry

y radius

x_axis_rotation

x axis rotation

large_arc_flag

large arc flag

sweep_flag

sweep flag

x

x coordinate

y

y coordinate

Return Values

No value is returned.

ImagickDraw::pathEllipticArcAbsolute
ImagickDraw::pathFinish
The ImagickDraw class


Terminates the current path

ImagickDraw::pathEllipticArcRelative
ImagickDraw::pathLineToAbsolute
The ImagickDraw class
PHP Manual

ImagickDraw::pathFinish

(PECL imagick 2.0.0)

ImagickDraw::pathFinish — Terminates the current path

Description

bool ImagickDraw::pathFinish ( void )
Warning

This function is currently not documented; only its argument list is available.

Terminates the current path.

Return Values

No value is returned.

ImagickDraw::pathEllipticArcRelative
ImagickDraw::pathLineToAbsolute
The ImagickDraw class


Draws a line path

ImagickDraw::pathFinish
ImagickDraw::pathLineToHorizontalAbsolute
The ImagickDraw class
PHP Manual

ImagickDraw::pathLineToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToAbsolute — Draws a line path

Description

bool ImagickDraw::pathLineToAbsolute ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a line path from the current point to the given coordinate using absolute coordinates. The coordinate then becomes the new current point.

Parameters

x

starting x coordinate

y

ending x coordinate

Return Values

No value is returned.

ImagickDraw::pathFinish
ImagickDraw::pathLineToHorizontalAbsolute
The ImagickDraw class


Draws a horizontal line path

ImagickDraw::pathLineToAbsolute
ImagickDraw::pathLineToHorizontalRelative
The ImagickDraw class
PHP Manual

ImagickDraw::pathLineToHorizontalAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path

Description

bool ImagickDraw::pathLineToHorizontalAbsolute ( float $x )
Warning

This function is currently not documented; only its argument list is available.

Draws a horizontal line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point.

Parameters

x

x coordinate

Return Values

No value is returned.

ImagickDraw::pathLineToAbsolute
ImagickDraw::pathLineToHorizontalRelative
The ImagickDraw class


Draws a horizontal line

ImagickDraw::pathLineToHorizontalAbsolute
ImagickDraw::pathLineToRelative
The ImagickDraw class
PHP Manual

ImagickDraw::pathLineToHorizontalRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line

Description

bool ImagickDraw::pathLineToHorizontalRelative ( float $x )
Warning

This function is currently not documented; only its argument list is available.

Draws a horizontal line path from the current point to the target point using relative coordinates. The target point then becomes the new current point.

Parameters

x

x coordinate

Return Values

No value is returned.

ImagickDraw::pathLineToHorizontalAbsolute
ImagickDraw::pathLineToRelative
The ImagickDraw class


Draws a line path

ImagickDraw::pathLineToHorizontalRelative
ImagickDraw::pathLineToVerticalAbsolute
The ImagickDraw class
PHP Manual

ImagickDraw::pathLineToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToRelative — Draws a line path

Description

bool ImagickDraw::pathLineToRelative ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a line path from the current point to the given coordinate using relative coordinates. The coordinate then becomes the new current point.

Parameters

x

starting x coordinate

y

starting y coordinate

Return Values

No value is returned.

ImagickDraw::pathLineToHorizontalRelative
ImagickDraw::pathLineToVerticalAbsolute
The ImagickDraw class


Draws a vertical line

ImagickDraw::pathLineToRelative
ImagickDraw::pathLineToVerticalRelative
The ImagickDraw class
PHP Manual

ImagickDraw::pathLineToVerticalAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line

Description

bool ImagickDraw::pathLineToVerticalAbsolute ( float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a vertical line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point.

Parameters

y

y coordinate

Return Values

No value is returned.

ImagickDraw::pathLineToRelative
ImagickDraw::pathLineToVerticalRelative
The ImagickDraw class


Draws a vertical line path

ImagickDraw::pathLineToVerticalAbsolute
ImagickDraw::pathMoveToAbsolute
The ImagickDraw class
PHP Manual

ImagickDraw::pathLineToVerticalRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path

Description

bool ImagickDraw::pathLineToVerticalRelative ( float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a vertical line path from the current point to the target point using relative coordinates. The target point then becomes the new current point.

Parameters

y

y coordinate

Return Values

No value is returned.

ImagickDraw::pathLineToVerticalAbsolute
ImagickDraw::pathMoveToAbsolute
The ImagickDraw class


Starts a new sub-path

ImagickDraw::pathLineToVerticalRelative
ImagickDraw::pathMoveToRelative
The ImagickDraw class
PHP Manual

ImagickDraw::pathMoveToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathMoveToAbsolute — Starts a new sub-path

Description

bool ImagickDraw::pathMoveToAbsolute ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Starts a new sub-path at the given coordinate using absolute coordinates. The current point then becomes the specified coordinate.

Parameters

x

x coordinate of the starting point

y

y coordinate of the starting point

Return Values

No value is returned.

ImagickDraw::pathLineToVerticalRelative
ImagickDraw::pathMoveToRelative
The ImagickDraw class


Starts a new sub-path

ImagickDraw::pathMoveToAbsolute
ImagickDraw::pathStart
The ImagickDraw class
PHP Manual

ImagickDraw::pathMoveToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathMoveToRelative — Starts a new sub-path

Description

bool ImagickDraw::pathMoveToRelative ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Starts a new sub-path at the given coordinate using relative coordinates. The current point then becomes the specified coordinate.

Parameters

x

target x coordinate

y

target y coordinate

Return Values

No value is returned.

ImagickDraw::pathMoveToAbsolute
ImagickDraw::pathStart
The ImagickDraw class


Declares the start of a path drawing list

ImagickDraw::pathMoveToRelative
ImagickDraw::point
The ImagickDraw class
PHP Manual

ImagickDraw::pathStart

(PECL imagick 2.0.0)

ImagickDraw::pathStart — Declares the start of a path drawing list

Description

bool ImagickDraw::pathStart ( void )
Warning

This function is currently not documented; only its argument list is available.

Declares the start of a path drawing list which is terminated by a matching DrawPathFinish() command. All other DrawPath commands must be enclosed between a and a DrawPathFinish() command. This is because path drawing commands are subordinate commands and they do not function by themselves.

Return Values

No value is returned.

ImagickDraw::pathMoveToRelative
ImagickDraw::point
The ImagickDraw class


Draws a point

ImagickDraw::pathStart
ImagickDraw::polygon
The ImagickDraw class
PHP Manual

ImagickDraw::point

(PECL imagick 2.0.0)

ImagickDraw::point — Draws a point

Description

bool ImagickDraw::point ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

Parameters

x

point's x coordinate

y

point's y coordinate

Return Values

No value is returned.

ImagickDraw::pathStart
ImagickDraw::polygon
The ImagickDraw class


Draws a polygon

ImagickDraw::point
ImagickDraw::polyline
The ImagickDraw class
PHP Manual

ImagickDraw::polygon

(PECL imagick 2.0.0)

ImagickDraw::polygon — Draws a polygon

Description

bool ImagickDraw::polygon ( array $coordinates )
Warning

This function is currently not documented; only its argument list is available.

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parameters

coordinates

multidimensional array like array( array( 'x' => 3, 'y' => 4 ), array( 'x' => 2, 'y' => 6 ) );

Return Values

Returns TRUE on success.

ImagickDraw::point
ImagickDraw::polyline
The ImagickDraw class


Draws a polyline

ImagickDraw::polygon
ImagickDraw::pop
The ImagickDraw class
PHP Manual

ImagickDraw::polyline

(PECL imagick 2.0.0)

ImagickDraw::polyline — Draws a polyline

Description

bool ImagickDraw::polyline ( array $coordinates )
Warning

This function is currently not documented; only its argument list is available.

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parameters

coordinates

array of x and y coordinates: array( array( 'x' => 4, 'y' => 6 ), array( 'x' => 8, 'y' => 10 ) )

Return Values

Returns TRUE on success.

ImagickDraw::polygon
ImagickDraw::pop
The ImagickDraw class


Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

ImagickDraw::polyline
ImagickDraw::popClipPath
The ImagickDraw class
PHP Manual

ImagickDraw::pop

(PECL imagick 2.0.0)

ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

Description

bool ImagickDraw::pop ( void )
Warning

This function is currently not documented; only its argument list is available.

Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw. Multiple ImagickDraws may exist. It is an error to attempt to pop more ImagickDraws than have been pushed, and it is proper form to pop all ImagickDraws which have been pushed.

Return Values

Returns TRUE on success and false on failure.

ImagickDraw::polyline
ImagickDraw::popClipPath
The ImagickDraw class


Terminates a clip path definition

ImagickDraw::pop
ImagickDraw::popDefs
The ImagickDraw class
PHP Manual

ImagickDraw::popClipPath

(PECL imagick 2.0.0)

ImagickDraw::popClipPath — Terminates a clip path definition

Description

bool ImagickDraw::popClipPath ( void )
Warning

This function is currently not documented; only its argument list is available.

Terminates a clip path definition.

Return Values

No value is returned.

ImagickDraw::pop
ImagickDraw::popDefs
The ImagickDraw class


Terminates a definition list

ImagickDraw::popClipPath
ImagickDraw::popPattern
The ImagickDraw class
PHP Manual

ImagickDraw::popDefs

(PECL imagick 2.0.0)

ImagickDraw::popDefs — Terminates a definition list

Description

bool ImagickDraw::popDefs ( void )
Warning

This function is currently not documented; only its argument list is available.

Terminates a definition list.

Return Values

No value is returned.

ImagickDraw::popClipPath
ImagickDraw::popPattern
The ImagickDraw class


Terminates a pattern definition

ImagickDraw::popDefs
ImagickDraw::push
The ImagickDraw class
PHP Manual

ImagickDraw::popPattern

(PECL imagick 2.0.0)

ImagickDraw::popPattern — Terminates a pattern definition

Description

bool ImagickDraw::popPattern ( void )
Warning

This function is currently not documented; only its argument list is available.

Terminates a pattern definition.

Return Values

Returns TRUE on success or FALSE on failure.

ImagickDraw::popDefs
ImagickDraw::push
The ImagickDraw class


Clones the current ImagickDraw and pushes it to the stack

ImagickDraw::popPattern
ImagickDraw::pushClipPath
The ImagickDraw class
PHP Manual

ImagickDraw::push

(PECL imagick 2.0.0)

ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack

Description

bool ImagickDraw::push ( void )
Warning

This function is currently not documented; only its argument list is available.

Clones the current ImagickDraw to create a new ImagickDraw, which is then added to the ImagickDraw stack. The original drawing ImagickDraw(s) may be returned to by invoking pop(). The ImagickDraws are stored on a ImagickDraw stack. For every Pop there must have already been an equivalent Push.

Return Values

Returns TRUE on success or FALSE on failure.

ImagickDraw::popPattern
ImagickDraw::pushClipPath
The ImagickDraw class


Starts a clip path definition

ImagickDraw::push
ImagickDraw::pushDefs
The ImagickDraw class
PHP Manual

ImagickDraw::pushClipPath

(PECL imagick 2.0.0)

ImagickDraw::pushClipPath — Starts a clip path definition

Description

bool ImagickDraw::pushClipPath ( string $clip_mask_id )
Warning

This function is currently not documented; only its argument list is available.

Starts a clip path definition which is comprised of any number of drawing commands and terminated by a ImagickDraw::popClipPath() command.

Parameters

clip_mask_id

Clip mask Id

Return Values

No value is returned.

ImagickDraw::push
ImagickDraw::pushDefs
The ImagickDraw class


Indicates that following commands create named elements for early processing

ImagickDraw::pushClipPath
ImagickDraw::pushPattern
The ImagickDraw class
PHP Manual

ImagickDraw::pushDefs

(PECL imagick 2.0.0)

ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing

Description

bool ImagickDraw::pushDefs ( void )
Warning

This function is currently not documented; only its argument list is available.

Indicates that commands up to a terminating ImagickDraw::popDefs() command create named elements (e.g. clip-paths, textures, etc.) which may safely be processed earlier for the sake of efficiency.

Return Values

No value is returned.

ImagickDraw::pushClipPath
ImagickDraw::pushPattern
The ImagickDraw class


Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

ImagickDraw::pushDefs
ImagickDraw::rectangle
The ImagickDraw class
PHP Manual

ImagickDraw::pushPattern

(PECL imagick 2.0.0)

ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

Description

bool ImagickDraw::pushPattern ( string $pattern_id , float $x , float $y , float $width , float $height )
Warning

This function is currently not documented; only its argument list is available.

Indicates that subsequent commands up to a DrawPopPattern() command comprise the definition of a named pattern. The pattern space is assigned top left corner coordinates, a width and height, and becomes its own drawing space. Anything which can be drawn may be used in a pattern definition. Named patterns may be used as stroke or brush definitions.

Parameters

pattern_id

the pattern Id

x

x coordinate of the top-left corner

y

y coordinate of the top-left corner

width

width of the pattern

height

height of the pattern

Return Values

Returns TRUE on success or FALSE on failure.

ImagickDraw::pushDefs
ImagickDraw::rectangle
The ImagickDraw class


Draws a rectangle

ImagickDraw::pushPattern
ImagickDraw::render
The ImagickDraw class
PHP Manual

ImagickDraw::rectangle

(PECL imagick 2.0.0)

ImagickDraw::rectangle — Draws a rectangle

Description

bool ImagickDraw::rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )
Warning

This function is currently not documented; only its argument list is available.

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

Parameters

x1

x coordinate of the top left corner

y1

y coordinate of the top left corner

x2

x coordinate of the bottom right corner

y2

y coordinate of the bottom right corner

Return Values

No value is returned.

ImagickDraw::pushPattern
ImagickDraw::render
The ImagickDraw class


Renders all preceding drawing commands onto the image

ImagickDraw::rectangle
ImagickDraw::rotate
The ImagickDraw class
PHP Manual

ImagickDraw::render

(PECL imagick 2.0.0)

ImagickDraw::render — Renders all preceding drawing commands onto the image

Description

bool ImagickDraw::render ( void )
Warning

This function is currently not documented; only its argument list is available.

Renders all preceding drawing commands onto the image.

Return Values

Returns TRUE on success or FALSE on failure.

ImagickDraw::rectangle
ImagickDraw::rotate
The ImagickDraw class


Applies the specified rotation to the current coordinate space

ImagickDraw::render
ImagickDraw::roundRectangle
The ImagickDraw class
PHP Manual

ImagickDraw::rotate

(PECL imagick 2.0.0)

ImagickDraw::rotate — Applies the specified rotation to the current coordinate space

Description

bool ImagickDraw::rotate ( float $degrees )
Warning

This function is currently not documented; only its argument list is available.

Applies the specified rotation to the current coordinate space.

Parameters

degrees

degrees to rotate

Return Values

No value is returned.

ImagickDraw::render
ImagickDraw::roundRectangle
The ImagickDraw class


Draws a rounded rectangle

ImagickDraw::rotate
ImagickDraw::scale
The ImagickDraw class
PHP Manual

ImagickDraw::roundRectangle

(PECL imagick 2.0.0)

ImagickDraw::roundRectangle — Draws a rounded rectangle

Description

bool ImagickDraw::roundRectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )
Warning

This function is currently not documented; only its argument list is available.

Draws a rounded rectangle given two coordinates, x & y corner radiuses and using the current stroke, stroke width, and fill settings.

Parameters

x1

x coordinate of the top left corner

y1

y coordinate of the top left corner

x2

x coordinate of the bottom right

y2

y coordinate of the bottom right

rx

x rounding

ry

y rounding

Return Values

No value is returned.

ImagickDraw::rotate
ImagickDraw::scale
The ImagickDraw class


Adjusts the scaling factor

ImagickDraw::roundRectangle
ImagickDraw::setClipPath
The ImagickDraw class
PHP Manual

ImagickDraw::scale

(PECL imagick 2.0.0)

ImagickDraw::scale — Adjusts the scaling factor

Description

bool ImagickDraw::scale ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

Parameters

x

horizontal factor

y

vertical factor

Return Values

No value is returned.

ImagickDraw::roundRectangle
ImagickDraw::setClipPath
The ImagickDraw class


Associates a named clipping path with the image

ImagickDraw::scale
ImagickDraw::setClipRule
The ImagickDraw class
PHP Manual

ImagickDraw::setClipPath

(PECL imagick 2.0.0)

ImagickDraw::setClipPath — Associates a named clipping path with the image

Description

bool ImagickDraw::setClipPath ( string $clip_mask )
Warning

This function is currently not documented; only its argument list is available.

Associates a named clipping path with the image. Only the areas drawn on by the clipping path will be modified as long as it remains in effect.

Parameters

clip_mask

the clipping path name

Return Values

No value is returned.

ImagickDraw::scale
ImagickDraw::setClipRule
The ImagickDraw class


Set the polygon fill rule to be used by the clipping path

ImagickDraw::setClipPath
ImagickDraw::setClipUnits
The ImagickDraw class
PHP Manual

ImagickDraw::setClipRule

(PECL imagick 2.0.0)

ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path

Description

bool ImagickDraw::setClipRule ( int $fill_rule )
Warning

This function is currently not documented; only its argument list is available.

Set the polygon fill rule to be used by the clipping path.

Parameters

fill_rule

FILLRULE_ constant

Return Values

No value is returned.

ImagickDraw::setClipPath
ImagickDraw::setClipUnits
The ImagickDraw class


Sets the interpretation of clip path units

ImagickDraw::setClipRule
ImagickDraw::setFillAlpha
The ImagickDraw class
PHP Manual

ImagickDraw::setClipUnits

(PECL imagick 2.0.0)

ImagickDraw::setClipUnits — Sets the interpretation of clip path units

Description

bool ImagickDraw::setClipUnits ( int $clip_units )
Warning

This function is currently not documented; only its argument list is available.

Sets the interpretation of clip path units.

Parameters

clip_units

the number of clip units

Return Values

No value is returned.

ImagickDraw::setClipRule
ImagickDraw::setFillAlpha
The ImagickDraw class


Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setClipUnits
ImagickDraw::setFillColor
The ImagickDraw class
PHP Manual

ImagickDraw::setFillAlpha

(PECL imagick 2.0.0)

ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture

Description

bool ImagickDraw::setFillAlpha ( float $opacity )
Warning

This function is currently not documented; only its argument list is available.

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

Parameters

opacity

fill alpha

Return Values

No value is returned.

ImagickDraw::setClipUnits
ImagickDraw::setFillColor
The ImagickDraw class


Sets the fill color to be used for drawing filled objects

ImagickDraw::setFillAlpha
ImagickDraw::setFillOpacity
The ImagickDraw class
PHP Manual

ImagickDraw::setFillColor

(PECL imagick 2.0.0)

ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects

Description

bool ImagickDraw::setFillColor ( ImagickPixel $fill_pixel )
Warning

This function is currently not documented; only its argument list is available.

Sets the fill color to be used for drawing filled objects.

Parameters

fill_pixel

ImagickPixel to use to set the color

Return Values

No value is returned.

ImagickDraw::setFillAlpha
ImagickDraw::setFillOpacity
The ImagickDraw class


Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setFillColor
ImagickDraw::setFillPatternURL
The ImagickDraw class
PHP Manual

ImagickDraw::setFillOpacity

(PECL imagick 2.0.0)

ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture

Description

bool ImagickDraw::setFillOpacity ( float $fillOpacity )
Warning

This function is currently not documented; only its argument list is available.

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

Parameters

fillOpacity

the fill opacity

Return Values

No value is returned.

ImagickDraw::setFillColor
ImagickDraw::setFillPatternURL
The ImagickDraw class


Sets the URL to use as a fill pattern for filling objects

ImagickDraw::setFillOpacity
ImagickDraw::setFillRule
The ImagickDraw class
PHP Manual

ImagickDraw::setFillPatternURL

(PECL imagick 2.0.0)

ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects

Description

bool ImagickDraw::setFillPatternURL ( string $fill_url )
Warning

This function is currently not documented; only its argument list is available.

Sets the URL to use as a fill pattern for filling objects. Only local URLs ("#identifier") are supported at this time. These local URLs are normally created by defining a named fill pattern with DrawPushPattern/DrawPopPattern.

Parameters

fill_url

URL to use to obtain fill pattern.

Return Values

Returns TRUE on success or FALSE on failure.

ImagickDraw::setFillOpacity
ImagickDraw::setFillRule
The ImagickDraw class


Sets the fill rule to use while drawing polygons

ImagickDraw::setFillPatternURL
ImagickDraw::setFont
The ImagickDraw class
PHP Manual

ImagickDraw::setFillRule

(PECL imagick 2.0.0)

ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons

Description

bool ImagickDraw::setFillRule ( int $fill_rule )
Warning

This function is currently not documented; only its argument list is available.

Sets the fill rule to use while drawing polygons.

Parameters

fill_rule

FILLRULE_ constant

Return Values

No value is returned.

ImagickDraw::setFillPatternURL
ImagickDraw::setFont
The ImagickDraw class


Sets the fully-specified font to use when annotating with text

ImagickDraw::setFillRule
ImagickDraw::setFontFamily
The ImagickDraw class
PHP Manual

ImagickDraw::setFont

(PECL imagick 2.0.0)

ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text

Description

bool ImagickDraw::setFont ( string $font_name )
Warning

This function is currently not documented; only its argument list is available.

Sets the fully-specified font to use when annotating with text.

Parameters

font_name

Return Values

Returns TRUE on success.

ImagickDraw::setFillRule
ImagickDraw::setFontFamily
The ImagickDraw class


Sets the font family to use when annotating with text

ImagickDraw::setFont
ImagickDraw::setFontSize
The ImagickDraw class
PHP Manual

ImagickDraw::setFontFamily

(PECL imagick 2.0.0)

ImagickDraw::setFontFamily — Sets the font family to use when annotating with text

Description

bool ImagickDraw::setFontFamily ( string $font_family )
Warning

This function is currently not documented; only its argument list is available.

Sets the font family to use when annotating with text.

Parameters

font_family

the font family

Return Values

Returns TRUE on success.

ImagickDraw::setFont
ImagickDraw::setFontSize
The ImagickDraw class


Sets the font pointsize to use when annotating with text

ImagickDraw::setFontFamily
ImagickDraw::setFontStretch
The ImagickDraw class
PHP Manual

ImagickDraw::setFontSize

(PECL imagick 2.0.0)

ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text

Description

bool ImagickDraw::setFontSize ( float $pointsize )
Warning

This function is currently not documented; only its argument list is available.

Sets the font pointsize to use when annotating with text.

Parameters

pointsize

the point size

Return Values

No value is returned.

ImagickDraw::setFontFamily
ImagickDraw::setFontStretch
The ImagickDraw class


Sets the font stretch to use when annotating with text

ImagickDraw::setFontSize
ImagickDraw::setFontStyle
The ImagickDraw class
PHP Manual

ImagickDraw::setFontStretch

(PECL imagick 2.0.0)

ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text

Description

bool ImagickDraw::setFontStretch ( int $fontStretch )
Warning

This function is currently not documented; only its argument list is available.

Sets the font stretch to use when annotating with text. The AnyStretch enumeration acts as a wild-card "don't care" option.

Parameters

fontStretch

STRETCH_ constant

Return Values

No value is returned.

ImagickDraw::setFontSize
ImagickDraw::setFontStyle
The ImagickDraw class


Sets the font style to use when annotating with text

ImagickDraw::setFontStretch
ImagickDraw::setFontWeight
The ImagickDraw class
PHP Manual

ImagickDraw::setFontStyle

(PECL imagick 2.0.0)

ImagickDraw::setFontStyle — Sets the font style to use when annotating with text

Description

bool ImagickDraw::setFontStyle ( int $style )
Warning

This function is currently not documented; only its argument list is available.

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

Parameters

style

STYLETYPE_ constant

Return Values

No value is returned.

ImagickDraw::setFontStretch
ImagickDraw::setFontWeight
The ImagickDraw class


Sets the font weight

ImagickDraw::setFontStyle
ImagickDraw::setGravity
The ImagickDraw class
PHP Manual

ImagickDraw::setFontWeight

(PECL imagick 2.0.0)

ImagickDraw::setFontWeight — Sets the font weight

Description

bool ImagickDraw::setFontWeight ( int $font_weight )
Warning

This function is currently not documented; only its argument list is available.

Sets the font weight to use when annotating with text.

Parameters

font_weight

Return Values

ImagickDraw::setFontStyle
ImagickDraw::setGravity
The ImagickDraw class


Sets the text placement gravity

ImagickDraw::setFontWeight
ImagickDraw::setStrokeAlpha
The ImagickDraw class
PHP Manual

ImagickDraw::setGravity

(PECL imagick 2.0.0)

ImagickDraw::setGravity — Sets the text placement gravity

Description

bool ImagickDraw::setGravity ( int $gravity )
Warning

This function is currently not documented; only its argument list is available.

Sets the text placement gravity to use when annotating with text.

Parameters

gravity

GRAVITY_ constant

Return Values

No value is returned.

ImagickDraw::setFontWeight
ImagickDraw::setStrokeAlpha
The ImagickDraw class


Specifies the opacity of stroked object outlines

ImagickDraw::setGravity
ImagickDraw::setStrokeAntialias
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokeAlpha

(PECL imagick 2.0.0)

ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines

Description

bool ImagickDraw::setStrokeAlpha ( float $opacity )
Warning

This function is currently not documented; only its argument list is available.

Specifies the opacity of stroked object outlines.

Parameters

opacity

opacity

Return Values

No value is returned.

ImagickDraw::setGravity
ImagickDraw::setStrokeAntialias
The ImagickDraw class


Controls whether stroked outlines are antialiased

ImagickDraw::setStrokeAlpha
ImagickDraw::setStrokeColor
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokeAntialias

(PECL imagick 2.0.0)

ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased

Description

bool ImagickDraw::setStrokeAntialias ( bool $stroke_antialias )
Warning

This function is currently not documented; only its argument list is available.

Controls whether stroked outlines are antialiased. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

Parameters

stroke_antialias

the antialias setting

Return Values

No value is returned.

ImagickDraw::setStrokeAlpha
ImagickDraw::setStrokeColor
The ImagickDraw class


Sets the color used for stroking object outlines

ImagickDraw::setStrokeAntialias
ImagickDraw::setStrokeDashArray
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokeColor

(PECL imagick 2.0.0)

ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines

Description

bool ImagickDraw::setStrokeColor ( ImagickPixel $stroke_pixel )
Warning

This function is currently not documented; only its argument list is available.

Sets the color used for stroking object outlines.

Parameters

stroke_pixel

the stroke color

Return Values

No value is returned.

ImagickDraw::setStrokeAntialias
ImagickDraw::setStrokeDashArray
The ImagickDraw class


Specifies the pattern of dashes and gaps used to stroke paths

ImagickDraw::setStrokeColor
ImagickDraw::setStrokeDashOffset
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokeDashArray

(PECL imagick 2.0.0)

ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths

Description

bool ImagickDraw::setStrokeDashArray ( array $dashArray )
Warning

This function is currently not documented; only its argument list is available.

Specifies the pattern of dashes and gaps used to stroke paths. The strokeDashArray represents an array of numbers that specify the lengths of alternating dashes and gaps in pixels. If an odd number of values is provided, then the list of values is repeated to yield an even number of values. To remove an existing dash array, pass a zero number_elements argument and null dash_array. A typical strokeDashArray_ array might contain the members 5 3 2.

Parameters

dashArray

array of floats

Return Values

Returns TRUE on success.

ImagickDraw::setStrokeColor
ImagickDraw::setStrokeDashOffset
The ImagickDraw class


Specifies the offset into the dash pattern to start the dash

ImagickDraw::setStrokeDashArray
ImagickDraw::setStrokeLineCap
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokeDashOffset

(PECL imagick 2.0.0)

ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash

Description

bool ImagickDraw::setStrokeDashOffset ( float $dash_offset )
Warning

This function is currently not documented; only its argument list is available.

Specifies the offset into the dash pattern to start the dash.

Parameters

dash_offset

dash offset

Return Values

No value is returned.

ImagickDraw::setStrokeDashArray
ImagickDraw::setStrokeLineCap
The ImagickDraw class


Specifies the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::setStrokeDashOffset
ImagickDraw::setStrokeLineJoin
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokeLineCap

(PECL imagick 2.0.0)

ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked

Description

bool ImagickDraw::setStrokeLineCap ( int $linecap )
Warning

This function is currently not documented; only its argument list is available.

Specifies the shape to be used at the end of open subpaths when they are stroked.

Parameters

linecap

LINECAP_ constant

Return Values

No value is returned.

ImagickDraw::setStrokeDashOffset
ImagickDraw::setStrokeLineJoin
The ImagickDraw class


Specifies the shape to be used at the corners of paths when they are stroked

ImagickDraw::setStrokeLineCap
ImagickDraw::setStrokeMiterLimit
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokeLineJoin

(PECL imagick 2.0.0)

ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked

Description

bool ImagickDraw::setStrokeLineJoin ( int $linejoin )
Warning

This function is currently not documented; only its argument list is available.

Specifies the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

Parameters

linejoin

LINEJOIN_ constant

Return Values

No value is returned.

ImagickDraw::setStrokeLineCap
ImagickDraw::setStrokeMiterLimit
The ImagickDraw class


Specifies the miter limit

ImagickDraw::setStrokeLineJoin
ImagickDraw::setStrokeOpacity
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokeMiterLimit

(PECL imagick 2.0.0)

ImagickDraw::setStrokeMiterLimit — Specifies the miter limit

Description

bool ImagickDraw::setStrokeMiterLimit ( int $miterlimit )
Warning

This function is currently not documented; only its argument list is available.

Specifies the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'.

Parameters

miterlimit

the miter limit

Return Values

No value is returned.

ImagickDraw::setStrokeLineJoin
ImagickDraw::setStrokeOpacity
The ImagickDraw class


Specifies the opacity of stroked object outlines

ImagickDraw::setStrokeMiterLimit
ImagickDraw::setStrokePatternURL
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokeOpacity

(PECL imagick 2.0.0)

ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines

Description

bool ImagickDraw::setStrokeOpacity ( float $stroke_opacity )
Warning

This function is currently not documented; only its argument list is available.

Specifies the opacity of stroked object outlines.

Parameters

stroke_opacity

stroke opacity. 1.0 is fully opaque

Return Values

No value is returned.

ImagickDraw::setStrokeMiterLimit
ImagickDraw::setStrokePatternURL
The ImagickDraw class


Sets the pattern used for stroking object outlines

ImagickDraw::setStrokeOpacity
ImagickDraw::setStrokeWidth
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokePatternURL

(PECL imagick 2.0.0)

ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines

Description

bool ImagickDraw::setStrokePatternURL ( string $stroke_url )
Warning

This function is currently not documented; only its argument list is available.

Sets the pattern used for stroking object outlines.

Parameters

stroke_url

stroke URL

Return Values

imagick.imagickdraw.return.success;

ImagickDraw::setStrokeOpacity
ImagickDraw::setStrokeWidth
The ImagickDraw class


Sets the width of the stroke used to draw object outlines

ImagickDraw::setStrokePatternURL
ImagickDraw::setTextAlignment
The ImagickDraw class
PHP Manual

ImagickDraw::setStrokeWidth

(PECL imagick 2.0.0)

ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines

Description

bool ImagickDraw::setStrokeWidth ( float $stroke_width )
Warning

This function is currently not documented; only its argument list is available.

Sets the width of the stroke used to draw object outlines.

Parameters

stroke_width

stroke width

Return Values

No value is returned.

ImagickDraw::setStrokePatternURL
ImagickDraw::setTextAlignment
The ImagickDraw class


Specifies a text alignment

ImagickDraw::setStrokeWidth
ImagickDraw::setTextAntialias
The ImagickDraw class
PHP Manual

ImagickDraw::setTextAlignment

(PECL imagick 2.0.0)

ImagickDraw::setTextAlignment — Specifies a text alignment

Description

bool ImagickDraw::setTextAlignment ( int $alignment )
Warning

This function is currently not documented; only its argument list is available.

Specifies a text alignment to be applied when annotating with text.

Parameters

alignment

ALIGN_ constant

Return Values

No value is returned.

ImagickDraw::setStrokeWidth
ImagickDraw::setTextAntialias
The ImagickDraw class


Controls whether text is antialiased

ImagickDraw::setTextAlignment
ImagickDraw::setTextDecoration
The ImagickDraw class
PHP Manual

ImagickDraw::setTextAntialias

(PECL imagick 2.0.0)

ImagickDraw::setTextAntialias — Controls whether text is antialiased

Description

bool ImagickDraw::setTextAntialias ( bool $antiAlias )
Warning

This function is currently not documented; only its argument list is available.

Controls whether text is antialiased. Text is antialiased by default.

Parameters

antiAlias

Return Values

No value is returned.

ImagickDraw::setTextAlignment
ImagickDraw::setTextDecoration
The ImagickDraw class


Specifies a decoration

ImagickDraw::setTextAntialias
ImagickDraw::setTextEncoding
The ImagickDraw class
PHP Manual

ImagickDraw::setTextDecoration

(PECL imagick 2.0.0)

ImagickDraw::setTextDecoration — Specifies a decoration

Description

bool ImagickDraw::setTextDecoration ( int $decoration )
Warning

This function is currently not documented; only its argument list is available.

Specifies a decoration to be applied when annotating with text.

Parameters

decoration

DECORATION_ constant

Return Values

No value is returned.

ImagickDraw::setTextAntialias
ImagickDraw::setTextEncoding
The ImagickDraw class


Specifies specifies the text code set

ImagickDraw::setTextDecoration
ImagickDraw::setTextUnderColor
The ImagickDraw class
PHP Manual

ImagickDraw::setTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::setTextEncoding — Specifies specifies the text code set

Description

bool ImagickDraw::setTextEncoding ( string $encoding )
Warning

This function is currently not documented; only its argument list is available.

Specifies specifies the code set to use for text annotations. The only character encoding which may be specified at this time is "UTF-8" for representing Unicode as a sequence of bytes. Specify an empty string to set text encoding to the system's default. Successful text annotation using Unicode may require fonts designed to support Unicode.

Parameters

encoding

the encoding name

Return Values

No value is returned.

ImagickDraw::setTextDecoration
ImagickDraw::setTextUnderColor
The ImagickDraw class


Specifies the color of a background rectangle

ImagickDraw::setTextEncoding
ImagickDraw::setVectorGraphics
The ImagickDraw class
PHP Manual

ImagickDraw::setTextUnderColor

(PECL imagick 2.0.0)

ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle

Description

bool ImagickDraw::setTextUnderColor ( ImagickPixel $under_color )
Warning

This function is currently not documented; only its argument list is available.

Specifies the color of a background rectangle to place under text annotations.

Parameters

under_color

the under color

Return Values

No value is returned.

ImagickDraw::setTextEncoding
ImagickDraw::setVectorGraphics
The ImagickDraw class


Sets the vector graphics

ImagickDraw::setTextUnderColor
ImagickDraw::setViewbox
The ImagickDraw class
PHP Manual

ImagickDraw::setVectorGraphics

(PECL imagick 2.0.0)

ImagickDraw::setVectorGraphics — Sets the vector graphics

Description

bool ImagickDraw::setVectorGraphics ( string $xml )
Warning

This function is currently not documented; only its argument list is available.

Sets the vector graphics associated with the specified ImagickDraw object. Use this method with ImagickDraw::getVectorGraphics() as a method to persist the vector graphics state.

Parameters

xml

xml containing the vector graphics

Return Values

Returns TRUE on success or FALSE on failure.

ImagickDraw::setTextUnderColor
ImagickDraw::setViewbox
The ImagickDraw class


Sets the overall canvas size

ImagickDraw::setVectorGraphics
ImagickDraw::skewX
The ImagickDraw class
PHP Manual

ImagickDraw::setViewbox

(PECL imagick 2.0.0)

ImagickDraw::setViewbox — Sets the overall canvas size

Description

bool ImagickDraw::setViewbox ( int $x1 , int $y1 , int $x2 , int $y2 )
Warning

This function is currently not documented; only its argument list is available.

Sets the overall canvas size to be recorded with the drawing vector data. Usually this will be specified using the same size as the canvas image. When the vector data is saved to SVG or MVG formats, the viewbox is use to specify the size of the canvas image that a viewer will render the vector data on.

Parameters

x1

left x coordinate

y1

left y coordinate

x2

right x coordinate

y2

right y coordinate

Return Values

No value is returned.

ImagickDraw::setVectorGraphics
ImagickDraw::skewX
The ImagickDraw class


Skews the current coordinate system in the horizontal direction

ImagickDraw::setViewbox
ImagickDraw::skewY
The ImagickDraw class
PHP Manual

ImagickDraw::skewX

(PECL imagick 2.0.0)

ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction

Description

bool ImagickDraw::skewX ( float $degrees )
Warning

This function is currently not documented; only its argument list is available.

Skews the current coordinate system in the horizontal direction.

Parameters

degrees

degrees to skew

Return Values

No value is returned.

ImagickDraw::setViewbox
ImagickDraw::skewY
The ImagickDraw class


Skews the current coordinate system in the vertical direction

ImagickDraw::skewX
ImagickDraw::translate
The ImagickDraw class
PHP Manual

ImagickDraw::skewY

(PECL imagick 2.0.0)

ImagickDraw::skewY — Skews the current coordinate system in the vertical direction

Description

bool ImagickDraw::skewY ( float $degrees )
Warning

This function is currently not documented; only its argument list is available.

Skews the current coordinate system in the vertical direction.

Parameters

degrees

degrees to skew

Return Values

No value is returned.

ImagickDraw::skewX
ImagickDraw::translate
The ImagickDraw class


Applies a translation to the current coordinate system

ImagickDraw::skewY
The ImagickPixel class
The ImagickDraw class
PHP Manual

ImagickDraw::translate

(PECL imagick 2.0.0)

ImagickDraw::translate — Applies a translation to the current coordinate system

Description

bool ImagickDraw::translate ( float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Applies a translation to the current coordinate system which moves the coordinate system origin to the specified coordinate.

Parameters

x

horizontal translation

y

vertical translation

Return Values

No value is returned.

ImagickDraw::skewY
The ImagickPixel class
The ImagickDraw class


Clears resources associated with this object

The ImagickPixel class
ImagickPixel::__construct
The ImagickPixel class
PHP Manual

ImagickPixel::clear

(PECL imagick 2.0.0)

ImagickPixel::clear — Clears resources associated with this object

Description

bool ImagickPixel::clear ( void )
Warning

This function is currently not documented; only its argument list is available.

Clears the ImagickPixel object, leaving it in a fresh state. This also unsets any color associated with the object.

Return Values

Returns TRUE on success.

The ImagickPixel class
ImagickPixel::__construct
The ImagickPixel class


The ImagickPixel constructor

ImagickPixel::clear
ImagickPixel::destroy
The ImagickPixel class
PHP Manual

ImagickPixel::__construct

(PECL imagick 2.0.0)

ImagickPixel::__construct — The ImagickPixel constructor

Description

ImagickPixel ImagickPixel::__construct ([ string $color ] )
Warning

This function is currently not documented; only its argument list is available.

Constructs an ImagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

Parameters

color

The optional color string to use as the initial value of this object.

Return Values

Returns an ImagickPixel object on success, throwing ImagickPixelException on failure.

ImagickPixel::clear
ImagickPixel::destroy
The ImagickPixel class


Deallocates resources associated with this object

ImagickPixel::__construct
ImagickPixel::getColor
The ImagickPixel class
PHP Manual

ImagickPixel::destroy

(PECL imagick 2.0.0)

ImagickPixel::destroy — Deallocates resources associated with this object

Description

bool ImagickPixel::destroy ( void )
Warning

This function is currently not documented; only its argument list is available.

Deallocates any resources used by the ImagickPixel object, and unsets any associated color. The object should not be used after the destroy function has been called.

Return Values

Returns TRUE on success.

ImagickPixel::__construct
ImagickPixel::getColor
The ImagickPixel class


Returns the color

ImagickPixel::destroy
ImagickPixel::getColorAsString
The ImagickPixel class
PHP Manual

ImagickPixel::getColor

(PECL imagick 2.0.0)

ImagickPixel::getColor — Returns the color

Description

array ImagickPixel::getColor ([ bool $normalized = false ] )
Warning

This function is currently not documented; only its argument list is available.

Returns the color described by the ImagickPixel object, as an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

Parameters

normalized

Normalize the color values

Return Values

An array of channel values, each normalized if TRUE is given as param. Throws ImagickPixelException on error.

ImagickPixel::destroy
ImagickPixel::getColorAsString
The ImagickPixel class


Returns the color as a string

ImagickPixel::getColor
ImagickPixel::getColorCount
The ImagickPixel class
PHP Manual

ImagickPixel::getColorAsString

(PECL imagick 2.1.0)

ImagickPixel::getColorAsString — Returns the color as a string

Description

string ImagickPixel::getColorAsString ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the color of the ImagickPixel object as a string.

Parameters

Return Values

Returns the color of the ImagickPixel object as a string.

ImagickPixel::getColor
ImagickPixel::getColorCount
The ImagickPixel class


Returns the color count associated with this color

ImagickPixel::getColorAsString
ImagickPixel::getColorValue
The ImagickPixel class
PHP Manual

ImagickPixel::getColorCount

(PECL imagick 2.0.0)

ImagickPixel::getColorCount — Returns the color count associated with this color

Description

int ImagickPixel::getColorCount ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the color count associated with this color.

Return Values

Returns the color count as an integer on success, throws ImagickPixelException on failure.

ImagickPixel::getColorAsString
ImagickPixel::getColorValue
The ImagickPixel class


Gets the normalized value of the provided color channel

ImagickPixel::getColorCount
ImagickPixel::getHSL
The ImagickPixel class
PHP Manual

ImagickPixel::getColorValue

(PECL imagick 2.0.0)

ImagickPixel::getColorValue — Gets the normalized value of the provided color channel

Description

float ImagickPixel::getColorValue ( int $color )
Warning

This function is currently not documented; only its argument list is available.

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

Parameters

color

The channel to check, specified as one of the Imagick channel constants.

Return Values

The value of the channel, as a normalized floating-point number, throwing ImagickPixelException on error.

ImagickPixel::getColorCount
ImagickPixel::getHSL
The ImagickPixel class


Returns the normalized HSL color of the ImagickPixel object

ImagickPixel::getColorValue
ImagickPixel::isSimilar
The ImagickPixel class
PHP Manual

ImagickPixel::getHSL

(PECL imagick 2.0.0)

ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object

Description

array ImagickPixel::getHSL ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the normalized HSL color described by the ImagickPixel object, with each of the three values as floating point numbers between 0.0 and 1.0.

Return Values

Returns the HSL value in an array with the keys "hue", "saturation", and "luminosity". Throws ImagickPixelException on failure.

Notes

Note: Available with ImageMagick library version 6.2.9 and higher.

ImagickPixel::getColorValue
ImagickPixel::isSimilar
The ImagickPixel class


Check the distance between this color and another

ImagickPixel::getHSL
ImagickPixel::setColor
The ImagickPixel class
PHP Manual

ImagickPixel::isSimilar

(PECL imagick 2.0.0)

ImagickPixel::isSimilar — Check the distance between this color and another

Description

bool ImagickPixel::isSimilar ( ImagickPixel $color , float $fuzz )
Warning

This function is currently not documented; only its argument list is available.

Checks the distance between the color described by this ImagickPixel object and that of the provided object, by plotting their RGB values on the color cube. If the distance between the two points is less than the fuzz value given, the colors are similar.

Parameters

color

The ImagickPixel object to compare this object against.

fuzz

The maximum distance within which to consider these colors as similar. The theoretical maximum for this value is the square root of three (1.732).

Return Values

Returns TRUE on success.

ImagickPixel::getHSL
ImagickPixel::setColor
The ImagickPixel class


Sets the color

ImagickPixel::isSimilar
ImagickPixel::setColorValue
The ImagickPixel class
PHP Manual

ImagickPixel::setColor

(PECL imagick 2.0.0)

ImagickPixel::setColor — Sets the color

Description

bool ImagickPixel::setColor ( string $color )
Warning

This function is currently not documented; only its argument list is available.

Sets the color described by the ImagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.).

Parameters

color

The color definition to use in order to initialise the ImagickPixel object.

Return Values

Returns TRUE if the specified color was set, FALSE otherwise.

ImagickPixel::isSimilar
ImagickPixel::setColorValue
The ImagickPixel class


Sets the normalized value of one of the channels

ImagickPixel::setColor
ImagickPixel::setHSL
The ImagickPixel class
PHP Manual

ImagickPixel::setColorValue

(PECL imagick 2.0.0)

ImagickPixel::setColorValue — Sets the normalized value of one of the channels

Description

bool ImagickPixel::setColorValue ( int $color , float $value )
Warning

This function is currently not documented; only its argument list is available.

Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to an ImagickPixel object.

Parameters

color

One of the Imagick channel color constants.

value

The value to set this channel to, ranging from 0 to 1.

Return Values

Returns TRUE on success.

ImagickPixel::setColor
ImagickPixel::setHSL
The ImagickPixel class


Sets the normalized HSL color

ImagickPixel::setColorValue
The ImagickPixelIterator class
The ImagickPixel class
PHP Manual

ImagickPixel::setHSL

(PECL imagick 2.0.0)

ImagickPixel::setHSL — Sets the normalized HSL color

Description

bool ImagickPixel::setHSL ( float $hue , float $saturation , float $luminosity )
Warning

This function is currently not documented; only its argument list is available.

Sets the color described by the ImagickPixel object using normalized values for hue, saturation and luminosity.

Parameters

hue

The normalized value for hue, described as a fractional arc (between 0 and 1) of the hue circle, where the zero value is red.

saturation

The normalized value for saturation, with 1 as full saturation.

luminosity

The normalized value for luminosity, on a scale from black at 0 to white at 1, with the full HS value at 0.5 luminosity.

Return Values

Returns TRUE on success.

Notes

Note: Available with ImageMagick library version 6.2.9 and higher.

ImagickPixel::setColorValue
The ImagickPixelIterator class
The ImagickPixel class


Clear resources associated with a PixelIterator

The ImagickPixelIterator class
ImagickPixelIterator::__construct
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::clear

(PECL imagick 2.0.0)

ImagickPixelIterator::clear — Clear resources associated with a PixelIterator

Description

bool ImagickPixelIterator::clear ( void )
Warning

This function is currently not documented; only its argument list is available.

Clear resources associated with a PixelIterator.

Return Values

Returns TRUE on success.

The ImagickPixelIterator class
ImagickPixelIterator::__construct
The ImagickPixelIterator class


The ImagickPixelIterator constructor

ImagickPixelIterator::clear
ImagickPixelIterator::destroy
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::__construct

(PECL imagick 2.0.0)

ImagickPixelIterator::__construct — The ImagickPixelIterator constructor

Description

ImagickPixelIterator ImagickPixelIterator::__construct ( Imagick $wand )
Warning

This function is currently not documented; only its argument list is available.

The ImagickPixelIterator constructor

Return Values

Returns TRUE on success.

ImagickPixelIterator::clear
ImagickPixelIterator::destroy
The ImagickPixelIterator class


Deallocates resources associated with a PixelIterator

ImagickPixelIterator::__construct
ImagickPixelIterator::getCurrentIteratorRow
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::destroy

(PECL imagick 2.0.0)

ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator

Description

bool ImagickPixelIterator::destroy ( void )
Warning

This function is currently not documented; only its argument list is available.

Deallocates resources associated with a PixelIterator.

Return Values

Returns TRUE on success.

ImagickPixelIterator::__construct
ImagickPixelIterator::getCurrentIteratorRow
The ImagickPixelIterator class


Returns the current row of ImagickPixel objects

ImagickPixelIterator::destroy
ImagickPixelIterator::getIteratorRow
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::getCurrentIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects

Description

array ImagickPixelIterator::getCurrentIteratorRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the current row as an array of ImagickPixel objects from the pixel iterator.

Return Values

Returns a row as an array of ImagickPixel objects that can themselves be iterated.

ImagickPixelIterator::destroy
ImagickPixelIterator::getIteratorRow
The ImagickPixelIterator class


Returns the current pixel iterator row

ImagickPixelIterator::getCurrentIteratorRow
ImagickPixelIterator::getNextIteratorRow
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::getIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row

Description

int ImagickPixelIterator::getIteratorRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the current pixel iterator row.

Return Values

Returns the integer offset of the row, throwing ImagickPixelIteratorException on error.

ImagickPixelIterator::getCurrentIteratorRow
ImagickPixelIterator::getNextIteratorRow
The ImagickPixelIterator class


Returns the next row of the pixel iterator

ImagickPixelIterator::getIteratorRow
ImagickPixelIterator::getPreviousIteratorRow
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::getNextIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator

Description

array ImagickPixelIterator::getNextIteratorRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the next row as an array of pixel wands from the pixel iterator.

Return Values

Returns the next row as an array of ImagickPixel objects, throwing ImagickPixelIteratorException on error.

ImagickPixelIterator::getIteratorRow
ImagickPixelIterator::getPreviousIteratorRow
The ImagickPixelIterator class


Returns the previous row

ImagickPixelIterator::getNextIteratorRow
ImagickPixelIterator::newPixelIterator
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::getPreviousIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row

Description

array ImagickPixelIterator::getPreviousIteratorRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the previous row as an array of pixel wands from the pixel iterator.

Return Values

Returns the previous row as an array of ImagickPixelWand objects from the ImagickPixelIterator, throwing ImagickPixelIteratorException on error.

ImagickPixelIterator::getNextIteratorRow
ImagickPixelIterator::newPixelIterator
The ImagickPixelIterator class


Returns a new pixel iterator

ImagickPixelIterator::getPreviousIteratorRow
ImagickPixelIterator::newPixelRegionIterator
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::newPixelIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator

Description

bool ImagickPixelIterator::newPixelIterator ( Imagick $wand )
Warning

This function is currently not documented; only its argument list is available.

Returns a new pixel iterator.

Return Values

Returns TRUE on success. Throwing ImagickPixelIteratorException.

ImagickPixelIterator::getPreviousIteratorRow
ImagickPixelIterator::newPixelRegionIterator
The ImagickPixelIterator class


Returns a new pixel iterator

ImagickPixelIterator::newPixelIterator
ImagickPixelIterator::resetIterator
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::newPixelRegionIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator

Description

bool ImagickPixelIterator::newPixelRegionIterator ( Imagick $wand , int $x , int $y , int $columns , int $rows )
Warning

This function is currently not documented; only its argument list is available.

Returns a new pixel iterator.

Parameters

wand

x

y

columns

rows

Return Values

Returns a new ImagickPixelIterator on success; on failure, throws ImagickPixelIteratorException.

ImagickPixelIterator::newPixelIterator
ImagickPixelIterator::resetIterator
The ImagickPixelIterator class


Resets the pixel iterator

ImagickPixelIterator::newPixelRegionIterator
ImagickPixelIterator::setIteratorFirstRow
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::resetIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::resetIterator — Resets the pixel iterator

Description

bool ImagickPixelIterator::resetIterator ( void )
Warning

This function is currently not documented; only its argument list is available.

Resets the pixel iterator. Use it in conjunction with ImagickPixelIterator::getNextIteratorRow() to iterate over all the pixels in a pixel container.

Return Values

Returns TRUE on success.

ImagickPixelIterator::newPixelRegionIterator
ImagickPixelIterator::setIteratorFirstRow
The ImagickPixelIterator class


Sets the pixel iterator to the first pixel row

ImagickPixelIterator::resetIterator
ImagickPixelIterator::setIteratorLastRow
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::setIteratorFirstRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row

Description

bool ImagickPixelIterator::setIteratorFirstRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Sets the pixel iterator to the first pixel row.

Return Values

Returns TRUE on success.

ImagickPixelIterator::resetIterator
ImagickPixelIterator::setIteratorLastRow
The ImagickPixelIterator class


Sets the pixel iterator to the last pixel row

ImagickPixelIterator::setIteratorFirstRow
ImagickPixelIterator::setIteratorRow
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::setIteratorLastRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row

Description

bool ImagickPixelIterator::setIteratorLastRow ( void )
Warning

This function is currently not documented; only its argument list is available.

Sets the pixel iterator to the last pixel row.

Return Values

Returns TRUE on success.

ImagickPixelIterator::setIteratorFirstRow
ImagickPixelIterator::setIteratorRow
The ImagickPixelIterator class


Set the pixel iterator row

ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator::syncIterator
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::setIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorRow — Set the pixel iterator row

Description

bool ImagickPixelIterator::setIteratorRow ( int $row )
Warning

This function is currently not documented; only its argument list is available.

Set the pixel iterator row.

Parameters

row

Return Values

Returns TRUE on success.

ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator::syncIterator
The ImagickPixelIterator class


Syncs the pixel iterator

ImagickPixelIterator::setIteratorRow
Gmagick
The ImagickPixelIterator class
PHP Manual

ImagickPixelIterator::syncIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::syncIterator — Syncs the pixel iterator

Description

bool ImagickPixelIterator::syncIterator ( void )
Warning

This function is currently not documented; only its argument list is available.

Syncs the pixel iterator.

Return Values

Returns TRUE on success.

ImagickPixelIterator::setIteratorRow
Gmagick
The ImagickPixelIterator class


Convert an 8bit string to a quoted-printable string

IMAP Functions
imap_alerts
IMAP Functions
PHP Manual

imap_8bit

(PHP 4, PHP 5)

imap_8bit — Convert an 8bit string to a quoted-printable string

Description

string imap_8bit ( string $string )

Convert an 8bit string to a quoted-printable string (according to » RFC2045, section 6.7).

Parameters

string

The 8bit string to convert

Return Values

Returns a quoted-printable string.

See Also

  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

IMAP Functions
imap_alerts
IMAP Functions


Returns all IMAP alert messages that have occurred

imap_8bit
imap_append
IMAP Functions
PHP Manual

imap_alerts

(PHP 4, PHP 5)

imap_alerts — Returns all IMAP alert messages that have occurred

Description

array imap_alerts ( void )

Returns all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page.

When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.

Return Values

Returns an array of all of the IMAP alert messages generated or FALSE if no alert messages are available.

See Also

  • imap_errors() - Returns all of the IMAP errors that have occured

imap_8bit
imap_append
IMAP Functions


Append a string message to a specified mailbox

imap_alerts
imap_base64
IMAP Functions
PHP Manual

imap_append

(PHP 4, PHP 5)

imap_append — Append a string message to a specified mailbox

Description

bool imap_append ( resource $imap_stream , string $mailbox , string $message [, string $options = NULL ] )

Appends a string message to the specified mailbox .

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

message

The message to be append, as a string

When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail

options

If provided, the options will also be written to the mailbox

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imap_append() example

<?php
$stream = imap_open("{imap.example.org}INBOX.Drafts", "username", "password");

$check = imap_check($stream);
echo "Msg Count before append: ". $check->Nmsgs . "\n";

imap_append($stream, "{imap.example.org}INBOX.Drafts"
                   , "From: me@example.com\r\n"
                   . "To: you@example.com\r\n"
                   . "Subject: test\r\n"
                   . "\r\n"
                   . "this is a test message, please ignore\r\n"
                   );

$check = imap_check($stream);
echo "Msg Count after append : ". $check->Nmsgs . "\n";

imap_close($stream);
?>

imap_alerts
imap_base64
IMAP Functions


Decode BASE64 encoded text

imap_append
imap_binary
IMAP Functions
PHP Manual

imap_base64

(PHP 4, PHP 5)

imap_base64 — Decode BASE64 encoded text

Description

string imap_base64 ( string $text )

Decodes the given BASE-64 encoded text .

Parameters

text

The encoded text

Return Values

Returns the decoded message as a string.

See Also

  • imap_binary() - Convert an 8bit string to a base64 string
  • base64_encode() - Encodes data with MIME base64
  • base64_decode() - Decodes data encoded with MIME base64
  • » RFC2045, Section 6.8

imap_append
imap_binary
IMAP Functions


Convert an 8bit string to a base64 string

imap_base64
imap_body
IMAP Functions
PHP Manual

imap_binary

(PHP 4, PHP 5)

imap_binary — Convert an 8bit string to a base64 string

Description

string imap_binary ( string $string )

Convert an 8bit string to a base64 string according to » RFC2045, Section 6.8.

Parameters

string

The 8bit string

Return Values

Returns a base64 encoded string.

See Also

  • imap_base64() - Decode BASE64 encoded text

imap_base64
imap_body
IMAP Functions


Read the message body

imap_binary
imap_bodystruct
IMAP Functions
PHP Manual

imap_body

(PHP 4, PHP 5)

imap_body — Read the message body

Description

string imap_body ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

imap_body() returns the body of the message, numbered msg_number in the current mailbox.

imap_body() will only return a verbatim copy of the message body. To extract single parts of a multipart MIME-encoded message you have to use imap_fetchstructure() to analyze its structure and imap_fetchbody() to extract a copy of a single body component.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

The optional options are a bit mask with one or more of the following:

  • FT_UID - The msg_number is a UID
  • FT_PEEK - Do not set the \Seen flag if not already set
  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Return Values

Returns the body of the specified message, as a string.

imap_binary
imap_bodystruct
IMAP Functions


Read the structure of a specified body section of a specific message

imap_body
imap_check
IMAP Functions
PHP Manual

imap_bodystruct

(PHP 4, PHP 5)

imap_bodystruct — Read the structure of a specified body section of a specific message

Description

object imap_bodystruct ( resource $imap_stream , int $msg_number , string $section )

Read the structure of a specified body section of a specific message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

section

The body section to read

Return Values

Returns the information in an object, for a detailed description of the object structure and properties see imap_fetchstructure().

See Also

  • imap_fetchstructure() - Read the structure of a particular message

imap_body
imap_check
IMAP Functions


Check current mailbox

imap_bodystruct
imap_clearflag_full
IMAP Functions
PHP Manual

imap_check

(PHP 4, PHP 5)

imap_check — Check current mailbox

Description

object imap_check ( resource $imap_stream )

Checks information about the current mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns the information in an object with following properties:

  • Date - current system time formatted according to » RFC2822
  • Driver - protocol used to access this mailbox: POP3, IMAP, NNTP
  • Mailbox - the mailbox name
  • Nmsgs - number of messages in the mailbox
  • Recent - number of recent messages in the mailbox

Returns FALSE on failure.

Examples

Example #1 imap_check() example

<?php

$imap_obj = imap_check($imap_stream);
var_dump($imap_obj);

?>

The above example will output something similar to:

object(stdClass)(5) {
  ["Date"]=>
  string(37) "Wed, 10 Dec 2003 17:56:54 +0100 (CET)"
  ["Driver"]=>
  string(4) "imap"
  ["Mailbox"]=>
  string(54)
  "{www.example.com:143/imap/user="foo@example.com"}INBOX"
  ["Nmsgs"]=>
  int(1)
  ["Recent"]=>
  int(0)
}

imap_bodystruct
imap_clearflag_full
IMAP Functions


Clears flags on messages

imap_check
imap_close
IMAP Functions
PHP Manual

imap_clearflag_full

(PHP 4, PHP 5)

imap_clearflag_full — Clears flags on messages

Description

bool imap_clearflag_full ( resource $imap_stream , string $sequence , string $flag [, int $options = 0 ] )

This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence .

Parameters

imap_stream

An IMAP stream returned by imap_open().

sequence

A sequence of message numbers. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

flag

The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by » RFC2060)

options

options are a bit mask and may contain the single option:

  • ST_UID - The sequence argument contains UIDs instead of sequence numbers

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_setflag_full() - Sets flags on messages

imap_check
imap_close
IMAP Functions


Close an IMAP stream

imap_clearflag_full
imap_createmailbox
IMAP Functions
PHP Manual

imap_close

(PHP 4, PHP 5)

imap_close — Close an IMAP stream

Description

bool imap_close ( resource $imap_stream [, int $flag = 0 ] )

Closes the imap stream.

Parameters

imap_stream

An IMAP stream returned by imap_open().

flag

If set to CL_EXPUNGE, the function will silently expunge the mailbox before closing, removing all messages marked for deletion. You can achieve the same thing by using imap_expunge()

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_open() - Open an IMAP stream to a mailbox

imap_clearflag_full
imap_createmailbox
IMAP Functions


Create a new mailbox

imap_close
imap_delete
IMAP Functions
PHP Manual

imap_createmailbox

(PHP 4, PHP 5)

imap_createmailbox — Create a new mailbox

Description

bool imap_createmailbox ( resource $imap_stream , string $mailbox )

Creates a new mailbox specified by mailbox .

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information. Names containing international characters should be encoded by imap_utf7_encode()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imap_createmailbox() example

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
     or die("can't connect: " . imap_last_error());

$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewb&ouml;x");

$newname = $name1;

echo "Newname will be '$name1'<br />\n";

// we will now create a new mailbox "phptestbox" in your inbox folder,
// check its status after creation and finaly remove it to restore
// your inbox to its initial state

if (@imap_createmailbox($mbox, imap_utf7_encode("{imap.example.org}INBOX.$newname"))) {
    $status = @imap_status($mbox, "{imap.example.org}INBOX.$newname", SA_ALL);
    if ($status) {
        echo "your new mailbox '$name1' has the following status:<br />\n";
        echo "Messages:   " . $status->messages    . "<br />\n";
        echo "Recent:     " . $status->recent      . "<br />\n";
        echo "Unseen:     " . $status->unseen      . "<br />\n";
        echo "UIDnext:    " . $status->uidnext     . "<br />\n";
        echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";

        if (imap_renamemailbox($mbox, "{imap.example.org}INBOX.$newname", "{imap.example.org}INBOX.$name2")) {
            echo "renamed new mailbox from '$name1' to '$name2'<br />\n";
            $newname = $name2;
        } else {
            echo "imap_renamemailbox on new mailbox failed: " . imap_last_error() . "<br />\n";
        }
    } else {
        echo "imap_status on new mailbox failed: " . imap_last_error() . "<br />\n";
    }

    if (@imap_deletemailbox($mbox, "{imap.example.org}INBOX.$newname")) {
        echo "new mailbox removed to restore initial state<br />\n";
    } else {
        echo "imap_deletemailbox on new mailbox failed: " . implode("<br />\n", imap_errors()) . "<br />\n";
    }

} else {
    echo "could not create new mailbox: " . implode("<br />\n", imap_errors()) . "<br />\n";
}

imap_close($mbox);
?>

See Also

  • imap_renamemailbox() - Rename an old mailbox to new mailbox
  • imap_deletemailbox() - Delete a mailbox

imap_close
imap_delete
IMAP Functions


Mark a message for deletion from current mailbox

imap_createmailbox
imap_deletemailbox
IMAP Functions
PHP Manual

imap_delete

(PHP 4, PHP 5)

imap_delete — Mark a message for deletion from current mailbox

Description

bool imap_delete ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

Marks messages listed in msg_number for deletion. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter CL_EXPUNGE.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

You can set the FT_UID which tells the function to treat the msg_number argument as an UID.

Return Values

Returns TRUE.

Examples

Example #1 imap_delete() example

<?php

$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
    or die("Can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);
echo "Messages before delete: " . $check->Nmsgs . "<br />\n";

imap_delete($mbox, 1);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after  delete: " . $check->Nmsgs . "<br />\n";

imap_expunge($mbox);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";

imap_close($mbox);
?>

Notes

Note: POP3 mailboxes do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.

See Also

  • imap_undelete() - Unmark the message which is marked deleted
  • imap_expunge() - Delete all messages marked for deletion
  • imap_close() - Close an IMAP stream

imap_createmailbox
imap_deletemailbox
IMAP Functions


Delete a mailbox

imap_delete
imap_errors
IMAP Functions
PHP Manual

imap_deletemailbox

(PHP 4, PHP 5)

imap_deletemailbox — Delete a mailbox

Description

bool imap_deletemailbox ( resource $imap_stream , string $mailbox )

Deletes the specified mailbox .

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_createmailbox() - Create a new mailbox
  • imap_renamemailbox() - Rename an old mailbox to new mailbox
  • imap_open() - Open an IMAP stream to a mailbox for the format of mbox

imap_delete
imap_errors
IMAP Functions


Returns all of the IMAP errors that have occured

imap_deletemailbox
imap_expunge
IMAP Functions
PHP Manual

imap_errors

(PHP 4, PHP 5)

imap_errors — Returns all of the IMAP errors that have occured

Description

array imap_errors ( void )

Gets all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.

When imap_errors() is called, the error stack is subsequently cleared.

Return Values

This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. Returns FALSE if no error messages are available.

See Also

  • imap_last_error() - Gets the last IMAP error that occurred during this page request
  • imap_alerts() - Returns all IMAP alert messages that have occurred

imap_deletemailbox
imap_expunge
IMAP Functions


Delete all messages marked for deletion

imap_errors
imap_fetch_overview
IMAP Functions
PHP Manual

imap_expunge

(PHP 4, PHP 5)

imap_expunge — Delete all messages marked for deletion

Description

bool imap_expunge ( resource $imap_stream )

Deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns TRUE.

imap_errors
imap_fetch_overview
IMAP Functions


Read an overview of the information in the headers of the given message

imap_expunge
imap_fetchbody
IMAP Functions
PHP Manual

imap_fetch_overview

(PHP 4, PHP 5)

imap_fetch_overview — Read an overview of the information in the headers of the given message

Description

array imap_fetch_overview ( resource $imap_stream , string $sequence [, int $options = 0 ] )

This function fetches mail headers for the given sequence and returns an overview of their contents.

Parameters

imap_stream

An IMAP stream returned by imap_open().

sequence

A message sequence description. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

options

sequence will contain a sequence of message indices or UIDs, if this parameter is set to FT_UID.

Return Values

Returns an array of objects describing one message header each. The object will only define a property if it exists. The possible properties are:

  • subject - the messages subject
  • from - who sent it
  • to - recipient
  • date - when was it sent
  • message_id - Message-ID
  • references - is a reference to this message id
  • in_reply_to - is a reply to this message id
  • size - size in bytes
  • uid - UID the message has in the mailbox
  • msgno - message sequence number in the mailbox
  • recent - this message is flagged as recent
  • flagged - this message is flagged
  • answered - this message is flagged as answered
  • deleted - this message is flagged for deletion
  • seen - this message is flagged as already read
  • draft - this message is flagged as being a draft

Examples

Example #1 imap_fetch_overview() example

<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password")
     or die("can't connect: " . imap_last_error());

$MC = imap_check($mbox);

// Fetch an overview for all messages in INBOX
$result = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
foreach ($result as $overview) {
    echo "#{$overview->msgno} ({$overview->date}) - From: {$overview->from}
    {$overview->subject}\n";
}
imap_close($mbox);
?>

See Also

  • imap_fetchheader() - Returns header for a message

imap_expunge
imap_fetchbody
IMAP Functions


Fetch a particular section of the body of the message

imap_fetch_overview
imap_fetchheader
IMAP Functions
PHP Manual

imap_fetchbody

(PHP 4, PHP 5)

imap_fetchbody — Fetch a particular section of the body of the message

Description

string imap_fetchbody ( resource $imap_stream , int $msg_number , string $section [, int $options = 0 ] )

Fetch of a particular section of the body of the specified messages. Body parts are not decoded by this function.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

section

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

options

A bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID
  • FT_PEEK - Do not set the \Seen flag if not already set
  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Return Values

Returns a particular section of the body of the specified messages as a text string.

See Also

  • imap_savebody() - Save a specific body section to a file
  • imap_fetchstructure() - Read the structure of a particular message

imap_fetch_overview
imap_fetchheader
IMAP Functions


Returns header for a message

imap_fetchbody
imap_fetchstructure
IMAP Functions
PHP Manual

imap_fetchheader

(PHP 4, PHP 5)

imap_fetchheader — Returns header for a message

Description

string imap_fetchheader ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

This function causes a fetch of the complete, unfiltered » RFC2822 format header of the specified message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

The possible options are:

  • FT_UID - The msgno argument is a UID
  • FT_INTERNAL - The return string is in "internal" format, without any attempt to canonicalize to CRLF newlines
  • FT_PREFETCHTEXT - The RFC822.TEXT should be pre-fetched at the same time. This avoids an extra RTT on an IMAP connection if a full message text is desired (e.g. in a "save to local file" operation)

Return Values

Returns the header of the specified message as a text string.

See Also

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message

imap_fetchbody
imap_fetchstructure
IMAP Functions


Read the structure of a particular message

imap_fetchheader
imap_gc
IMAP Functions
PHP Manual

imap_fetchstructure

(PHP 4, PHP 5)

imap_fetchstructure — Read the structure of a particular message

Description

object imap_fetchstructure ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

Fetches all the structured information for a given message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

This optional parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID.

Return Values

Returns an object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachment. The structure of the returned objects is as follows:

Returned Objects for imap_fetchstructure()
type | Primary body type
encoding | Body transfer encoding
ifsubtype | TRUE if there is a subtype string
subtype | MIME subtype
ifdescription | TRUE if there is a description string
description | Content description string
ifid | TRUE if there is an identification string
id | Identification string
lines | Number of lines
bytes | Number of bytes
ifdisposition | TRUE if there is a disposition string
disposition | Disposition string
ifdparameters | TRUE if the dparameters array exists
dparameters | An array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIME header.
ifparameters | TRUE if the parameters array exists
parameters | An array of objects where each object has an "attribute" and a "value" property.
parts | An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.

Primary body type (may vary with used library)
0 | text
1 | multipart
2 | message
3 | application
4 | audio
5 | image
6 | video
7 | other

Transfer encodings (may vary with used library)
0 | 7BIT
1 | 8BIT
2 | BINARY
3 | BASE64
4 | QUOTED-PRINTABLE
5 | OTHER

See Also

  • imap_fetchbody() - Fetch a particular section of the body of the message
  • imap_bodystruct() - Read the structure of a specified body section of a specific message

imap_fetchheader
imap_gc
IMAP Functions


Clears IMAP cache

imap_fetchstructure
imap_get_quota
IMAP Functions
PHP Manual

imap_gc

(PHP 5 >= 5.3.0)

imap_gc — Clears IMAP cache

Description

string imap_gc ( resource $imap_stream , int $caches )

Purges the cache of entries of a specific type.

Parameters

imap_stream

An IMAP stream returned by imap_open().

caches

Specifies the cache to purge. It may one or a combination of the following constants: IMAP_GC_ELT (message cache elements), IMAP_GC_ENV (enveloppe and bodies), IMAP_GC_TEXTS (texts).

Return Values

Returns TRUE.

Examples

Example #1 imap_gc() example

<?php

$mbox = imap_open("{imap.example.org:143}", "username", "password");

imap_gc($mbox, IMAP_GC_ELT);

?>

imap_fetchstructure
imap_get_quota
IMAP Functions


Retrieve the quota level settings, and usage statics per mailbox

imap_gc
imap_get_quotaroot
IMAP Functions
PHP Manual

imap_get_quota

(PHP 4 >= 4.0.5, PHP 5)

imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox

Description

array imap_get_quota ( resource $imap_stream , string $quota_root )

Retrieve the quota level settings, and usage statics per mailbox.

For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.

Parameters

imap_stream

An IMAP stream returned by imap_open().

quota_root

quota_root should normally be in the form of user.name where name is the mailbox you wish to retrieve information about.

Return Values

Returns an array with integer values limit and usage for the given mailbox. The value of limit represents the total amount of space allowed for this mailbox. The usage value represents the mailboxes current level of capacity. Will return FALSE in the case of failure.

As of PHP 4.3, the function more properly reflects the functionality as dictated by the » RFC2087. The array return value has changed to support an unlimited number of returned resources (i.e. messages, or sub-folders) with each named resource receiving an individual array key. Each key value then contains an another array with the usage and limit values within it.

For backwards compatibility reasons, the original access methods are still available for use, although it is suggested to update.

Examples

Example #1 imap_get_quota() example

<?php
$mbox = imap_open("{imap.example.org}", "mailadmin", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota_value = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_value)) {
    echo "Usage level is: " . $quota_value['usage'];
    echo "Limit level is: " . $quota_value['limit'];
}

imap_close($mbox);
?>

Example #2 imap_get_quota() 4.3 or greater example

<?php
$mbox = imap_open("{imap.example.org}", "mailadmin", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota_values = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_values)) {
   $storage = $quota_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit is: " .  $message['limit'];

   /* ...  */
}

imap_close($mbox);
?>

Notes

This function is currently only available to users of the c-client2000 or greater library.

The given imap_stream must be opened as the mail administrator, otherwise this function will fail.

See Also

  • imap_open() - Open an IMAP stream to a mailbox
  • imap_set_quota() - Sets a quota for a given mailbox
  • imap_get_quotaroot() - Retrieve the quota settings per user

imap_gc
imap_get_quotaroot
IMAP Functions


Retrieve the quota settings per user

imap_get_quota
imap_getacl
IMAP Functions
PHP Manual

imap_get_quotaroot

(PHP 4 >= 4.3.0, PHP 5)

imap_get_quotaroot — Retrieve the quota settings per user

Description

array imap_get_quotaroot ( resource $imap_stream , string $quota_root )

Retrieve the quota settings per user. The limit value represents the total amount of space allowed for this user's total mailbox usage. The usage value represents the user's current total mailbox capacity.

Parameters

imap_stream

An IMAP stream returned by imap_open().

quota_root

quota_root should normally be in the form of which mailbox (i.e. INBOX).

Return Values

Returns an array of integer values pertaining to the specified user mailbox. All values contain a key based upon the resource name, and a corresponding array with the usage and limit values within.

This function will return FALSE in the case of call failure, and an array of information about the connection upon an un-parsable response from the server.

Examples

Example #1 imap_get_quotaroot() example

<?php
$mbox = imap_open("{imap.example.org}", "kalowsky", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota = imap_get_quotaroot($mbox, "INBOX");
if (is_array($quota)) {
   $storage = $quota_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit level is: " .  $message['limit'];

   /* ...  */

}

imap_close($mbox);
?>

Notes

This function is currently only available to users of the c-client2000 or greater library.

The imap_stream should be opened as the user whose mailbox you wish to check.

See Also

  • imap_open() - Open an IMAP stream to a mailbox
  • imap_set_quota() - Sets a quota for a given mailbox
  • imap_get_quota() - Retrieve the quota level settings, and usage statics per mailbox

imap_get_quota
imap_getacl
IMAP Functions


Gets the ACL for a given mailbox

imap_get_quotaroot
imap_getmailboxes
IMAP Functions
PHP Manual

imap_getacl

(PHP 5)

imap_getacl — Gets the ACL for a given mailbox

Description

array imap_getacl ( resource $imap_stream , string $mailbox )

Gets the ACL for a given mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

Return Values

Returns an associative array of "folder" => "acl" pairs.

Examples

Example #1 imap_getacl() example

<?php

print_r(imap_getacl($conn_id, 'user.joecool'));

?>

The above example will output something similar to:

Array
(
    [asubfolder] => lrswipcda
    [anothersubfolder] => lrswipcda
)

Notes

This function is currently only available to users of the c-client2000 or greater library.

See Also

  • imap_setacl() - Sets the ACL for a giving mailbox

imap_get_quotaroot
imap_getmailboxes
IMAP Functions


Read the list of mailboxes, returning detailed information on each one

imap_getacl
imap_getsubscribed
IMAP Functions
PHP Manual

imap_getmailboxes

(PHP 4, PHP 5)

imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one

Description

array imap_getmailboxes ( resource $imap_stream , string $ref , string $pattern )

Gets information on the mailboxes.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern : '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Return Values

Returns an array of objects containing mailbox information. Each object has the attributes name , specifying the full name of the mailbox; delimiter , which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes . Attributes is a bitmask that can be tested against:

  • LATT_NOINFERIORS - This mailbox contains, and may not contain any "children" (there are no mailboxes below this one). Calling imap_createmailbox() will not work on this mailbox.

  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.

  • LATT_MARKED - This mailbox is marked. This means that it may contain new messages since the last time it was checked. Not provided by all IMAP servers.

  • LATT_UNMARKED - This mailbox is not marked, does not contain new messages. If either MARKED or UNMARKED is provided, you can assume the IMAP server supports this feature for this mailbox.

Examples

Example #1 imap_getmailboxes() example

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$list = imap_getmailboxes($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
    foreach ($list as $key => $val) {
        echo "($key) ";
        echo imap_utf7_decode($val->name) . ",";
        echo "'" . $val->delimiter . "',";
        echo $val->attributes . "<br />\n";
    }
} else {
    echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

See Also

  • imap_getsubscribed() - List all the subscribed mailboxes

imap_getacl
imap_getsubscribed
IMAP Functions


List all the subscribed mailboxes

imap_getmailboxes
imap_header
IMAP Functions
PHP Manual

imap_getsubscribed

(PHP 4, PHP 5)

imap_getsubscribed — List all the subscribed mailboxes

Description

array imap_getsubscribed ( resource $imap_stream , string $ref , string $pattern )

Gets information about the subscribed mailboxes.

Identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern : '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Return Values

Returns an array of objects containing mailbox information. Each object has the attributes name , specifying the full name of the mailbox; delimiter , which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes . Attributes is a bitmask that can be tested against:

  • LATT_NOINFERIORS - This mailbox has no "children" (there are no mailboxes below this one).
  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.
  • LATT_MARKED - This mailbox is marked. Only used by UW-IMAPD.
  • LATT_UNMARKED - This mailbox is not marked. Only used by UW-IMAPD.

imap_getmailboxes
imap_header
IMAP Functions


Alias of imap_headerinfo

imap_getsubscribed
imap_headerinfo
IMAP Functions
PHP Manual

imap_header

(PHP 4, PHP 5)

imap_header — Alias of imap_headerinfo()

Description

This function is an alias of: imap_headerinfo().

imap_getsubscribed
imap_headerinfo
IMAP Functions


Read the header of the message

imap_header
imap_headers
IMAP Functions
PHP Manual

imap_headerinfo

(PHP 4, PHP 5)

imap_headerinfo — Read the header of the message

Description

object imap_headerinfo ( resource $imap_stream , int $msg_number [, int $fromlength = 0 [, int $subjectlength = 0 [, string $defaulthost = NULL ]]] )

Gets information about the given message number by reading its headers.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

fromlength

Number of characters for the fetchfrom property. Must be greater than or equal to zero.

subjectlength

Number of characters for the fetchsubject property Must be greater than or equal to zero.

defaulthost

Return Values

Returns the information in an object with following properties:

  • toaddress - full to: line, up to 1024 characters
  • to - an array of objects from the To: line, with the following properties: personal, adl, mailbox, and host
  • fromaddress - full from: line, up to 1024 characters
  • from - an array of objects from the From: line, with the following properties: personal, adl, mailbox, and host
  • ccaddress - full cc: line, up to 1024 characters
  • cc - an array of objects from the Cc: line, with the following properties: personal, adl, mailbox, and host
  • bccaddress - full bcc: line, up to 1024 characters
  • bcc - an array of objects from the Bcc: line, with the following properties: personal, adl, mailbox, and host
  • reply_toaddress - full Reply-To: line, up to 1024 characters
  • reply_to - an array of objects from the Reply-To: line, with the following properties: personal, adl, mailbox, and host
  • senderaddress - full sender: line, up to 1024 characters
  • sender - an array of objects from the Sender: line, with the following properties: personal, adl, mailbox, and host
  • return_pathaddress - full Return-Path: line, up to 1024 characters
  • return_path - an array of objects from the Return-Path: line, with the following properties: personal, adl, mailbox, and host
  • remail -
  • date - The message date as found in its headers
  • Date - Same as date
  • subject - The message subject
  • Subject - Same a subject
  • in_reply_to -
  • message_id -
  • newsgroups -
  • followup_to -
  • references -
  • Recent - R if recent and seen, N if recent and not seen, ' ' if not recent.
  • Unseen - U if not seen AND not recent, ' ' if seen OR not seen and recent
  • Flagged - F if flagged, ' ' if not flagged
  • Answered - A if answered, ' ' if unanswered
  • Deleted - D if deleted, ' ' if not deleted
  • Draft - X if draft, ' ' if not draft
  • Msgno - The message number
  • MailDate -
  • Size - The message size
  • udate - mail message date in Unix time
  • fetchfrom - from line formatted to fit fromlength characters
  • fetchsubject - subject line formatted to fit subjectlength characters

See Also

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message

imap_header
imap_headers
IMAP Functions


Returns headers for all messages in a mailbox

imap_headerinfo
imap_last_error
IMAP Functions
PHP Manual

imap_headers

(PHP 4, PHP 5)

imap_headers — Returns headers for all messages in a mailbox

Description

array imap_headers ( resource $imap_stream )

Returns headers for all messages in a mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns an array of string formatted with header info. One element per mail message.

imap_headerinfo
imap_last_error
IMAP Functions


Gets the last IMAP error that occurred during this page request

imap_headers
imap_list
IMAP Functions
PHP Manual

imap_last_error

(PHP 4, PHP 5)

imap_last_error — Gets the last IMAP error that occurred during this page request

Description

string imap_last_error ( void )

Gets the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.

Return Values

Returns the full text of the last IMAP error message that occurred on the current page. Returns FALSE if no error messages are available.

See Also

  • imap_errors() - Returns all of the IMAP errors that have occured

imap_headers
imap_list
IMAP Functions


Read the list of mailboxes

imap_last_error
imap_listmailbox
IMAP Functions
PHP Manual

imap_list

(PHP 4, PHP 5)

imap_list — Read the list of mailboxes

Description

array imap_list ( resource $imap_stream , string $ref , string $pattern )

Read the list of mailboxes.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref should normally be just the server specification as described in imap_open().

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern : '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Return Values

Returns an array containing the names of the mailboxes.

Examples

Example #1 imap_list() example

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$list = imap_list($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
    foreach ($list as $val) {
        echo imap_utf7_decode($val) . "\n";
    }
} else {
    echo "imap_list failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

See Also

  • imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one
  • imap_lsub() - List all the subscribed mailboxes

imap_last_error
imap_listmailbox
IMAP Functions


Alias of imap_list

imap_list
imap_listscan
IMAP Functions
PHP Manual

imap_listmailbox

(PHP 4, PHP 5)

imap_listmailbox — Alias of imap_list()

Description

This function is an alias of: imap_list().

imap_list
imap_listscan
IMAP Functions


Returns the list of mailboxes that matches the given text

imap_listmailbox
imap_listsubscribed
IMAP Functions
PHP Manual

imap_listscan

(PHP 4, PHP 5)

imap_listscan — Returns the list of mailboxes that matches the given text

Description

array imap_listscan ( resource $imap_stream , string $ref , string $pattern , string $content )

Returns an array containing the names of the mailboxes that have content in the text of the mailbox.

This function is similar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern : '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

content

The searched string

Return Values

Returns an array containing the names of the mailboxes that have content in the text of the mailbox.

See Also

  • imap_listmailbox() - Alias of imap_list
  • imap_search() - This function returns an array of messages matching the given search criteria

imap_listmailbox
imap_listsubscribed
IMAP Functions


Alias of imap_lsub

imap_listscan
imap_lsub
IMAP Functions
PHP Manual

imap_listsubscribed

(PHP 4, PHP 5)

imap_listsubscribed — Alias of imap_lsub()

Description

This function is an alias of: imap_lsub().

imap_listscan
imap_lsub
IMAP Functions


List all the subscribed mailboxes

imap_listsubscribed
imap_mail_compose
IMAP Functions
PHP Manual

imap_lsub

(PHP 4, PHP 5)

imap_lsub — List all the subscribed mailboxes

Description

array imap_lsub ( resource $imap_stream , string $ref , string $pattern )

Gets an array of all the mailboxes that you have subscribed.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern : '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Return Values

Returns an array of all the subscribed mailboxes.

See Also

  • imap_list() - Read the list of mailboxes
  • imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one

imap_listsubscribed
imap_mail_compose
IMAP Functions


Send an email message

imap_mail_move
imap_mailboxmsginfo
IMAP Functions
PHP Manual

imap_mail

(PHP 4, PHP 5)

imap_mail — Send an email message

Description

bool imap_mail ( string $to , string $subject , string $message [, string $additional_headers = NULL [, string $cc = NULL [, string $bcc = NULL [, string $rpath = NULL ]]]] )

This function allows sending of emails with correct handling of Cc and Bcc receivers.

The parameters to , cc and bcc are all strings and are all parsed as » RFC822 address lists.

Parameters

to

The receiver

subject

The mail subject

message

The mail body

additional_headers

As string with additional headers to be set on the mail

cc

bcc

The receivers specified in bcc will get the mail, but are excluded from the headers.

rpath

Use this parameter to specify return path upon mail delivery failure. This is useful when using PHP as a mail client for multiple users.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mail() - Send mail

imap_mail_move
imap_mailboxmsginfo
IMAP Functions


Create a MIME message based on given envelope and body sections

imap_lsub
imap_mail_copy
IMAP Functions
PHP Manual

imap_mail_compose

(PHP 4, PHP 5)

imap_mail_compose — Create a MIME message based on given envelope and body sections

Description

string imap_mail_compose ( array $envelope , array $body )

Create a MIME message based on the given envelope and body sections.

Parameters

envelope

An associative array of headers fields

body

An indexed array of bodies

A body is an associative array which can consist of the following keys: "type", "encoding", "subtype", "description" and "contents.data"

Return Values

Returns the MIME message.

Examples

Example #1 imap_mail_compose() example

<?php

$envelope["from"]= "joe@example.com";
$envelope["to"]  = "foo@example.com";
$envelope["cc"]  = "bar@example.com";

$part1["type"] = TYPEMULTIPART;
$part1["subtype"] = "mixed";

$filename = "/tmp/imap.c.gz";
$fp = fopen($filename, "r");
$contents = fread($fp, filesize($filename));
fclose($fp);

$part2["type"] = TYPEAPPLICATION;
$part2["encoding"] = ENCBINARY;
$part2["subtype"] = "octet-stream";
$part2["description"] = basename($filename);
$part2["contents.data"] = $contents;

$part3["type"] = TYPETEXT;
$part3["subtype"] = "plain";
$part3["description"] = "description3";
$part3["contents.data"] = "contents.data3\n\n\n\t";

$body[1] = $part1;
$body[2] = $part2;
$body[3] = $part3;

echo nl2br(imap_mail_compose($envelope, $body));

?>

imap_lsub
imap_mail_copy
IMAP Functions


Copy specified messages to a mailbox

imap_mail_compose
imap_mail_move
IMAP Functions
PHP Manual

imap_mail_copy

(PHP 4, PHP 5)

imap_mail_copy — Copy specified messages to a mailbox

Description

bool imap_mail_copy ( resource $imap_stream , string $msglist , string $mailbox [, int $options = 0 ] )

Copies mail messages specified by msglist to specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msglist

msglist is a range not just message numbers (as described in » RFC2060).

mailbox

The mailbox name, see imap_open() for more information

options

options is a bitmask of one or more of

  • CP_UID - the sequence numbers contain UIDS
  • CP_MOVE - Delete the messages from the current mailbox after copying

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_mail_move() - Move specified messages to a mailbox

imap_mail_compose
imap_mail_move
IMAP Functions


Move specified messages to a mailbox

imap_mail_copy
imap_mail
IMAP Functions
PHP Manual

imap_mail_move

(PHP 4, PHP 5)

imap_mail_move — Move specified messages to a mailbox

Description

bool imap_mail_move ( resource $imap_stream , string $msglist , string $mailbox [, int $options = 0 ] )

Moves mail messages specified by msglist to the specified mailbox .

Parameters

imap_stream

An IMAP stream returned by imap_open().

msglist

msglist is a range not just message numbers (as described in » RFC2060).

mailbox

The mailbox name, see imap_open() for more information

options

options is a bitmask and may contain the single option:

  • CP_UID - the sequence numbers contain UIDS

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: imap_mail_move() will flag the original mail with a delete flag, to successfully delete it a call to to the imap_expunge() must be made.

See Also

  • imap_mail_copy() - Copy specified messages to a mailbox

imap_mail_copy
imap_mail
IMAP Functions


Get information about the current mailbox

imap_mail
imap_mime_header_decode
IMAP Functions
PHP Manual

imap_mailboxmsginfo

(PHP 4, PHP 5)

imap_mailboxmsginfo — Get information about the current mailbox

Description

object imap_mailboxmsginfo ( resource $imap_stream )

Checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns the information in an object with following properties:

Mailbox properties
Date | date of last change (current datetime)
Driver | driver
Mailbox | name of the mailbox
Nmsgs | number of messages
Recent | number of recent messages
Unread | number of unread messages
Deleted | number of deleted messages
Size | mailbox size

Returns FALSE on failure.

Examples

Example #1 imap_mailboxmsginfo() example

<?php

$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
      or die("can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);

if ($check) {
    echo "Date: "     . $check->Date    . "<br />\n" ;
    echo "Driver: "   . $check->Driver  . "<br />\n" ;
    echo "Mailbox: "  . $check->Mailbox . "<br />\n" ;
    echo "Messages: " . $check->Nmsgs   . "<br />\n" ;
    echo "Recent: "   . $check->Recent  . "<br />\n" ;
    echo "Unread: "   . $check->Unread  . "<br />\n" ;
    echo "Deleted: "  . $check->Deleted . "<br />\n" ;
    echo "Size: "     . $check->Size    . "<br />\n" ;
} else {
    echo "imap_check() failed: " . imap_last_error() . "<br />\n";
}

imap_close($mbox);

?>

imap_mail
imap_mime_header_decode
IMAP Functions


Decode MIME header elements

imap_mailboxmsginfo
imap_msgno
IMAP Functions
PHP Manual

imap_mime_header_decode

(PHP 4, PHP 5)

imap_mime_header_decode — Decode MIME header elements

Description

array imap_mime_header_decode ( string $text )

Decodes MIME message header extensions that are non ASCII text (see » RFC2047).

Parameters

text

The MIME text

Return Values

The decoded elements are returned in an array of objects, where each object has two properties, charset and text.

If the element hasn't been encoded, and in other words is in plain US-ASCII, the charset property of that element is set to default.

Examples

Example #1 imap_mime_header_decode() example

<?php
$text = "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@example.com>";

$elements = imap_mime_header_decode($text);
for ($i=0; $i<count($elements); $i++) {
    echo "Charset: {$elements[$i]->charset}\n";
    echo "Text: {$elements[$i]->text}\n\n";
}
?>

The above example will output:

Charset: ISO-8859-1
Text: Keld Jørn Simonsen

Charset: default
Text:  <keld@example.com>

In the above example we would have two elements, whereas the first element had previously been encoded with ISO-8859-1, and the second element would be plain US-ASCII.

See Also

  • imap_utf8() - Converts MIME-encoded text to UTF-8

imap_mailboxmsginfo
imap_msgno
IMAP Functions


Gets the message sequence number for the given UID

imap_mime_header_decode
imap_num_msg
IMAP Functions
PHP Manual

imap_msgno

(PHP 4, PHP 5)

imap_msgno — Gets the message sequence number for the given UID

Description

int imap_msgno ( resource $imap_stream , int $uid )

Returns the message sequence number for the given uid .

This function is the inverse of imap_uid().

Parameters

imap_stream

An IMAP stream returned by imap_open().

uid

The message UID

Return Values

Returns the message sequence number for the given uid .

See Also

  • imap_uid() - This function returns the UID for the given message sequence number

imap_mime_header_decode
imap_num_msg
IMAP Functions


Gets the number of messages in the current mailbox

imap_msgno
imap_num_recent
IMAP Functions
PHP Manual

imap_num_msg

(PHP 4, PHP 5)

imap_num_msg — Gets the number of messages in the current mailbox

Description

int imap_num_msg ( resource $imap_stream )

Gets the number of messages in the current mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Return the number of messages in the current mailbox, as an integer.

See Also

  • imap_num_recent() - Gets the number of recent messages in current mailbox
  • imap_status() - Returns status information on a mailbox

imap_msgno
imap_num_recent
IMAP Functions


Gets the number of recent messages in current mailbox

imap_num_msg
imap_open
IMAP Functions
PHP Manual

imap_num_recent

(PHP 4, PHP 5)

imap_num_recent — Gets the number of recent messages in current mailbox

Description

int imap_num_recent ( resource $imap_stream )

Gets the number of recent messages in the current mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns the number of recent messages in the current mailbox, as an integer.

See Also

  • imap_num_msg() - Gets the number of messages in the current mailbox
  • imap_status() - Returns status information on a mailbox

imap_num_msg
imap_open
IMAP Functions


Open an IMAP stream to a mailbox

imap_num_recent
imap_ping
IMAP Functions
PHP Manual

imap_open

(PHP 4, PHP 5)

imap_open — Open an IMAP stream to a mailbox

Description

resource imap_open ( string $mailbox , string $username , string $password [, int $options = NIL [, int $n_retries = 0 ]] )

Opens an IMAP stream to a mailbox .

This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.

Parameters

mailbox

A mailbox name consists of a server and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded width imap_utf7_encode().

The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/').

The server part is mandatory in all mailbox parameters.

All names which start with { are remote names, and are in the form "{" remote_system_name [":" port] [flags] "}" [mailbox_name] where:

  • remote_system_name - Internet domain name or bracketed IP address of server.
  • port - optional TCP port number, default is the default port for that service
  • flags - optional flags, see following table.
  • mailbox_name - remote mailbox name, default is INBOX

Optional flags for names
Flag | Description
/service=service | mailbox access service, default is "imap"
/user=user | remote user name for login on the server
/authuser=user | remote authentication user; if specified this is the user name whose password is used (e.g. administrator)
/anonymous | remote access as anonymous user
/debug | record protocol telemetry in application's debug log
/secure | do not transmit a plaintext password over the network
/imap, /imap2, /imap2bis, /imap4, /imap4rev1 | equivalent to /service=imap
/pop3 | equivalent to /service=pop3
/nntp | equivalent to /service=nntp
/norsh | do not use rsh or ssh to establish a preauthenticated IMAP session
/ssl | use the Secure Socket Layer to encrypt the session
/validate-cert | validate certificates from TLS/SSL server (this is the default behavior)
/novalidate-cert | do not validate certificates from TLS/SSL server, needed if server uses self-signed certificates
/tls | force use of start-TLS to encrypt the session, and reject connection to servers that do not support it
/notls | do not do start-TLS to encrypt the session, even with servers that support it
/readonly | request read-only mailbox open (IMAP only; ignored on NNTP, and an error with SMTP and POP3)

username

The user name

password

The password associated with the username

options

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only
  • OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
  • OP_DEBUG - Debug protocol negotiations
  • OP_SHORTCACHE - Short (elt-only) caching
  • OP_SILENT - Don't pass up events (internal use)
  • OP_PROTOTYPE - Return driver prototype
  • OP_SECURE - Don't do non-secure authentication

n_retries

Number of maximum connect attempts

Return Values

Returns an IMAP stream on success or FALSE on error.

Changelog

Version | Description
5.2.0 | n_retries added

Examples

Example #1 Different use of imap_open()

<?php
// To connect to an IMAP server running on port 143 on the local machine,
// do the following:
$mbox = imap_open("{localhost:143}INBOX", "user_id", "password");

// To connect to a POP3 server on port 110 on the local server, use:
$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

// To connect to an SSL IMAP or POP3 server, add /ssl after the protocol
// specification:
$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");

// To connect to an SSL IMAP or POP3 server with a self-signed certificate,
// add /ssl/novalidate-cert after the protocol specification:
$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");

// To connect to an NNTP server on port 119 on the local server, use:
$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");
// To connect to a remote server replace "localhost" with the name or the
// IP address of the server you want to connect to.
?>

Example #2 imap_open() example

<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password");

echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{imap.example.org:143}", "*");

if ($folders == false) {
    echo "Call failed<br />\n";
} else {
    foreach ($folders as $val) {
        echo $val . "<br />\n";
    }
}

echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);

if ($headers == false) {
    echo "Call failed<br />\n";
} else {
    foreach ($headers as $val) {
        echo $val . "<br />\n";
    }
}

imap_close($mbox);
?>

See Also

  • imap_close() - Close an IMAP stream

imap_num_recent
imap_ping
IMAP Functions


Check if the IMAP stream is still active

imap_open
imap_qprint
IMAP Functions
PHP Manual

imap_ping

(PHP 4, PHP 5)

imap_ping — Check if the IMAP stream is still active

Description

bool imap_ping ( resource $imap_stream )

imap_ping() pings the stream to see if it's still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns TRUE if the stream is still alive, FALSE otherwise.

Examples

Example #1 imap_ping() Example

<?php

$imap = imap_open("{imap.example.org}", "mailadmin", "password");

// after some sleeping
if (!imap_ping($imap)) {
    // do some stuff to reconnect
}

?>

imap_open
imap_qprint
IMAP Functions


Convert a quoted-printable string to an 8 bit string

imap_ping
imap_renamemailbox
IMAP Functions
PHP Manual

imap_qprint

(PHP 4, PHP 5)

imap_qprint — Convert a quoted-printable string to an 8 bit string

Description

string imap_qprint ( string $string )

Convert a quoted-printable string to an 8 bit string according to » RFC2045, section 6.7.

Parameters

string

A quoted-printable string

Return Values

Returns an 8 bits string.

See Also

  • imap_8bit() - Convert an 8bit string to a quoted-printable string

imap_ping
imap_renamemailbox
IMAP Functions


Rename an old mailbox to new mailbox

imap_qprint
imap_reopen
IMAP Functions
PHP Manual

imap_renamemailbox

(PHP 4, PHP 5)

imap_renamemailbox — Rename an old mailbox to new mailbox

Description

bool imap_renamemailbox ( resource $imap_stream , string $old_mbox , string $new_mbox )

This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).

Parameters

imap_stream

An IMAP stream returned by imap_open().

old_mbox

The old mailbox name, see imap_open() for more information

new_mbox

The new mailbox name, see imap_open() for more information

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_createmailbox() - Create a new mailbox
  • imap_deletemailbox() - Delete a mailbox

imap_qprint
imap_reopen
IMAP Functions


Reopen IMAP stream to new mailbox

imap_renamemailbox
imap_rfc822_parse_adrlist
IMAP Functions
PHP Manual

imap_reopen

(PHP 4, PHP 5)

imap_reopen — Reopen IMAP stream to new mailbox

Description

bool imap_reopen ( resource $imap_stream , string $mailbox [, int $options = 0 [, int $n_retries = 0 ]] )

Reopens the specified stream to a new mailbox on an IMAP or NNTP server.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

options

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only
  • OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
  • OP_EXPUNGE - Silently expunge recycle stream
  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())

n_retries

Number of maximum connect attempts

Return Values

Returns TRUE if the stream is reopened, FALSE otherwise.

Changelog

Version | Description
5.2.0 | n_retries added

Examples

Example #1 imap_reopen() example

<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password") or die(implode(", ", imap_errors()));
// ...
imap_reopen($mbox, "{imap.example.org:143}INBOX.Sent") or die(implode(", ", imap_errors()));
// ..
?>

imap_renamemailbox
imap_rfc822_parse_adrlist
IMAP Functions


Parses an address string

imap_reopen
imap_rfc822_parse_headers
IMAP Functions
PHP Manual

imap_rfc822_parse_adrlist

(PHP 4, PHP 5)

imap_rfc822_parse_adrlist — Parses an address string

Description

array imap_rfc822_parse_adrlist ( string $address , string $default_host )

Parses the address string as defined in » RFC2822 and for each address.

Parameters

address

A string containing addresses

default_host

The default host name

Return Values

Returns an array of objects. The objects properties are:

  • mailbox - the mailbox name (username)
  • host - the host name
  • personal - the personal name
  • adl - at domain source route

Examples

Example #1 imap_rfc822_parse_adrlist() example

<?php

$address_string = "Joe Doe <doe@example.com>, postmaster@example.com, root";
$address_array  = imap_rfc822_parse_adrlist($address_string, "example.com");
if (!is_array($address_array) || count($address_array) < 1) {
    die("something is wrong\n");
}

foreach ($address_array as $id => $val) {
    echo "# $id\n";
    echo "  mailbox : " . $val->mailbox . "\n";
    echo "  host    : " . $val->host . "\n";
    echo "  personal: " . $val->personal . "\n";
    echo "  adl     : " . $val->adl . "\n";
}
?>

The above example will output:

# 0
  mailbox : doe
  host    : example.com
  personal: Joe Doe
  adl     :
# 1
  mailbox : postmaster
  host    : example.com
  personal:
  adl     :
# 2
  mailbox : root
  host    : example.com
  personal:
  adl     :

See Also

  • imap_rfc822_parse_headers() - Parse mail headers from a string

imap_reopen
imap_rfc822_parse_headers
IMAP Functions


Parse mail headers from a string

imap_rfc822_parse_adrlist
imap_rfc822_write_address
IMAP Functions
PHP Manual

imap_rfc822_parse_headers

(PHP 4, PHP 5)

imap_rfc822_parse_headers — Parse mail headers from a string

Description

object imap_rfc822_parse_headers ( string $headers [, string $defaulthost = "UNKNOWN" ] )

Gets an object of various header elements, similar to imap_header().

Parameters

headers

The parsed headers data

defaulthost

The default host name

Return Values

Returns an object similar to the one returned by imap_header(), except for the flags and other properties that come from the IMAP server.

See Also

  • imap_rfc822_parse_adrlist() - Parses an address string

imap_rfc822_parse_adrlist
imap_rfc822_write_address
IMAP Functions


Returns a properly formatted email address given the mailbox, host, and personal info

imap_rfc822_parse_headers
imap_savebody
IMAP Functions
PHP Manual

imap_rfc822_write_address

(PHP 4, PHP 5)

imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info

Description

string imap_rfc822_write_address ( string $mailbox , string $host , string $personal )

Returns a properly formatted email address as defined in » RFC2822 given the needed information.

Parameters

mailbox

The mailbox name, see imap_open() for more information

host

The email host part

personal

The name of the account owner

Return Values

Returns a string properly formatted email address as defined in » RFC2822.

Examples

Example #1 imap_rfc822_write_address() example

<?php
echo imap_rfc822_write_address("hartmut", "example.com", "Hartmut Holzgraefe");
?>

The above example will output:

Hartmut Holzgraefe <hartmut@example.com>

imap_rfc822_parse_headers
imap_savebody
IMAP Functions


Save a specific body section to a file

imap_rfc822_write_address
imap_scanmailbox
IMAP Functions
PHP Manual

imap_savebody

(PHP 5 >= 5.1.3)

imap_savebody — Save a specific body section to a file

Description

bool imap_savebody ( resource $imap_stream , mixed $file , int $msg_number [, string $part_number = "" [, int $options = 0 ]] )

Saves a part or the whole body of the specified message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

file

The path to the saved file as a string, or a valid file descriptor returned by fopen().

msg_number

The message number

part_number

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

options

A bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID
  • FT_PEEK - Do not set the \Seen flag if not already set
  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_fetchbody() - Fetch a particular section of the body of the message

imap_rfc822_write_address
imap_scanmailbox
IMAP Functions


Alias of imap_listscan

imap_savebody
imap_search
IMAP Functions
PHP Manual

imap_scanmailbox

(PHP 4, PHP 5)

imap_scanmailbox — Alias of imap_listscan()

Description

This function is an alias of: imap_listscan().

imap_savebody
imap_search
IMAP Functions


This function returns an array of messages matching the given search criteria

imap_scanmailbox
imap_set_quota
IMAP Functions
PHP Manual

imap_search

(PHP 4, PHP 5)

imap_search — This function returns an array of messages matching the given search criteria

Description

array imap_search ( resource $imap_stream , string $criteria [, int $options = SE_FREE [, string $charset = NIL ]] )

This function performs a search on the mailbox currently opened in the given IMAP stream.

For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be incomplete or inaccurate (see also » RFC2060, section 6.4.4).

Parameters

imap_stream

An IMAP stream returned by imap_open().

criteria

A string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. FROM "joey smith") must be quoted.

  • ALL - return all messages matching the rest of the criteria
  • ANSWERED - match messages with the \\ANSWERED flag set
  • BCC "string" - match messages with "string" in the Bcc: field
  • BEFORE "date" - match messages with Date: before "date"
  • BODY "string" - match messages with "string" in the body of the message
  • CC "string" - match messages with "string" in the Cc: field
  • DELETED - match deleted messages
  • FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
  • FROM "string" - match messages with "string" in the From: field
  • KEYWORD "string" - match messages with "string" as a keyword
  • NEW - match new messages
  • OLD - match old messages
  • ON "date" - match messages with Date: matching "date"
  • RECENT - match messages with the \\RECENT flag set
  • SEEN - match messages that have been read (the \\SEEN flag is set)
  • SINCE "date" - match messages with Date: after "date"
  • SUBJECT "string" - match messages with "string" in the Subject:
  • TEXT "string" - match messages with text "string"
  • TO "string" - match messages with "string" in the To:
  • UNANSWERED - match messages that have not been answered
  • UNDELETED - match messages that are not deleted
  • UNFLAGGED - match messages that are not flagged
  • UNKEYWORD "string" - match messages that do not have the keyword "string"
  • UNSEEN - match messages which have not been read yet

options

Valid values for options are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.

charset

Return Values

Returns an array of message numbers or UIDs.

Return FALSE if it does not understand the search criteria or no messages have been found.

Changelog

Version | Description
4.3.3 | The charset parameter was added

See Also

  • imap_listscan() - Returns the list of mailboxes that matches the given text

imap_scanmailbox
imap_set_quota
IMAP Functions


Sets a quota for a given mailbox

imap_search
imap_setacl
IMAP Functions
PHP Manual

imap_set_quota

(PHP 4 >= 4.0.5, PHP 5)

imap_set_quota — Sets a quota for a given mailbox

Description

bool imap_set_quota ( resource $imap_stream , string $quota_root , int $quota_limit )

Sets an upper limit quota on a per mailbox basis.

Parameters

imap_stream

An IMAP stream returned by imap_open().

quota_root

The mailbox to have a quota set. This should follow the IMAP standard format for a mailbox: user.name.

quota_limit

The maximum size (in KB) for the quota_root

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imap_set_quota() example

<?php
$mbox = imap_open("{imap.example.org:143}", "mailadmin", "password");

if (!imap_set_quota($mbox, "user.kalowsky", 3000)) {
    echo "Error in setting quota\n";
    return;
}

imap_close($mbox);
?>

Notes

This function is currently only available to users of the c-client2000 or greater library.

The given imap_stream must be opened as the mail administrator, other wise this function will fail.

See Also

  • imap_open() - Open an IMAP stream to a mailbox
  • imap_get_quota() - Retrieve the quota level settings, and usage statics per mailbox

imap_search
imap_setacl
IMAP Functions


Sets the ACL for a giving mailbox

imap_set_quota
imap_setflag_full
IMAP Functions
PHP Manual

imap_setacl

(PHP 4 >= 4.0.7, PHP 5)

imap_setacl — Sets the ACL for a giving mailbox

Description

bool imap_setacl ( resource $imap_stream , string $mailbox , string $id , string $rights )

Sets the ACL for a giving mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

id

The user to give the rights to.

rights

The rights to give to the user. Passing an empty string will delete acl.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

This function is currently only available to users of the c-client2000 or greater library.

See Also

  • imap_getacl() - Gets the ACL for a given mailbox

imap_set_quota
imap_setflag_full
IMAP Functions


Sets flags on messages

imap_setacl
imap_sort
IMAP Functions
PHP Manual

imap_setflag_full

(PHP 4, PHP 5)

imap_setflag_full — Sets flags on messages

Description

bool imap_setflag_full ( resource $imap_stream , string $sequence , string $flag [, int $options = NIL ] )

Causes a store to add the specified flag to the flags set for the messages in the specified sequence .

Parameters

imap_stream

An IMAP stream returned by imap_open().

sequence

A sequence of message numbers. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

flag

The flags which you can set are \Seen, \Answered, \Flagged, \Deleted, and \Draft as defined by » RFC2060.

options

A bit mask that may contain the single option:

  • ST_UID - The sequence argument contains UIDs instead of sequence numbers

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imap_setflag_full() example

<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password")
     or die("can't connect: " . imap_last_error());

$status = imap_setflag_full($mbox, "2,5", "\\Seen \\Flagged");

echo gettype($status) . "\n";
echo $status . "\n";

imap_close($mbox);
?>

See Also

  • imap_clearflag_full() - Clears flags on messages

imap_setacl
imap_sort
IMAP Functions


Gets and sort messages

imap_setflag_full
imap_status
IMAP Functions
PHP Manual

imap_sort

(PHP 4, PHP 5)

imap_sort — Gets and sort messages

Description

array imap_sort ( resource $imap_stream , int $criteria , int $reverse [, int $options = 0 [, string $search_criteria = NULL [, string $charset = NIL ]]] )

Gets and sorts message numbers by the given parameters.

Parameters

imap_stream

An IMAP stream returned by imap_open().

criteria

Criteria can be one (and only one) of the following:

  • SORTDATE - message Date
  • SORTARRIVAL - arrival date
  • SORTFROM - mailbox in first From address
  • SORTSUBJECT - message subject
  • SORTTO - mailbox in first To address
  • SORTCC - mailbox in first cc address
  • SORTSIZE - size of message in octets

reverse

Set this to 1 for reverse sorting

options

The options are a bitmask of one or more of the following:

  • SE_UID - Return UIDs instead of sequence numbers
  • SE_NOPREFETCH - Don't prefetch searched messages

search_criteria

charset

Return Values

Returns an array of message numbers sorted by the given parameters.

Changelog

Version | Description
4.3.3 | The charset parameter was added

imap_setflag_full
imap_status
IMAP Functions


Returns status information on a mailbox

imap_sort
imap_subscribe
IMAP Functions
PHP Manual

imap_status

(PHP 4, PHP 5)

imap_status — Returns status information on a mailbox

Description

object imap_status ( resource $imap_stream , string $mailbox , int $options )

Gets status information about the given mailbox .

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

options

Valid flags are:

  • SA_MESSAGES - set $status->messages to the number of messages in the mailbox
  • SA_RECENT - set $status->recent to the number of recent messages in the mailbox
  • SA_UNSEEN - set $status->unseen to the number of unseen (new) messages in the mailbox
  • SA_UIDNEXT - set $status->uidnext to the next uid to be used in the mailbox
  • SA_UIDVALIDITY - set $status->uidvalidity to a constant that changes when uids for the mailbox may no longer be valid
  • SA_ALL - set all of the above

Return Values

This function returns an object containing status information. The object has the following properties: messages, recent, unseen, uidnext, and uidvalidity.

flags is also set, which contains a bitmask which can be checked against any of the above constants.

Examples

Example #1 imap_status() example

<?php
$mbox = imap_open("{imap.example.com}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$status = imap_status($mbox, "{imap.example.org}INBOX", SA_ALL);
if ($status) {
  echo "Messages:   " . $status->messages    . "<br />\n";
  echo "Recent:     " . $status->recent      . "<br />\n";
  echo "Unseen:     " . $status->unseen      . "<br />\n";
  echo "UIDnext:    " . $status->uidnext     . "<br />\n";
  echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";
} else {
  echo "imap_status failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

imap_sort
imap_subscribe
IMAP Functions


Subscribe to a mailbox

imap_status
imap_thread
IMAP Functions
PHP Manual

imap_subscribe

(PHP 4, PHP 5)

imap_subscribe — Subscribe to a mailbox

Description

bool imap_subscribe ( resource $imap_stream , string $mailbox )

Subscribe to a new mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_unsubscribe() - Unsubscribe from a mailbox

imap_status
imap_thread
IMAP Functions


Returns a tree of threaded message

imap_subscribe
imap_timeout
IMAP Functions
PHP Manual

imap_thread

(PHP 4 >= 4.0.7, PHP 5)

imap_thread — Returns a tree of threaded message

Description

array imap_thread ( resource $imap_stream [, int $options = SE_FREE ] )

Gets a tree of a threaded message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

options

Return Values

imap_thread() returns an associative array containing a tree of messages threaded by REFERENCES, or FALSE on error.

Every message in the current mailbox will be represented by three entries in the resulting array:

  • $thread["XX.num"] - current message number

  • $thread["XX.next"]

  • $thread["XX.branch"]

Examples

Example #1 imap_thread() Example

<?php

// Here we're outputting the threads of a newsgroup, in HTML

$nntp = imap_open('{news.example.com:119/nntp}some.newsgroup', '', '');
$threads = imap_thread($nntp);

foreach ($threads as $key => $val) {
  $tree = explode('.', $key);
  if ($tree[1] == 'num') {
    $header = imap_headerinfo($nntp, $val);
    echo "<ul>\n\t<li>" . $header->fromaddress . "\n";
  } elseif ($tree[1] == 'branch') {
    echo "\t</li>\n</ul>\n";
  }
}

imap_close($nntp);

?>

imap_subscribe
imap_timeout
IMAP Functions


Set or fetch imap timeout

imap_thread
imap_uid
IMAP Functions
PHP Manual

imap_timeout

(PHP 4 >= 4.3.3, PHP 5)

imap_timeout — Set or fetch imap timeout

Description

mixed imap_timeout ( int $timeout_type [, int $timeout = -1 ] )

Sets or fetches the imap timeout.

Parameters

timeout_type

One of the following: IMAP_OPENTIMEOUT, IMAP_READTIMEOUT, IMAP_WRITETIMEOUT, or IMAP_CLOSETIMEOUT.

timeout

The timeout, in seconds.

Return Values

If the timeout parameter is set, this function returns TRUE on success and FALSE on failure.

If timeout is not provided or evaluates to -1, the current timeout value of timeout_type is returned as an integer.

Examples

Example #1 imap_timeout() example

<?php

echo "The current read timeout is " . imap_timeout(IMAP_READTIMEOUT) . "\n";

?>

imap_thread
imap_uid
IMAP Functions


This function returns the UID for the given message sequence number

imap_timeout
imap_undelete
IMAP Functions
PHP Manual

imap_uid

(PHP 4, PHP 5)

imap_uid — This function returns the UID for the given message sequence number

Description

int imap_uid ( resource $imap_stream , int $msg_number )

This function returns the UID for the given message sequence number. An UID is a unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes.

This function is the inverse of imap_msgno().

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number.

Return Values

The UID of the given message.

Notes

Note: This function is not supported by POP3 mailboxes.

See Also

  • imap_msgno() - Gets the message sequence number for the given UID

imap_timeout
imap_undelete
IMAP Functions


Unmark the message which is marked deleted

imap_uid
imap_unsubscribe
IMAP Functions
PHP Manual

imap_undelete

(PHP 4, PHP 5)

imap_undelete — Unmark the message which is marked deleted

Description

bool imap_undelete ( resource $imap_stream , int $msg_number [, int $flags = 0 ] )

Removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

flags

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_delete() - Mark a message for deletion from current mailbox
  • imap_mail_move() - Move specified messages to a mailbox

imap_uid
imap_unsubscribe
IMAP Functions


Unsubscribe from a mailbox

imap_undelete
imap_utf7_decode
IMAP Functions
PHP Manual

imap_unsubscribe

(PHP 4, PHP 5)

imap_unsubscribe — Unsubscribe from a mailbox

Description

bool imap_unsubscribe ( resource $imap_stream , string $mailbox )

Unsubscribe from the specified mailbox .

Parameters

imap_stream

An IMAP stream returned by imap_open().

mailbox

The mailbox name, see imap_open() for more information

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_subscribe() - Subscribe to a mailbox

imap_undelete
imap_utf7_decode
IMAP Functions


Decodes a modified UTF-7 encoded string

imap_unsubscribe
imap_utf7_encode
IMAP Functions
PHP Manual

imap_utf7_decode

(PHP 4, PHP 5)

imap_utf7_decode — Decodes a modified UTF-7 encoded string

Description

string imap_utf7_decode ( string $text )

Decodes modified UTF-7 text into ISO-8859-1 string.

This function is needed to decode mailbox names that contain certain characters which are not in range of printable ASCII characters.

Parameters

text

A modified UTF-7 encoding string, as defined in » RFC 2060, section 5.1.3 (original UTF-7 was defined in » RFC1642).

Return Values

Returns a string that is encoded in ISO-8859-1 and consists of the same sequence of characters in text , or FALSE if text contains invalid modified UTF-7 sequence or text contains a character that is not part of ISO-8859-1 character set.

See Also

  • imap_utf7_encode() - Converts ISO-8859-1 string to modified UTF-7 text

imap_unsubscribe
imap_utf7_encode
IMAP Functions


Converts ISO-8859-1 string to modified UTF-7 text

imap_utf7_decode
imap_utf8
IMAP Functions
PHP Manual

imap_utf7_encode

(PHP 4, PHP 5)

imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text

Description

string imap_utf7_encode ( string $data )

Converts data to modified UTF-7 text.

This is needed to encode mailbox names that contain certain characters which are not in range of printable ASCII characters.

Parameters

data

An ISO-8859-1 string.

Return Values

Returns data encoded with the modified UTF-7 encoding as defined in » RFC 2060, section 5.1.3 (original UTF-7 was defined in » RFC1642).

See Also

  • imap_utf7_decode() - Decodes a modified UTF-7 encoded string

imap_utf7_decode
imap_utf8
IMAP Functions


Converts MIME-encoded text to UTF-8

imap_utf7_encode
Mail
IMAP Functions
PHP Manual

imap_utf8

(PHP 4, PHP 5)

imap_utf8 — Converts MIME-encoded text to UTF-8

Description

string imap_utf8 ( string $mime_encoded_text )

Converts the given mime_encoded_text to UTF-8.

Parameters

mime_encoded_text

A MIME encoded string. MIME encoding method and the UTF-8 specification are described in » RFC2047 and » RFC2044 respectively.

Return Values

Returns an UTF-8 encoded string.

See Also

  • imap_mime_header_decode() - Decode MIME header elements

imap_utf7_encode
Mail
IMAP Functions


include

require
require_once
Control Structures
PHP Manual

include()

The include() statement includes and evaluates the specified file.

The documentation below also applies to require().

Files are included based on the file path given or, if none is given, the include_path specified. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.

If a path is defined (full or relative), the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

For more information on how PHP handles including files and the include path, see the documentation for include_path.

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Example #1 Basic include() example

vars.php
<?php

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

?>

test.php
<?php

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

include 'vars.php';

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

?>

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

Example #2 Including within functions

<?php

function foo()
{
    global $color;

    include 'vars.php';

    echo "A $color $fruit";
}

/* vars.php is in the scope of foo() so     *
* $fruit is NOT available outside of this  *
* scope.  $color is because we declared it *
* as global.                               */

foo();                    // A green apple
echo "A $color $fruit";   // A green

?>

When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see List of Supported Protocols/Wrappers for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.

Warning

Windows versions of PHP prior to PHP 4.3.0 do not support access of remote files via this function, even if allow_url_fopen is enabled.

Example #3 include() through HTTP

<?php

/* This example assumes that www.example.com is configured to parse .php
* files and not .txt files. Also, 'Works' here means that the variables
* $foo and $bar are available within the included file. */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

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

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

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

?>

Warning

Security warning

Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code.

See also Remote files, fopen() and file() for related information.

Handling Returns: It is possible to execute a return() statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.

Because include() is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.

Example #4 Comparing return value of include

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
    echo 'OK';
}

// works
if ((include 'vars.php') == 'OK') {
    echo 'OK';
}
?>

Example #5 include() and the return() statement

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?>

$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return() within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued.

If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return(). It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.

Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include(). For example:

Example #6 Using output buffering to include a PHP file into a string

<?php
$string = get_include_contents('somefile.php');

function get_include_contents($filename) {
    if (is_file($filename)) {
        ob_start();
        include $filename;
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }
    return false;
}

?>

In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini.

Note: Because this is a language construct and not a function, it cannot be called using variable functions

See also require(), require_once(),
include_once(), get_included_files(),
readfile(), virtual(), and
include_path.

require
require_once
Control Structures


include_once

require_once
goto
Control Structures
PHP Manual

include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

include_once() may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

See the include() documentation for information about how this function works.

Note: With PHP 4, _once functionality differs with case-insensitive operating systems (like Windows) so for example:

Example #1 include_once() with a case insensitive OS in PHP 4

<?php
include_once "a.php"; // this will include a.php
include_once "A.php"; // this will include a.php again! (PHP 4 only)
?>

This behaviour changed in PHP 5, so for example with Windows the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is included just once.

require_once
goto
Control Structures


Get the inclued data

inclued Functions
PHP Options/Info
inclued Functions
PHP Manual

inclued_get_data

(PECL inclued >= 0.1.0)

inclued_get_data — Get the inclued data

Description

array inclued_get_data ( void )

Get the inclued data.

Parameters

This function has no parameters.

Return Values

The inclued data.

Examples

Example #1 inclued_get_data() example

See the inclued examples section for ways to create a graphs with this data.

<?php
include 'x.php';

$clue = inclued_get_data();

print_r($clue);
?>

The above example will output something similar to:

Array
(
  [includes] => Array
    (
      [0] => Array
        (
          [operation] => include
          [op_type] => 2
          [filename] => x.php
          [opened_path] => /tmp/x.php
          [fromfile] => /tmp/z.php
          [fromline] => 2
        )
    )
)

See Also

  • inclued examples
  • debug_backtrace() - Generates a backtrace
  • include() - include

inclued Functions
PHP Options/Info
inclued Functions


Switch autocommit on or off

ingres_autocommit_state
ingres_charset
Ingres Functions
PHP Manual

ingres_autocommit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_autocommit — Switch autocommit on or off

Description

bool ingres_autocommit ( resource $link )

ingres_autocommit() is called before opening a transaction (before the first call to ingres_query() or just after a call to ingres_rollback() or ingres_commit()) to switch the autocommit mode of the server on or off (when the script begins the autocommit mode is off).

When autocommit mode is on, every query is automatically committed by the server, as if ingres_commit() was called after every call to ingres_query(). To see if autocommit is enabled use, ingres_autocommit_state().

By default Ingres will rollback any uncommitted transactions at the end of a request. Use this function or ingres_commit() to ensure your data is committed to the database.

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_autocommit_state() - Test if the connection is using autocommit
  • ingres_query() - Send an SQL query to Ingres
  • ingres_rollback() - Roll back a transaction
  • ingres_commit() - Commit a transaction

ingres_autocommit_state
ingres_charset
Ingres Functions


Test if the connection is using autocommit

Ingres Functions
ingres_autocommit
Ingres Functions
PHP Manual

ingres_autocommit_state

(PECL ingres >= 2.0.0)

ingres_autocommit_state — Test if the connection is using autocommit

Description

bool ingres_autocommit_state ( resource $link )

ingres_autocommit_state() is called to determine whether the current link has autocommit enabled or not.

Parameters

link

The connection link identifier

Return Values

Returns TRUE if autocommit is enabled or FALSE when autocommit is disabled

See Also

  • ingres_autocommit() - Switch autocommit on or off
  • ingres_query() - Send an SQL query to Ingres

Ingres Functions
ingres_autocommit
Ingres Functions


Returns the installation character set

ingres_autocommit
ingres_close
Ingres Functions
PHP Manual

ingres_charset

(PECL ingres >= 2.1.0)

ingres_charset — Returns the installation character set

Description

string ingres_charset ( resource $link )

ingres_charset() is called to determine the character set being used by the Ingres client, from II_CHARSETxx (where xx is the installation code).

Note: You can override the value returned by using the function putenv(). Changing the value of II_CHARSETxx in a running Ingres installation can cause data corruption.

Parameters

link

The connection link identifier

Return Values

Returns a string with the value for II_CHARSETxx or returns NULL if the value could not be determined.

Examples

Example #1 ingres_charset() - Get the installation character set

<?php
$link = ingres_connect($database, $user, $password);

echo ingres_charset($link) . "\n";

ingres_close($link);
?>

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_query() - Send an SQL query to Ingres

ingres_autocommit
ingres_close
Ingres Functions


Close an Ingres database connection

ingres_charset
ingres_commit
Ingres Functions
PHP Manual

ingres_close

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_close — Close an Ingres database connection

Description

bool ingres_close ( resource $link )

ingres_close() closes the connection to the Ingres server that is associated with the specified link.

ingres_close() is usually unnecessary, as it will not close persistent connections and all non-persistent connections are automatically closed at the end of the script.

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_pconnect() - Open a persistent connection to an Ingres database

ingres_charset
ingres_commit
Ingres Functions


Commit a transaction

ingres_close
ingres_connect
Ingres Functions
PHP Manual

ingres_commit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_commit — Commit a transaction

Description

bool ingres_commit ( resource $link )

ingres_commit() commits the currently open transaction, making all changes made to the database permanent.

This closes the transaction. A new transaction can be opened by sending a query with ingres_query().

You can also have the server commit automatically after every query by calling ingres_autocommit() before opening the transaction.

By default Ingres will roll back any uncommitted transactions at the end of a request. Use this function or ingres_autocommit() to ensure your that data is committed to the database.

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off

ingres_close
ingres_connect
Ingres Functions


Open a connection to an Ingres database

ingres_commit
ingres_cursor
Ingres Functions
PHP Manual

ingres_connect

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_connect — Open a connection to an Ingres database

Description

resource ingres_connect ([ string $database [, string $username [, string $password [, array $options ]]]] )

ingres_connect() opens a connection with the given Ingres database .

The connection is closed when the script ends or when ingres_close() is called on this link.

Parameters

If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database , ingres.default_user and ingres.default_password .

database

The database name. Must follow the syntax:

[vnode::]dbname[/svr_class]

username

The Ingres user name

password

The password associated with username

options

ingres_connect() options

Option name | Option type | Description | Example
date_century_boundary | integer | The threshold by which a 2-digit year is determined to be in the current century or in the next century. Equivalent to II_DATE_CENTURY_BOUNDARY. | 50
group | string | Specifies the group ID of the user, equivalent to the "-G" flag | payroll
role | string | The role ID of the application. If a role password is required, the parameter value should be specified as "role/password"
effective_user | string | The ingres user account being impersonated, equivalent to the "-u" flag | another_user
dbms_password | string | The internal database password for the user connecting to Ingres | s3cr3t
table_structure string

The default structure for new tables. Valid values for table_structure are:

  • INGRES_STRUCTURE_BTREE
  • INGRES_STRUCTURE_HASH
  • INGRES_STRUCTURE_HEAP
  • INGRES_STRUCTURE_ISAM
  • INGRES_STRUCTURE_CBTREE
  • INGRES_STRUCTURE_CISAM
  • INGRES_STRUCTURE_CHASH
  • INGRES_STRUCTURE_CHEAP

 INGRES_STRUCTURE_BTREE
index_structure string

The default structure for new secondary indexes. Valid values for index_structure are:

  • INGRES_STRUCTURE_CBTREE
  • INGRES_STRUCTURE_CISAM
  • INGRES_STRUCTURE_CHASH
  • INGRES_STRUCTURE_BTREE
  • INGRES_STRUCTURE_HASH
  • INGRES_STRUCTURE_ISAM

 INGRES_STRUCTURE_HASH
login_local | boolean | Determines how the connection user ID and password are used when a VNODE is included in the target database string. If set to TRUE, the user ID and password are used to locally access the VNODE, and the VNODE login information is used to establish the DBMS connection. If set to FALSE, the process user ID is used to access the VNODE, and the connection user ID and password are used in place of the VNODE login information to establish the DBMS connection. This parameter is ignored if no VNODE is included in the target database string. The default is FALSE. | TRUE
timezone | string | Controls the timezone of the session. If not set it will default to the value defined by II_TIMEZONE_NAME. If II_TIMEZONE_NAME is not defined, NA-PACIFIC (GMT-8 with Daylight Savings) is used.
date_format integer

Sets the allowable input and output format for Ingres dates. Defaults to the value defined by II_DATE_FORMAT. If II_DATE_FORMAT is not set the default date format is US, e.g. mm/dd/yy. Valid values for date_format are:

  • INGRES_DATE_DMY
  • INGRES_DATE_FINISH
  • INGRES_DATE_GERMAN
  • INGRES_DATE_ISO
  • INGRES_DATE_ISO4
  • INGRES_DATE_MDY
  • INGRES_DATE_MULTINATIONAL
  • INGRES_DATE_MULTINATIONAL4
  • INGRES_DATE_YMD
  • INGRES_DATE_US

 INGRES_DATE_MULTINATIONAL4
decimal_separator string The character identifier for decimal data ","
money_lort integer

Leading or trailing currency sign. Valid values for money_lort are:

  • INGRES_MONEY_LEADING
  • INGRES_MONEY_TRAILING

 INGRES_MONEY_TRAILING
money_sign string The currency symbol to be used with the MONEY datatype €
money_precision | integer | The precision of the MONEY datatype | 3
float4_precision | integer | Precision of the FLOAT4 datatype | 10
float8_precision | integer | Precision of the FLOAT8 data | 10
blob_segment_length | integer | The amount of data in bytes to fetch at a time when retrieving BLOB or CLOB data, defaults to 4096 bytes when not explicitly set | 8192

Return Values

Returns a Ingres link resource on success or FALSE on failure

Examples

Example #1 Open a connection to an Ingres database

<?php
$link = ingres_connect("mydb", "user", "pass")
    or die("Could not connect");
echo "Connected successfully";
ingres_close($link);
?>

See Also

  • ingres_pconnect() - Open a persistent connection to an Ingres database
  • ingres_close() - Close an Ingres database connection

ingres_commit
ingres_cursor
Ingres Functions


Get a cursor name for a given result resource

ingres_connect
ingres_errno
Ingres Functions
PHP Manual

ingres_cursor

(PECL ingres >= 1.1.0)

ingres_cursor — Get a cursor name for a given result resource

Description

string ingres_cursor ( resource $result )

Returns a string with the active cursor name. If no cursor is active then NULL is returned.

Parameters

result

The query result identifier

Return Values

Returns a string containing the active cursor name. If no cursor is active then NULL is returned.

Examples

Example #1 Get cursor name for a query resource

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_prepare($link, "select * from table");

$cursor_name = ingres_cursor($result);

echo $cursor_name;

?>

See Also

  • ingres_prepare() - Prepare a query for later execution
  • ingres_execute() - Execute a prepared query

ingres_connect
ingres_errno
Ingres Functions


Get the last Ingres error number generated

ingres_cursor
ingres_error
Ingres Functions
PHP Manual

ingres_errno

(PECL ingres >= 1.1.0)

ingres_errno — Get the last Ingres error number generated

Description

int ingres_errno ([ resource $link ] )

Returns an integer containing the last error number. If no error was reported 0 is returned.

If a link resource is passed to ingres_errno() it returns the last error recorded for the link. If no link is passed, then ingres_errno() returns the last error reported using the default link.

The function, ingres_errno(), should always be called after executing a database query. Calling another function before ingres_errno() is called will reset or change any error code from the last Ingres function call.

Parameters

link

The connection link identifier

Return Values

Returns an integer containing the last error number. If no error was reported, 0 is returned.

Examples

Example #1 Get the last Ingres error number generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_code = ingres_errno($link);

if ( $error_code != 0 ) {
   echo "An error occured - " . $error_code;
}
?>

See Also

  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated
  • ingres_next_error() - Get the next Ingres error

ingres_cursor
ingres_error
Ingres Functions


Get a meaningful error message for the last error generated

ingres_errno
ingres_errsqlstate
Ingres Functions
PHP Manual

ingres_error

(PECL ingres >= 1.1.0)

ingres_error — Get a meaningful error message for the last error generated

Description

string ingres_error ([ resource $link ] )

Returns a string containing the last error, or NULL if no error has occurred.

If a link resource is passed to ingres_error(), it returns the last error recorded for the link. If no link is passed then ingres_error() returns the last error reported using the default link.

The function, ingres_error(), should always be called after executing any database query. Calling another function before ingres_error() is called will reset or change any error message from the last Ingres function call.

Parameters

link

The connection link identifier

Return Values

Returns a string containing the last error, or NULL if no error has occurred.

Examples

Example #1 Get a message for the last error generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_text = ingres_error();

if (!is_null($error_text)) {
   echo "An error occured - " . $error_text;
}
?>

See Also

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated
  • ingres_next_error() - Get the next Ingres error

ingres_errno
ingres_errsqlstate
Ingres Functions


Get the last SQLSTATE error code generated

ingres_error
ingres_escape_string
Ingres Functions
PHP Manual

ingres_errsqlstate

(PECL ingres >= 1.1.0)

ingres_errsqlstate — Get the last SQLSTATE error code generated

Description

string ingres_errsqlstate ([ resource $link ] )

Returns a string containing the last SQLSTATE, or NULL if no error has occurred.

If a link resource is passed to ingres_errsqlstate(), it returns the last error recorded for the link. If no link is passed, then ingres_errsqlstate() returns the last error reported using the default link.

The function, ingres_errsqlstate(), should always be called after executing any database query. Calling another function before ingres_errsqlstate() is called will reset or change any error message from the last Ingres function call.

Parameters

link

The connection link identifier

Return Values

Returns a string containing the last SQLSTATE, or NULL if no error has occurred.

Examples

Example #1 Get the last SQLSTATE error code generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_sqlstate = ingres_errsqlstate($link);

if (!is_null($error_sqlstate)) {
   echo "An error occured - " . $error_sqlstate;
}
?>

See Also

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_next_error() - Get the next Ingres error

ingres_error
ingres_escape_string
Ingres Functions


Escape special characters for use in a query

ingres_errsqlstate
ingres_execute
Ingres Functions
PHP Manual

ingres_escape_string

(PECL ingres >= 2.1.0)

ingres_escape_string — Escape special characters for use in a query

Description

string ingres_escape_string ( resource $link , string $source_string )

ingres_escape_string() is used to escape certain characters within a string before it is sent to the database server.

Parameters

link

The connection link identifier

source_string

The source string to be parsed

Return Values

Returns a string containing the escaped data.

Examples

Example #1 Escape special characters for use in a query

<?php
$link = ingres_connect($database, $user, $password);

$last_name = "O'Connor";

$sql = sprintf("select * from user_profile where up_last = '%s'", ingres_escape_string( $link, $last_name));

$result = ingres_query($link, $sql);

while ($user = ingres_fetch_object($result))
{
  echo $user->up_first . '<BR/>';
}

ingres_commit($link);

ingres_close($link);

?>

See Also

  • ingres_query() - Send an SQL query to Ingres

ingres_errsqlstate
ingres_execute
Ingres Functions


Execute a prepared query

ingres_escape_string
ingres_fetch_array
Ingres Functions
PHP Manual

ingres_execute

(PECL ingres >= 1.1.0)

ingres_execute — Execute a prepared query

Description

boolean ingres_execute ( resource $result [, array $params [, string $types ]] )

Execute a query prepared using ingres_prepare().

Note: Related Configurations
See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The result query identifier

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. See the types parameter in ingres_query() for the list of type codes.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

ingres_escape_string
ingres_fetch_array
Ingres Functions


Fetch a row of result into an array

ingres_execute
ingres_fetch_assoc
Ingres Functions
PHP Manual

ingres_fetch_array

( PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_fetch_array — Fetch a row of result into an array

Description

array ingres_fetch_array ( resource $result [, int $result_type ] )

This function is an extended version of ingres_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

If two or more columns of the result have the same field names, the last column will take precedence. To access the another column or columns of the same name, you must use the numeric index of the column or make an alias for the column. For example:

<?php

$result = ingres_query($link, "select ap_place as city, ap_ccode as country from airport where ap_iatacode = 'VLL'");
$result = ingres_fetch_array($result);
$foo = $result["city"];
$bar = $result["country"];

?>

With regard to speed, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

By default, arrays created by ingres_fetch_array() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Note: Related Configurations
See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The query result identifier

result_type

The result type. This result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH (default).

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row of result into an array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link,"select * from table");
while ($row = ingres_fetch_array($result)) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
    echo $row[1];          // using enumerated array
    echo $row[2];
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_execute
ingres_fetch_assoc
Ingres Functions


Fetch a row of result into an associative array

ingres_fetch_array
ingres_fetch_object
Ingres Functions
PHP Manual

ingres_fetch_assoc

(No version information available, might only be in SVN)

ingres_fetch_assoc — Fetch a row of result into an associative array

Description

array ingres_fetch_assoc ( resource $result )

This function is stores the data fetched from a query executed using ingres_query() in an associative array, using the field names as keys.

With regard to speed, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

By default, arrays created by ingres_fetch_assoc() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Note: Related Configurations
See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The query result identifier

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row into an associative array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link,"select * from table");
while ($row = ingres_fetch_assoc($result)) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_fetch_array
ingres_fetch_object
Ingres Functions


Fetch a row of result into an object

ingres_fetch_assoc
ingres_fetch_proc_return
Ingres Functions
PHP Manual

ingres_fetch_object

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_fetch_object — Fetch a row of result into an object

Description

object ingres_fetch_object ( resource $result [, int $result_type ] )

This function is similar to ingres_fetch_array(), with one difference - an object is returned instead of an array. Indirectly, this means that you can access the data only by the field names and not by their offsets (numbers are illegal property names).

With regard to speed, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Note: Related Configurations
See also the ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

link

The query result identifier

result_type

(Optional argument.) result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.

Return Values

Returns an object that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row into an object

<?php
$link = ingres_connect($database, $user, $password);
$result = ingres_query($link, "select * from table");
while ($row = ingres_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_fetch_assoc
ingres_fetch_proc_return
Ingres Functions


Get the return value from a procedure call

ingres_fetch_object
ingres_fetch_row
Ingres Functions
PHP Manual

ingres_fetch_proc_return

(PECL ingres >= 1.4.0)

ingres_fetch_proc_return — Get the return value from a procedure call

Description

int ingres_fetch_proc_return ( resource $result )

This function is used to retrieve the return value following the execution of an Ingres database procedure (stored procedure).

Note: If used with a row-producing procedure, this function should be called after all the rows from the procedure have been fetched using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row(). This function will eliminate any rows yet to be fetched should there be any left over.

Parameters

result

The result identifier for a query

Return Values

Returns an integer if there is a return value otherwise it will return NULL.

Examples

Example #1 Get the return value from a procedure call

<?php

$link = ingres_connect($database);

if ( ingres_errno() != 0 ) {
    $error_text = ingres_error();
    die($error_text);
}

$result = ingres_query($link, "execute procedure php_proc (value = 1000)");

if ( ingres_errno() != 0 ) {
    $error_text = ingres_error();
    die($error_text);
}

echo "return value - " . ingres_fetch_proc_return($result) . "\n";

ingres_close($link);

?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_fetch_object
ingres_fetch_row
Ingres Functions


Fetch a row of result into an enumerated array

ingres_fetch_proc_return
ingres_field_length
Ingres Functions
PHP Manual

ingres_fetch_row

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_fetch_row — Fetch a row of result into an enumerated array

Description

array ingres_fetch_row ( resource $result )

ingres_fetch_row() returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 1.

Subsequent calls to ingres_fetch_row() return the next row in the result set, or FALSE if there are no more rows.

By default, arrays created by ingres_fetch_row() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Note: Related Configurations
See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The query result identifier

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row of result into an enumerated array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

See Also

  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object

ingres_fetch_proc_return
ingres_field_length
Ingres Functions


Get the length of a field

ingres_fetch_row
ingres_field_name
Ingres Functions
PHP Manual

ingres_field_length

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_length — Get the length of a field

Description

int ingres_field_length ( resource $result , int $index )

ingres_field_length() returns the length of a field. This is the number of bytes the server uses to store the field. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Note: Related Configurations
See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the column number whose length will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the length of a field.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_fetch_row
ingres_field_name
Ingres Functions


Get the name of a field in a query result

ingres_field_length
ingres_field_nullable
Ingres Functions
PHP Manual

ingres_field_name

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_name — Get the name of a field in a query result

Description

string ingres_field_name ( resource $result , int $index )

ingres_field_name() returns the name of a field in a query result.

Note: Related Configurations
See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose name will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the name of a field in a query result or FALSE on failure

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_field_length
ingres_field_nullable
Ingres Functions


Test if a field is nullable

ingres_field_name
ingres_field_precision
Ingres Functions
PHP Manual

ingres_field_nullable

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_nullable — Test if a field is nullable

Description

bool ingres_field_nullable ( resource $result , int $index )

Test if a field is nullable.

Note: Related Configurations
See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose nullability will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it cannot

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_field_name
ingres_field_precision
Ingres Functions


Get the precision of a field

ingres_field_nullable
ingres_field_scale
Ingres Functions
PHP Manual

ingres_field_precision

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_precision — Get the precision of a field

Description

int ingres_field_precision ( resource $result , int $index )

ingres_field_precision() returns the precision of a field. This value is used only for decimal, float, and money SQL data types. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Note: Related Configurations
See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose precision will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the field precision as an integer

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_field_nullable
ingres_field_scale
Ingres Functions


Get the scale of a field

ingres_field_precision
ingres_field_type
Ingres Functions
PHP Manual

ingres_field_scale

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_scale — Get the scale of a field

Description

int ingres_field_scale ( resource $result , int $index )

ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Note: Related Configurations
See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose scale will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the scale of the field, as an integer

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_field_precision
ingres_field_type
Ingres Functions


Get the type of a field in a query result

ingres_field_scale
ingres_free_result
Ingres Functions
PHP Manual

ingres_field_type

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_type — Get the type of a field in a query result

Description

string ingres_field_type ( resource $result , int $index )

Get the type of a field in a query result.

Note: Related Configurations
See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose type will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

ingres_field_type() returns the type of a field in a query result or FALSE on failure. Examples of types returned are IIAPI_BYTE_TYPE, IIAPI_CHA_TYPE, IIAPI_DTE_TYPE, IIAPI_FLT_TYPE, IIAPI_INT_TYPE, IIAPI_VCH_TYPE. Some of these types can map to more than one SQL type depending on the length of the field (see ingres_field_length()). For example IIAPI_FLT_TYPE can be a float4 or a float8. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_field_scale
ingres_free_result
Ingres Functions


Free the resources associated with a result identifier

ingres_field_type
ingres_next_error
Ingres Functions
PHP Manual

ingres_free_result

(PECL ingres >= 2.0.0)

ingres_free_result — Free the resources associated with a result identifier

Description

bool ingres_free_result ( resource $result )

Parameters

result

The query result identifier

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Free a result resource

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
ingres_free_result($result);

ingres_close($link)

?>

See Also

  • ingres_query() - Send an SQL query to Ingres

ingres_field_type
ingres_next_error
Ingres Functions


Get the next Ingres error

ingres_free_result
ingres_num_fields
Ingres Functions
PHP Manual

ingres_next_error

(PECL ingres >= 2.0.0)

ingres_next_error — Get the next Ingres error

Description

bool ingres_next_error ([ resource $link ] )

Get the next Ingres error for the last executed query. Each call to ingres_next_error() can be followed by a call to ingres_errno(), ingres_error() or ingres_errsqlstate() to get the respective error number, error text, or SQL STATE. While ingres_next_error() returns TRUE, there are more errors to fetch.

Parameters

link

The connection link identifier

Return Values

ingres_next_error() returns TRUE if there is another error to retrieve or FALSE when there are no more errors

See Also

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated

ingres_free_result
ingres_num_fields
Ingres Functions


Get the number of fields returned by the last query

ingres_next_error
ingres_num_rows
Ingres Functions
PHP Manual

ingres_num_fields

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_num_fields — Get the number of fields returned by the last query

Description

int ingres_num_fields ( resource $result )

ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query().

Parameters

result

The query result identifier

Return Values

Returns the number of fields

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_next_error
ingres_num_rows
Ingres Functions


Get the number of rows affected or returned by a query

ingres_num_fields
ingres_pconnect
Ingres Functions
PHP Manual

ingres_num_rows

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_num_rows — Get the number of rows affected or returned by a query

Description

int ingres_num_rows ( resource $result )

This function primarily is meant to get the number of rows modified in the database. However, it can be used to retrieve the number of rows to fetch for a SELECT statement.

Note: If scrollable cursors are disabled and this function is called before using ingres_fetch_array(), ingres_fetch_object(), or ingres_fetch_row(), the server will delete the result's data and the script will be unable to get them.
Instead, you should retrieve the result's data using one of these fetch functions in a loop until it returns FALSE, indicating that no more results are available.

Parameters

result

The result identifier for a query

Return Values

For delete, insert, or update queries, ingres_num_rows() returns the number of rows affected by the query. For other queries, ingres_num_rows() returns the number of rows in the query's result.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_num_fields
ingres_pconnect
Ingres Functions


Open a persistent connection to an Ingres database

ingres_num_rows
ingres_prepare
Ingres Functions
PHP Manual

ingres_pconnect

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_pconnect — Open a persistent connection to an Ingres database

Description

resource ingres_pconnect ([ string $database [, string $username [, string $password [, array $options ]]]] )

Open a persistent connection to an Ingres database.

There are only two differences between this function and ingres_connect(): First, when connecting, the function will initially try to find a (persistent) link that is already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the Ingres server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ingres_close() will not close links established by ingres_pconnect()). This type of link is therefore called "persistent".

Parameters

database

The database name. Must follow the syntax:

[vnode::]dbname[/svr_class]

username

The Ingres user name

password

The password associated with username

options

See ingres_connect() for the list of options that can be passed

Return Values

Returns an Ingres link resource on success or FALSE on failure

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_close() - Close an Ingres database connection

ingres_num_rows
ingres_prepare
Ingres Functions


Prepare a query for later execution

ingres_pconnect
ingres_query
Ingres Functions
PHP Manual

ingres_prepare

(PECL ingres >= 1.1.0)

ingres_prepare — Prepare a query for later execution

Description

mixed ingres_prepare ( resource $link , string $query )

Prepares a query for execution by ingres_execute().

The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can call either ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed.

Note: Related Configurations
See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration.

Parameters

link

The connection link identifier

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation. See the query parameter in ingres_query() for a list of SQL statements which cannot be executed using ingres_prepare()

Return Values

ingres_prepare() returns a query result identifier that
is used with ingres_execute() to execute the query. To see
if an error occurred, use ingres_errno(),
ingres_error(), or
ingres_errsqlstate().

See Also

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

ingres_pconnect
ingres_query
Ingres Functions


Send an SQL query to Ingres

ingres_prepare
ingres_result_seek
Ingres Functions
PHP Manual

ingres_query

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_query — Send an SQL query to Ingres

Description

mixed ingres_query ( resource $link , string $query [, array $params [, string $types ]] )

ingres_query() sends the given query to the Ingres server.

The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can call either ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed.

Note: Related Configurations
See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration

Parameters

link

The connection link identifier.

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation.

Data inside the query should be properly escaped.

The following types of SQL queries cannot be sent with this function:

  • close (see ingres_close())
  • commit (see ingres_commit())
  • connect (see ingres_connect())
  • disconnect (see ingres_close())
  • get dbevent
  • prepare to commit
  • rollback (see ingres_rollback())
  • savepoint
  • set autocommit (see ingres_autocommit())
  • all cursor-related queries are unsupported

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. When ingres.describe is enabled, this parameter can be ignored as the driver automatically fetches the expected parameter types from the server.

Type code | Ingres type
b | BYTE
B | LONG BYTE/BLOB
c | CHAR
d | DATE/ANSIDATE/TIMESTAMP/TIME
f | FLOAT
i | INTEGER
L | LONG TEXT
m | MONEY
M | LONG NVARCHAR
n | NCHAR
N | NVARCHAR
t | TEXT
v | VARCHAR
V | LONG VARCHAR

Return Values

ingres_query() returns a query result identifier on
success else it returns FALSE. To see if an error
occurred use ingres_errno(),
ingres_error() or
ingres_errsqlstate().

Examples

Example #1 Send a simple select

<?php
$link = ingres_connect("demodb");

$result = ingres_query($link, "select * from user_profile");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #2 Passing query parameters to ingres_query()

<?php
$link = ingres_connect("demodb");

$params[] = "Emma";
$query = "select * from user_profile where up_first = ?";
$result = ingres_query($link, $query, $params);
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #3 Inserting a BLOB with parameter types

<?php
$link = ingres_connect("demodb");

//Open a photo
$fh = fopen("photo.jpg","r");
$blob_data = stream_get_contents($fh);
fclose($fh);

//Prepare parameters
$params[] = $blob_data;
$params[] = 1201;

//Define parameter types
$param_types = "Bi";

$query = "update user_profile set up_image = ? where up_id = ?";
$result = ingres_query($link, $query , $params, $param_types);

if (ingres_errno())
{
    echo ingres_errno() . "-" . ingres_error() . "\n";
}

ingres_commit($link);

ingres_close($link);
?>

See Also

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

ingres_prepare
ingres_result_seek
Ingres Functions


Set the row position before fetching data

ingres_query
ingres_rollback
Ingres Functions
PHP Manual

ingres_result_seek

(PECL ingres >= 2.1.0)

ingres_result_seek — Set the row position before fetching data

Description

boolean ingres_result_seek ( resource $result , integer $position )

This function is used to position the cursor associated with the result resource before issuing a fetch. If ingres.array_index_start is set to 0 then the first row is 0 else it is 1. ingres_result_seek() can be used only with queries that make use of scrollable cursors. It cannot be used with ingres_unbuffered_query().

Note: Related Configurations
See also the ingres.scrollable and ingres.array_index_start directives in Runtime Configuration.

Parameters

result

The result identifier for a query

position

The row to position the cursor on. If ingres.array_index_start is set to 0, then the first row is 0, else it is 1

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Position the cursor on the 3rd row

<?php

$result=ingres_query($link, "select * from airport where ap_ccode = 'ES' order by ap_place asc");

/* goto row 3 */
if (!ingres_result_seek($result, 3))
{
    echo ingres_errno() . " - " . ingres_error . "\n";
    die("i died");
}
else
{
    $airport = ingres_fetch_object ($result);
    {
        echo $airport->ap_iatacode . " - " .  $airport->ap_name . "\n";
    }
}

ingres_commit($link);

?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_query
ingres_rollback
Ingres Functions


Roll back a transaction

ingres_result_seek
ingres_set_environment
Ingres Functions
PHP Manual

ingres_rollback

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_rollback — Roll back a transaction

Description

bool ingres_rollback ( resource $link )

ingres_rollback() rolls back the currently open transaction, actually cancelling all changes made to the database during the transaction.

This closes the transaction. A new transaction can be opened by sending a query with ingres_query().

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_commit() - Commit a transaction
  • ingres_autocommit() - Switch autocommit on or off

ingres_result_seek
ingres_set_environment
Ingres Functions


Set environment features controlling output options

ingres_rollback
ingres_unbuffered_query
Ingres Functions
PHP Manual

ingres_set_environment

(PECL ingres >= 1.2.0)

ingres_set_environment — Set environment features controlling output options

Description

bool ingres_set_environment ( resource $link , array $options )

ingres_set_environment() is called to set environmental options that affect the output of certain values from Ingres, such as the timezone, date format, decimal character separator, and float precision.

Parameters

link

The connection link identifier

options

An enumerated array of option name/value pairs. The following table lists the option name and the expected type

Option name | Option type | Description | Example
date_century_boundary | integer | The threshold by which a 2-digit year is determined to be in the current century or in the next century. Equivalent to II_DATE_CENTURY_BOUNDARY | 50
timezone | string | Controls the timezone of the session. If not set, it will default the value defined by II_TIMEZONE_NAME. If II_TIMEZONE_NAME is not defined, NA-PACIFIC (GMT-8 with Daylight Savings) is used. | UNITED-KINGDOM
date_format integer

Sets the allowable input and output format for Ingres dates. Defaults to the value defined by II_DATE_FORMAT. If II_DATE_FORMAT is not set, the default date format is US, for example mm/dd/yy. Valid values for date_format are:

  • INGRES_DATE_DMY
  • INGRES_DATE_FINISH
  • INGRES_DATE_GERMAN
  • INGRES_DATE_ISO
  • INGRES_DATE_ISO4
  • INGRES_DATE_MDY
  • INGRES_DATE_MULTINATIONAL
  • INGRES_DATE_MULTINATIONAL4
  • INGRES_DATE_YMD
  • INGRES_DATE_US

 INGRES_DATE_ISO4
decimal_separator string The character identifier for decimal data ","
money_lort integer

Leading or trailing currency sign. Valid values for money_lort are:

  • INGRES_MONEY_LEADING
  • INGRES_MONEY_TRAILING

 INGRES_MONEY_LEADING
money_sign string The currency symbol to be used with the MONEY datatype €
money_precision | integer | The precision of the MONEY datatype | 2
float4_precision | integer | Precision of the FLOAT4 datatype | 10
float8_precision | integer | Precision of the FLOAT8 data | 10
blob_segment_length | integer | The amount of data in bytes to fetch at a time when retrieving BLOB or CLOB data. Defaults to 4096 bytes when not set explicitly | 8192

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Set date_format to ISO4

<?php
$options = array( "date_format" => INGRES_DATE_ISO4 );

if (ingres_set_environment($link, $options))
{
    $result=ingres_query($link,"select date('now') as date");

    while ( $object = ingres_fetch_object ($result) ) {
        echo $object->date."\n";
    }
}
?>

Example #2 Set timezone to HONG-KONG

<?php

$options = array( "timezone" => "HONG-KONG");

if (ingres_set_environment($link, $options))
{
    $result=ingres_query($link,"select date('now') as date");

    while ( $object = ingres_fetch_object ($result) ) {
        echo $object->date."\n";
    }
}
?>

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_query() - Send an SQL query to Ingres

ingres_rollback
ingres_unbuffered_query
Ingres Functions


Send an unbuffered SQL query to Ingres

ingres_set_environment
MaxDB
Ingres Functions
PHP Manual

ingres_unbuffered_query

(No version information available, might only be in SVN)

ingres_unbuffered_query — Send an unbuffered SQL query to Ingres

Description

mixed ingres_unbuffered_query ( resource $link , string $query [, array $params [, string $types ]] )

ingres_unbuffered_query() sends the given query to the Ingres server.

The query becomes part of the currently open transaction. If there is no open transaction, ingres_unbuffered_query() opens a new transaction. To close the transaction, you can call either ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed. Ingres allows only a single unbuffered statement to be active at any one time. The extension will close any active unbuffered statements before executing any SQL. In addition you cannot use ingres_result_seek() to position the row before fetching.

Note: Related Configurations
See also the ingres.describe and ingres.utf8 directives in Runtime Configuration.

Parameters

link

The connection link identifier

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation. See the query parameter in ingres_query() for a list of SQL statements that cannot be executed via ingres_unbuffered_query().

Data inside the query should be properly escaped.

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. See the types parameter in ingres_query() for the list of type codes.

Return Values

ingres_unbuffered_query() returns a query result identifier when there are rows to fetch; else it returns FALSE when there are no rows, as is the case of an INSERT, UPDATE, or DELETE statement. To see if an error occurred, use ingres_errno(), ingres_error(), or ingres_errsqlstate().

Examples

Example #1 Issue a simple un-buffered select

<?php
$link = ingres_connect("demodb");

$result = ingres_unbuffered_query($link, "select * from user_profile");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #2 Passing query parameters to ingres_unbuffered_query()

<?php
$link = ingres_connect("demodb");

$params[] = "Emma";
$query = "select * from user_profile where up_first = ?";
$result = ingres_unbuffered_query($link, $query, $params);
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #3 Inserting a BLOB with parameter types

<?php
$link = ingres_connect("demodb");

//Open a photo
$fh = fopen("photo.jpg","r");
$blob_data = stream_get_contents($fh);
fclose($fh);

//Prepare parameters
$params[] = $blob_data;
$params[] = 1201;

//Define parameter types
$param_types = "Bi";

$query = "update user_profile set up_image = ? where up_id = ?";
$result = ingres_unbuffered_query($link, $query , $params, $param_types);

if (ingres_errno())
{
    echo ingres_errno() . "-" . ingres_error() . "\n";
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated

ingres_set_environment
MaxDB
Ingres Functions


Alias of ini_set

getrusage
ini_get_all
PHP Options/Info Functions
PHP Manual

ini_alter

(PHP 4, PHP 5)

ini_alter — Alias of ini_set()

Description

This function is an alias of: ini_set().

getrusage
ini_get_all
PHP Options/Info Functions


Gets the value of a configuration option

ini_get_all
ini_restore
PHP Options/Info Functions
PHP Manual

ini_get

(PHP 4, PHP 5)

ini_get — Gets the value of a configuration option

Description

string ini_get ( string $varname )

Returns the value of the configuration option on success.

Parameters

varname

The configuration option name.

Return Values

Returns the value of the configuration option as a string on success, or an empty string on failure or for null values.

Examples

Example #1 A few ini_get() examples

<?php
/*
Our php.ini contains the following settings:

display_errors = On
register_globals = Off
post_max_size = 8M
*/

echo 'display_errors = ' . ini_get('display_errors') . "\n";
echo 'register_globals = ' . ini_get('register_globals') . "\n";
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
echo 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n";
echo 'post_max_size in bytes = ' . return_bytes(ini_get('post_max_size'));

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

?>

The above example will output something similar to:

display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9
post_max_size in bytes = 8388608

Notes

Note: When querying boolean values
A boolean ini value of off will be returned as an empty string or "0" while a boolean ini value of on will be returned as "1". The function can also return the literal string of INI value.

Note: When querying memory size values
Many ini memory size values, such as upload_max_filesize, are stored in the php.ini file in shorthand notation. ini_get() will return the exact string stored in the php.ini file and NOT its integer equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results. The example above shows one way to convert shorthand notation into bytes, much like how the PHP source does it.

See Also

  • get_cfg_var() - Gets the value of a PHP configuration option
  • ini_get_all() - Gets all configuration options
  • ini_restore() - Restores the value of a configuration option
  • ini_set() - Sets the value of a configuration option

ini_get_all
ini_restore
PHP Options/Info Functions


Gets all configuration options

ini_alter
ini_get
PHP Options/Info Functions
PHP Manual

ini_get_all

(PHP 4 >= 4.2.0, PHP 5)

ini_get_all — Gets all configuration options

Description

array ini_get_all ([ string $extension [, bool $details = true ]] )

Returns all the registered configuration options.

Parameters

extension

An optional extension name. If set, the function return only options specific for that extension.

details

Retrieve details settings or only the current value for each setting. Default is TRUE (retrieve details).

Return Values

Returns an associative array with directive name as the array key.

When details is TRUE (default) the array will contain global_value (set in php.ini), local_value (perhaps set with ini_set() or .htaccess), and access (the access level).

When details is FALSE the value will be the current value of the option.

See the manual section for information on what access levels mean.

Note: It's possible for a directive to have multiple access levels, which is why access shows the appropriate bitmask values.

Changelog

Version | Description
5.3.0 | Added details .

Examples

Example #1 ini_get_all() examples

<?php
print_r(ini_get_all("pcre"));
print_r(ini_get_all());
?>

The above example will output something similar to:

Array
(
    [pcre.backtrack_limit] => Array
        (
            [global_value] => 100000
            [local_value] => 100000
            [access] => 7
        )

    [pcre.recursion_limit] => Array
        (
            [global_value] => 100000
            [local_value] => 100000
            [access] => 7
        )

)
Array
(
    [allow_call_time_pass_reference] => Array
        (
            [global_value] => 0
            [local_value] => 0
            [access] => 6
        )

    [allow_url_fopen] => Array
        (
            [global_value] => 1
            [local_value] => 1
            [access] => 4
        )

    ...

)

Example #2 Disabling details

<?php
print_r(ini_get_all("pcre", false)); // Added in PHP 5.3.0
print_r(ini_get_all(null, false)); // Added in PHP 5.3.0
?>

The above example will output something similar to:

Array
(
    [pcre.backtrack_limit] => 100000
    [pcre.recursion_limit] => 100000
)
Array
(
    [allow_call_time_pass_reference] => 0
    [allow_url_fopen] => 1
    ...
)

See Also

  • How to change configuration settings
  • ini_get() - Gets the value of a configuration option
  • ini_restore() - Restores the value of a configuration option
  • ini_set() - Sets the value of a configuration option
  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • phpinfo() - Outputs lots of PHP information

ini_alter
ini_get
PHP Options/Info Functions


Restores the value of a configuration option

ini_get
ini_set
PHP Options/Info Functions
PHP Manual

ini_restore

(PHP 4, PHP 5)

ini_restore — Restores the value of a configuration option

Description

void ini_restore ( string $varname )

Restores a given configuration option to its original value.

Parameters

varname

The configuration option name.

Return Values

No value is returned.

Examples

Example #1 ini_restore() example

<?php
$setting = 'y2k_compliance';

echo 'Current value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_set($setting, ini_get($setting) ? 0 : 1);
echo 'New value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_restore($setting);
echo 'Original value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
?>

The above example will output:

Current value for 'y2k_compliance': 1
New value for 'y2k_compliance': 0
Original value for 'y2k_compliance': 1

See Also

  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options
  • ini_set() - Sets the value of a configuration option

ini_get
ini_set
PHP Options/Info Functions


Sets the value of a configuration option

ini_restore
magic_quotes_runtime
PHP Options/Info Functions
PHP Manual

ini_set

(PHP 4, PHP 5)

ini_set — Sets the value of a configuration option

Description

string ini_set ( string $varname , string $newvalue )

Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.

Parameters

varname

Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix.

newvalue

The new value for the option.

Return Values

Returns the old value on success, FALSE on failure.

Examples

Example #1 Setting an ini option

<?php
echo ini_get('display_errors');

if (!ini_get('display_errors')) {
    ini_set('display_errors', 1);
}

echo ini_get('display_errors');
?>

See Also

  • get_cfg_var() - Gets the value of a PHP configuration option
  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options
  • ini_restore() - Restores the value of a configuration option
  • How to change configuration settings

ini_restore
magic_quotes_runtime
PHP Options/Info Functions


Add a watch to an initialized inotify instance

Inotify Functions
inotify_init
Inotify Functions
PHP Manual

inotify_add_watch

(PECL inotify >= 0.1.2)

inotify_add_watch — Add a watch to an initialized inotify instance

Description

int inotify_add_watch ( resource $inotify_instance , string $pathname , int $mask )

inotify_add_watch() adds a new watch or modify an existing watch for the file or directory specified in pathname .

Using inotify_add_watch() on a watched object replaces the existing watch. Using the IN_MASK_ADD constant adds (OR) events to the existing watch.

Parameters

inotify_instance

Resource returned by inotify_init()

pathname

File or directory to watch

mask

Events to watch for. See Predefined Constants.

Return Values

The return value is a unique (inotify instance wide) watch descriptor.

See Also

  • inotify_init() - Initialize an inotify instance

Inotify Functions
inotify_init
Inotify Functions


Initialize an inotify instance

inotify_add_watch
inotify_queue_len
Inotify Functions
PHP Manual

inotify_init

(PECL inotify >= 0.1.2)

inotify_init — Initialize an inotify instance

Description

resource inotify_init ( void )

Initialize an inotify instance for use with inotify_add_watch()

Return Values

A stream resource or FALSE on error.

Examples

Example #1 Example usage of inotify

<?php
// Open an inotify instance
$fd = inotify_init();

// Watch __FILE__ for metadata changes (e.g. mtime)
$watch_descriptor = inotify_add_watch($fd, __FILE__, IN_ATTRIB);

// generate an event
touch(__FILE__);

// Read events
$events = inotify_read($fd);
print_r($events);

// The following methods allows to use inotify functions without blocking on inotify_read():

// - Using stream_select() on $fd:
$read = array($fd);
$write = null;
$except = null;
stream_select($read,$write,$except,0);

// - Using stream_set_blocking() on $fd
stream_set_blocking($fd, 0);
inotify_read($fd); // Does no block, and return false if no events are pending

// - Using inotify_queue_len() to check if event queue is not empty
$queue_len = inotify_queue_len($fd); // If > 0, inotify_read() will not block

// Stop watching __FILE__ for metadata changes
inotify_rm_watch($fd, $watch_descriptor);

// Close the inotify instance
// This may have closed all watches if this was not already done
fclose($fd);

?>

The above example will output something similar to:

array(
  array(
    'wd' => 1,     // Equals $watch_descriptor
    'mask' => 4,   // IN_ATTRIB bit is set
    'cookie' => 0, // unique id to connect related events (e.g.
                   // IN_MOVE_FROM and IN_MOVE_TO events)
    'name' => '',  // the name of a file (e.g. if we monitored changes
                   // in a directory)
  ),
);

See Also

  • inotify_add_watch() - Add a watch to an initialized inotify instance
  • inotify_rm_watch() - Remove an existing watch from an inotify instance
  • inotify_queue_len() - Return a number upper than zero if there are pending events
  • inotify_read() - Read events from an inotify instance
  • fclose() - Closes an open file pointer

inotify_add_watch
inotify_queue_len
Inotify Functions


Return a number upper than zero if there are pending events

inotify_init
inotify_read
Inotify Functions
PHP Manual

inotify_queue_len

(PECL inotify >= 0.1.2)

inotify_queue_len — Return a number upper than zero if there are pending events

Description

int inotify_queue_len ( resource $inotify_instance )

This function allows to know if inotify_read() will block or not. If a number upper than zero is returned, there are pending events and inotify_read() will not block.

Parameters

inotify_instance

Resource returned by inotify_init()

Return Values

Returns a number upper than zero if there are pending events.

See Also

  • inotify_init() - Initialize an inotify instance
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream

inotify_init
inotify_read
Inotify Functions


Read events from an inotify instance

inotify_queue_len
inotify_rm_watch
Inotify Functions
PHP Manual

inotify_read

(PECL inotify >= 0.1.2)

inotify_read — Read events from an inotify instance

Description

array inotify_read ( resource $inotify_instance )

Read inotify events from an inotify instance.

Parameters

inotify_instance

Resource returned by inotify_init()

Return Values

An array of inotify events or FALSE if no events was pending and inotify_instance is non-blocking. Each event is an array with the following keys:

  • wd is a watch descriptor returned by inotify_add_watch()
  • mask is a bit mask of events
  • cookie is a unique id to connect related events (e.g. IN_MOVE_FROM and IN_MOVE_TO)
  • name is the name of a file (e.g. if a file was modified in a watched directory)

See Also

  • inotify_init() - Initialize an inotify instance
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • inotify_queue_len() - Return a number upper than zero if there are pending events

inotify_queue_len
inotify_rm_watch
Inotify Functions


Remove an existing watch from an inotify instance

inotify_read
Mimetype
Inotify Functions
PHP Manual

inotify_rm_watch

(PECL inotify >= 0.1.2)

inotify_rm_watch — Remove an existing watch from an inotify instance

Description

bool inotify_rm_watch ( resource $inotify_instance , int $watch_descriptor )

inotify_rm_watch() removes the watch watch_descriptor from the inotify instance inotify_instance .

Parameters

inotify_instance

Resource returned by inotify_init()

watch_descriptor

Watch to remove from the instance

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • inotify_init() - Initialize an inotify instance

inotify_read
Mimetype
Inotify Functions


Get symbolic name for a given error code

intl Functions
intl_get_error_code
intl Functions
PHP Manual

intl_error_name

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_error_name — Get symbolic name for a given error code

Description

string intl_error_name ( int $error_code )

Return ICU error code name.

Parameters

error_code

ICU error code.

Return Values

The returned string will be the same as the name of the error code constant.

Examples

Example #1 intl_error_name() example

<?php
$coll     = collator_create( 'en_RU' );
$err_code = collator_get_error_code( $coll );

printf( "Symbolic name for %d is %s\n.", $err_code, intl_error_name( $err_code ) );
?>

The above example will output something similar to:

Symbolic name for -128 is U_USING_FALLBACK_WARNING.

See Also

  • intl_is_failure() - Check whether the given error code indicates failure
  • intl_get_error_code() - Get the last error code
  • intl_get_error_message() - Get description of the last error

intl Functions
intl_get_error_code
intl Functions


Get the last error code

intl_error_name
intl_get_error_message
intl Functions
PHP Manual

intl_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_get_error_code — Get the last error code

Description

int intl_get_error_code ( void )

Useful to handle errors occurred in static methods when there's no object to get error code from.

Return Values

Error code returned by the last API function call.

Examples

Example #1 intl_get_error_code() example

<?php
$coll = collator_create( '<bad_param>' );
if( !$coll ) {
    handle_error( intl_get_error_code() );
}
?>

See Also

  • intl_is_failure() - Check whether the given error code indicates failure
  • intl_error_name() - Get symbolic name for a given error code
  • intl_get_error_message() - Get description of the last error
  • collator_get_error_code() - Get collator's last error code
  • numfmt_get_error_code() - Get formatter's last error code.

intl_error_name
intl_get_error_message
intl Functions


Get description of the last error

intl_get_error_code
intl_is_failure
intl Functions
PHP Manual

intl_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_get_error_message — Get description of the last error

Description

string intl_get_error_message ( void )

Get error message from last internationalization function called.

Return Values

Description of an error occurred in the last API function call.

Examples

Example #1 intl_get_error_message() example

<?php
if( Collator::getAvailableLocales() === false ) {
    show_error( intl_get_error_message() );
}
?>

See Also

  • intl_error_name() - Get symbolic name for a given error code
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure
  • collator_get_error_message() - Get text for collator's last error code
  • numfmt_get_error_message() - Get formatter's last error message.

intl_get_error_code
intl_is_failure
intl Functions


Check whether the given error code indicates failure

intl_get_error_message
Multibyte String
intl Functions
PHP Manual

intl_is_failure

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_is_failure — Check whether the given error code indicates failure

Description

bool intl_is_failure ( int $error_code )

Parameters

error_code

is a value that returned by functions: intl_get_error_code(), collator_get_error_code() .

Return Values

TRUE if it the code indicates some failure, and FALSE in case of success or a warning.

Examples

Example #1 intl_is_failure() example

<?php
function check( $err_code )
{
    var_export( intl_is_failure( $err_code ) );
    echo "\n";
}

check( U_ZERO_ERROR );
check( U_USING_FALLBACK_WARNING );
check( U_ILLEGAL_ARGUMENT_ERROR );
?>

The above example will output something similar to:

false
false
true

See Also

  • intl_get_error_code() - Get the last error code
  • collator_get_error_code() - Get collator's last error code
  • Collator-getErrorCode() - Get collator's last error code

intl_get_error_message
Multibyte String
intl Functions


Embeds binary IPTC data into a JPEG image

imagexbm
iptcparse
GD and Image Functions
PHP Manual

iptcembed

(PHP 4, PHP 5)

iptcembed — Embeds binary IPTC data into a JPEG image

Description

mixed iptcembed ( string $iptcdata , string $jpeg_file_name [, int $spool ] )

Embeds binary IPTC data into a JPEG image.

Parameters

iptcdata

The data to be written.

jpeg_file_name

Path to the JPEG image.

spool

Spool flag. If the spool flag is over 2 then the JPEG will be returned as a string.

Return Values

If success and spool flag is lower than 2 then the JPEG will not be returned as a string, FALSE on errors.

Examples

Example #1 Embedding IPTC data into a JPEG

<?php

// iptc_make_tag() function by Thies C. Arntzen
function iptc_make_tag($rec, $data, $value)
{
    $length = strlen($value);
    $retval = chr(0x1C) . chr($rec) . chr($data);

    if($length < 0x8000)
    {
        $retval .= chr($length >> 8) .  chr($length & 0xFF);
    }
    else
    {
        $retval .= chr(0x80) .
                   chr(0x04) .
                   chr(($length >> 24) & 0xFF) .
                   chr(($length >> 16) & 0xFF) .
                   chr(($length >> 8) & 0xFF) .
                   chr($length & 0xFF);
    }

    return $retval . $value;
}

// Path to jpeg file
$path = './phplogo.jpg';

// We need to check if theres any IPTC data in the jpeg image. If there is then
// bail out because we cannot embed any image that already has some IPTC data!
$image = getimagesize($path, $info);

if(isset($info['APP13']))
{
    die('Error: IPTC data found in source image, cannot continue');
}

// Set the IPTC tags
$iptc = array(
    '2#120' => 'Test image',
    '2#116' => 'Copyright 2008-2009, The PHP Group'
);

// Convert the IPTC tags into binary code
$data = '';

foreach($iptc as $tag => $string)
{
    $tag = substr($tag, 2);
    $data .= iptc_make_tag(2, $tag, $string);
}

// Embed the IPTC data
$content = iptcembed($data, $path);

// Write the new image data out to the file.
$fp = fopen($path, "wb");
fwrite($fp, $content);
fclose($fp);
?>

Notes

Note: This function does not require the GD image library.

imagexbm
iptcparse
GD and Image Functions


Parse a binary IPTC block into single tags.

iptcembed
jpeg2wbmp
GD and Image Functions
PHP Manual

iptcparse

(PHP 4, PHP 5)

iptcparse — Parse a binary IPTC block into single tags.

Description

array iptcparse ( string $iptcblock )

Parses an » IPTC block into its single tags.

Parameters

iptcblock

A binary IPTC block.

Return Values

Returns an array using the tagmarker as an index and the value as the value. It returns FALSE on error or if no IPTC data was found.

Examples

Example #1 iptcparse() used together with getimagesize()

<?php
$size = getimagesize('./test.jpg', $info);
if(isset($info['APP13']))
{
    $iptc = iptcparse($info['APP13']);
    var_dump($iptc);
}
?>

Notes

Note: This function does not require the GD image library.

iptcembed
jpeg2wbmp
GD and Image Functions


Tells whether the filename is a directory

glob
is_executable
Filesystem Functions
PHP Manual

is_dir

(PHP 4, PHP 5)

is_dir — Tells whether the filename is a directory

Description

bool is_dir ( string $filename )

Tells whether the given filename is a directory.

Parameters

filename

Path to the file. If filename is a relative filename, it will be checked relative to the current working directory. If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled safe mode, or open_basedir further restrictions may apply.

Return Values

Returns TRUE if the filename exists and is a directory, FALSE otherwise.

Examples

Example #1 is_dir() example

<?php
var_dump(is_dir('a_file.txt'));
var_dump(is_dir('bogus_dir/abc'));

var_dump(is_dir('..')); //one dir up
?>

The above example will output:

bool(false)
bool(false)
bool(true)

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • chdir() - Change directory
  • dir
  • opendir() - Open directory handle
  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link

glob
is_executable
Filesystem Functions


Tells whether the filename is executable

is_dir
is_file
Filesystem Functions
PHP Manual

is_executable

(PHP 4, PHP 5)

is_executable — Tells whether the filename is executable

Description

bool is_executable ( string $filename )

Tells whether the filename is executable.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is executable, or FALSE on error.

Changelog

Version | Description
5.0.0 | is_executable() became available with Windows

Examples

Example #1 is_executable() example

<?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
    echo $file.' is executable';
} else {
    echo $file.' is not executable';
}

?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link

is_dir
is_file
Filesystem Functions


Tells whether the filename is a regular file

is_executable
is_link
Filesystem Functions
PHP Manual

is_file

(PHP 4, PHP 5)

is_file — Tells whether the filename is a regular file

Description

bool is_file ( string $filename )

Tells whether the given file is a regular file.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is a regular file, FALSE otherwise.

Examples

Example #1 is_file() example

<?php
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>

The above example will output:

bool(true)
bool(false)

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • is_dir() - Tells whether the filename is a directory
  • is_link() - Tells whether the filename is a symbolic link

is_executable
is_link
Filesystem Functions


Finds whether a value is a legal finite number

hypot
is_infinite
Math Functions
PHP Manual

is_finite

(PHP 4 >= 4.2.0, PHP 5)

is_finite — Finds whether a value is a legal finite number

Description

bool is_finite ( float $val )

Checks whether val is a legal finite on this platform.

Parameters

val

The value to check

Return Values

TRUE if val is a legal finite number within the allowed range for a PHP float on this platform, else FALSE.

See Also

  • is_infinite() - Finds whether a value is infinite
  • is_nan() - Finds whether a value is not a number

hypot
is_infinite
Math Functions


Finds whether a value is infinite

is_finite
is_nan
Math Functions
PHP Manual

is_infinite

(PHP 4 >= 4.2.0, PHP 5)

is_infinite — Finds whether a value is infinite

Description

bool is_infinite ( float $val )

Returns TRUE if val is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this platform.

Parameters

val

The value to check

Return Values

TRUE if val is infinite, else FALSE.

See Also

  • is_finite() - Finds whether a value is a legal finite number
  • is_nan() - Finds whether a value is not a number

is_finite
is_nan
Math Functions


Tells whether the filename is a symbolic link

is_file
is_readable
Filesystem Functions
PHP Manual

is_link

(PHP 4, PHP 5)

is_link — Tells whether the filename is a symbolic link

Description

bool is_link ( string $filename )

Tells whether the given file is a symbolic link.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is a symbolic link, FALSE otherwise.

Examples

Example #1 Create and confirm if a file is a symbolic link

<?php
$link = 'uploads';

if (is_link($link)) {
    echo(readlink($link));
} else {
    symlink('uploads.php', $link);
}
?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • is_dir() - Tells whether the filename is a directory
  • is_file() - Tells whether the filename is a regular file
  • readlink() - Returns the target of a symbolic link

is_file
is_readable
Filesystem Functions


Finds whether a value is not a number

is_infinite
lcg_value
Math Functions
PHP Manual

is_nan

(PHP 4 >= 4.2.0, PHP 5)

is_nan — Finds whether a value is not a number

Description

bool is_nan ( float $val )

Checks whether val is 'not a number', like the result of acos(1.01).

Parameters

val

The value to check

Return Values

Returns TRUE if val is 'not a number', else FALSE.

Examples

Example #1 is_nan() example

<?php
// Invalid calculation, will return a
// NaN value
$nan = acos(8);

var_dump($nan, is_nan($nan));
?>

The above example will output:

float(NAN)
bool(true)

See Also

  • is_finite() - Finds whether a value is a legal finite number
  • is_infinite() - Finds whether a value is infinite

is_infinite
lcg_value
Math Functions


Tells whether a file exists and is readable

is_link
is_uploaded_file
Filesystem Functions
PHP Manual

is_readable

(PHP 4, PHP 5)

is_readable — Tells whether a file exists and is readable

Description

bool is_readable ( string $filename )

Tells whether a file exists and is readable.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise.

Examples

Example #1 is_readable() example

<?php
$filename = 'test.txt';
if (is_readable($filename)) {
    echo 'The file is readable';
} else {
    echo 'The file is not readable';
}
?>

Notes

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account before PHP 5.1.5.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

Note: The check is done using the real UID/GID instead of the effective one.

See Also

  • is_writable() - Tells whether the filename is writable
  • file_exists() - Checks whether a file or directory exists
  • fgets() - Gets line from file pointer

is_link
is_uploaded_file
Filesystem Functions


Tells whether the file was uploaded via HTTP POST

is_readable
is_writable
Filesystem Functions
PHP Manual

is_uploaded_file

(PHP 4 >= 4.0.3, PHP 5)

is_uploaded_file — Tells whether the file was uploaded via HTTP POST

Description

bool is_uploaded_file ( string $filename )

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the clients machine $_FILES['userfile']['name'] does not work.

Parameters

filename

The filename being checked.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 is_uploaded_file() example

<?php

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
   echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
   echo "Displaying contents\n";
   readfile($_FILES['userfile']['tmp_name']);
} else {
   echo "Possible file upload attack: ";
   echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
}

?>

See Also

  • move_uploaded_file() - Moves an uploaded file to a new location
  • $_FILES
  • See Handling file uploadsfor a simple usage example.

is_readable
is_writable
Filesystem Functions


Tells whether the filename is writable

is_uploaded_file
is_writeable
Filesystem Functions
PHP Manual

is_writable

(PHP 4, PHP 5)

is_writable — Tells whether the filename is writable

Description

bool is_writable ( string $filename )

Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

Parameters

filename

The filename being checked.

Return Values

Returns TRUE if the filename exists and is writable.

Examples

Example #1 is_writable() example

<?php
$filename = 'test.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}
?>

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • is_readable() - Tells whether a file exists and is readable
  • file_exists() - Checks whether a file or directory exists
  • fwrite() - Binary-safe file write

is_uploaded_file
is_writeable
Filesystem Functions


Alias of is_writable

is_writable
lchgrp
Filesystem Functions
PHP Manual

is_writeable

(PHP 4, PHP 5)

is_writeable — Alias of is_writable()

Description

This function is an alias of: is_writable().

is_writable
lchgrp
Filesystem Functions


Returns the day of the week

GregorianToJD
JDMonthName
Calendar Functions
PHP Manual

JDDayOfWeek

(PHP 4, PHP 5)

JDDayOfWeek — Returns the day of the week

Description

mixed jddayofweek ( int $julianday [, int $mode = CAL_DOW_DAYNO ] )

Returns the day of the week. Can return a string or an integer depending on the mode.

Parameters

julianday

A julian day number as integer

mode
Calendar week modes
Mode | Meaning
0 (Default) | Return the day number as an int (0=Sunday, 1=Monday, etc)
1 | Returns string containing the day of week (English-Gregorian)
2 | Return a string containing the abbreviated day of week (English-Gregorian)

Return Values

The gregorian weekday as either an integer or string.

GregorianToJD
JDMonthName
Calendar Functions


Returns a month name

JDDayOfWeek
JDToFrench
Calendar Functions
PHP Manual

JDMonthName

(PHP 4, PHP 5)

JDMonthName — Returns a month name

Description

string jdmonthname ( int $julianday , int $mode )

Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.

Calendar modes
Mode | Meaning | Values
0 | Gregorian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
1 | Gregorian | January, February, March, April, May, June, July, August, September, October, November, December
2 | Julian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3 | Julian | January, February, March, April, May, June, July, August, September, October, November, December
4 | Jewish | Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
5 | French Republican | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

Parameters

jday

The Julian Day to operate on

calendar

The calendar to take the month name from

Return Values

The month name for the given Julian Day and calendar .

JDDayOfWeek
JDToFrench
Calendar Functions


Converts a Julian Day Count to the French Republican Calendar

JDMonthName
JDToGregorian
Calendar Functions
PHP Manual

JDToFrench

(PHP 4, PHP 5)

JDToFrench — Converts a Julian Day Count to the French Republican Calendar

Description

string jdtofrench ( int $juliandaycount )

Converts a Julian Day Count to the French Republican Calendar.

Parameters

julianday

A julian day number as integer

Return Values

The french revolution date as a string in the form "month/day/year"

See Also

  • frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

JDMonthName
JDToGregorian
Calendar Functions


Converts Julian Day Count to Gregorian date

JDToFrench
jdtojewish
Calendar Functions
PHP Manual

JDToGregorian

(PHP 4, PHP 5)

JDToGregorian — Converts Julian Day Count to Gregorian date

Description

string jdtogregorian ( int $julianday )

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

Parameters

julianday

A julian day number as integer

Return Values

The gregorian date as a string in the form "month/day/year"

See Also

  • gregoriantojd() - Converts a Gregorian date to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

JDToFrench
jdtojewish
Calendar Functions


Converts a Julian day count to a Jewish calendar date

JDToGregorian
JDToJulian
Calendar Functions
PHP Manual

jdtojewish

(PHP 4, PHP 5)

jdtojewish — Converts a Julian day count to a Jewish calendar date

Description

string jdtojewish ( int $juliandaycount [, bool $hebrew = false [, int $fl = 0 ]] )

Converts a Julian Day Count to the Jewish Calendar.

Parameters

julianday

A julian day number as integer

hebrew

If the hebrew parameter is set to TRUE, the fl parameter is used for Hebrew, string based, output format.

fl

The available formats are: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.

Return Values

The jewish date as a string in the form "month/day/year"

Changelog

Version | Description
5.0.0 | The fl parameter was added.
4.3.0 | The hebrew parameter was added.

Examples

Example #1 jdtojewish() Example

<?php
echo jdtojewish(gregoriantojd(10, 8, 2002), true,
       CAL_JEWISH_ADD_GERESHAYIM + CAL_JEWISH_ADD_ALAFIM + CAL_JEWISH_ADD_ALAFIM_GERESH);
?>

See Also

  • jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

JDToGregorian
JDToJulian
Calendar Functions


Converts a Julian Day Count to a Julian Calendar Date

jdtojewish
jdtounix
Calendar Functions
PHP Manual

JDToJulian

(PHP 4, PHP 5)

JDToJulian — Converts a Julian Day Count to a Julian Calendar Date

Description

string jdtojulian ( int $julianday )

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

Parameters

julianday

A julian day number as integer

Return Values

The julian date as a string in the form "month/day/year"

See Also

  • juliantojd() - Converts a Julian Calendar date to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

jdtojewish
jdtounix
Calendar Functions


Convert Julian Day to Unix timestamp

JDToJulian
JewishToJD
Calendar Functions
PHP Manual

jdtounix

(PHP 4, PHP 5)

jdtounix — Convert Julian Day to Unix timestamp

Description

int jdtounix ( int $jday )

This function will return a Unix timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the Unix epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is localtime (and not GMT).

Parameters

jday

A julian day number between 2440588 and 2465342.

Return Values

The unix timestamp for the start of the given julian day.

See Also

  • unixtojd() - Convert Unix timestamp to Julian Day

JDToJulian
JewishToJD
Calendar Functions


Converts a date in the Jewish Calendar to Julian Day Count

jdtounix
JulianToJD
Calendar Functions
PHP Manual

JewishToJD

(PHP 4, PHP 5)

JewishToJD — Converts a date in the Jewish Calendar to Julian Day Count

Description

int jewishtojd ( int $month , int $day , int $year )

Although this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

Parameters

month

The month as a number from 1 to 13

day

The day as a number from 1 to 30

year

The year as a number between 1 and 9999

Return Values

The julian day for the given jewish date as an integer.

See Also

  • jdtojewish() - Converts a Julian day count to a Jewish calendar date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count

jdtounix
JulianToJD
Calendar Functions


Convert JPEG image file to WBMP image file

iptcparse
png2wbmp
GD and Image Functions
PHP Manual

jpeg2wbmp

(PHP 4 >= 4.0.5, PHP 5)

jpeg2wbmp — Convert JPEG image file to WBMP image file

Description

bool jpeg2wbmp ( string $jpegname , string $wbmpname , int $dest_height , int $dest_width , int $threshold )

Converts a JPEG file into a WBMP file.

Parameters

jpegname

Path to JPEG file.

wbmpname

Path to destination WBMP file.

dest_height

Destination image height.

dest_width

Destination image width.

threshold

Threshold value, between 0 and 8 (inclusive).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 jpeg2wbmp() example

<?php
// Path to the target jpeg
$path = './test.jpg';

// Get the image sizes
$image = getimagesize($path);

// Convert image
jpeg2wbmp($path, './test.wbmp', $image[1], $image[0], 5);
?>

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Note: JPEG support is only available if PHP was compiled against GD-1.8 or later.

See Also

  • png2wbmp() - Convert PNG image file to WBMP image file

iptcparse
png2wbmp
GD and Image Functions


Decodes a JSON string

JSON Functions
json_encode
JSON Functions
PHP Manual

json_decode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_decode — Decodes a JSON string

Description

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 ]] )

Takes a JSON encoded string and converts it into a PHP variable.

Parameters

json

The json string being decoded.

assoc

When TRUE, returned objects will be converted into associative arrays.

depth

User specified recursion depth.

Return Values

Returns the value encoded in json in appropriate PHP type. Values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

Examples

Example #1 json_decode() examples

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

The above example will output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Example #2 Another example

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>

Example #3 common mistakes using json_decode()

<?php

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

?>

Example #4 depth errors

<?php
// Encode the data.
$json = json_encode(
    array(
        1 => array(
            'English' => array(
                'One',
                'January'
            ),
            'French' => array(
                'Une',
                'Janvier'
            )
        )
    )
);

// Define the errors.
$json_errors = array(
    JSON_ERROR_NONE => 'No error has occurred',
    JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
    JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
    JSON_ERROR_SYNTAX => 'Syntax error',
);

// Show the errors for different depths.
foreach(range(4, 3, -1) as $depth) {
    var_dump(json_decode($json, True, $depth));
    echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
    }
?>

The above example will output:

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["French"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Last error : No error has occurred

NULL
Last error : The maximum stack depth has been exceeded

Notes

Note: The JSON spec is not JavaScript, but a subset of JavaScript.

Note: In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.

Changelog

Version | Description
5.3.0 | Added the optional depth . The default recursion depth was increased from 128 to 512
5.2.3 | The nesting limit was increased from 20 to 128

See Also

  • json_encode() - Returns the JSON representation of a value
  • json_last_error() - Returns the last error occurred

JSON Functions
json_encode
JSON Functions


Returns the JSON representation of a value

json_decode
json_last_error
JSON Functions
PHP Manual

json_encode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_encode — Returns the JSON representation of a value

Description

string json_encode ( mixed $value [, int $options = 0 ] )

Returns a string containing the JSON representation of value .

Parameters

value

The value being encoded. Can be any type except a resource.

This function only works with UTF-8 encoded data.

options

Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_FORCE_OBJECT.

Return Values

Returns a JSON encoded string on success.

Changelog

Version | Description
5.3.0 | The options parameter was added.
5.2.1 | Added support to JSON encode basic types.

Examples

Example #1 A json_encode() example

<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);
?>

The above example will output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

Example #2 A json_encode() example showing all the options in action

<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&');

echo "Normal: ", json_encode($a), "\n";
echo "Tags: ",   json_encode($a,JSON_HEX_TAG), "\n";
echo "Apos: ",   json_encode($a,JSON_HEX_APOS), "\n";
echo "Quot: ",   json_encode($a,JSON_HEX_QUOT), "\n";
echo "Amp: ",    json_encode($a,JSON_HEX_AMP), "\n";
echo "All: ",    json_encode($a,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP), "\n\n";

$b = array();

echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";

$c = array(array(1,2,3));

echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";
?>

The above example will output:

Normal: ["<foo>","'bar'","\"baz\"","&blong&"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&"]
Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&"]
Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&"]
Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026"]

Empty array output as array: []
Empty array output as object: {}

Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}

See Also

  • json_decode() - Decodes a JSON string

json_decode
json_last_error
JSON Functions


Returns the last error occurred

json_encode
Misc.
JSON Functions
PHP Manual

json_last_error

(PHP 5 >= 5.3.0)

json_last_error — Returns the last error occurred

Description

int json_last_error ( void )

Returns the last error (if any) occurred by last JSON parsing.

Parameters

This function has no parameters.

Return Values

Returns an integer, the value can be one of the following constants:

JSON error codes
Constant | Meaning
JSON_ERROR_NONE | No error has occurred
JSON_ERROR_DEPTH | The maximum stack depth has been exceeded
JSON_ERROR_CTRL_CHAR | Control character error, possibly incorrectly encoded
JSON_ERROR_SYNTAX | Syntax error

Examples

Example #1 json_last_error() example

<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';

// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";

foreach($json as $string)
{
    echo 'Decoding: ' . $string;
    json_decode($string);

    switch(json_last_error())
    {
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
        break;
        case JSON_ERROR_NONE:
            echo ' - No errors';
        break;
    }

    echo PHP_EOL;
}
?>

The above example will output:

Decoding: {"Organization": "PHP Documentation Team"} - No errors
Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON

See Also

  • json_decode() - Decodes a JSON string

json_encode
Misc.
JSON Functions


Converts a Julian Calendar date to Julian Day Count

JewishToJD
unixtojd
Calendar Functions
PHP Manual

JulianToJD

(PHP 4, PHP 5)

JulianToJD — Converts a Julian Calendar date to Julian Day Count

Description

int juliantojd ( int $month , int $day , int $year )

Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.

Caution

Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.

Parameters

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4713 and 9999

Return Values

The julian day for the given julian date as an integer.

See Also

  • jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count

JewishToJD
unixtojd
Calendar Functions


Changes the principal's password

KADM5 Functions
kadm5_create_principal
KADM5 Functions
PHP Manual

kadm5_chpass_principal

(PECL kadm5 >= 0.2.3)

kadm5_chpass_principal — Changes the principal's password

Description

bool kadm5_chpass_principal ( resource $handle , string $principal , string $password )

kadm5_chpass_principal() sets the new password password for the principal .

Parameters

handle

A KADM5 handle.

principal

The principal.

password

The new password.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Example of changing principal's password

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_chpass_principal($handle, "burbach@GONICUS.LOCAL", "newpassword");

kadm5_destroy($handle);
?>

KADM5 Functions
kadm5_create_principal
KADM5 Functions


Creates a kerberos principal with the given parameters

kadm5_chpass_principal
kadm5_delete_principal
KADM5 Functions
PHP Manual

kadm5_create_principal

(PECL kadm5 >= 0.2.3)

kadm5_create_principal — Creates a kerberos principal with the given parameters

Description

bool kadm5_create_principal ( resource $handle , string $principal [, string $password [, array $options ]] )

Creates a principal with the given password .

Parameters

handle

A KADM5 handle.

principal

The principal.

password

If password is omitted or is NULL, a random key will be generated.

options

It is possible to specify several optional parameters within the array options . Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Example of principal's creation

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
                 KADM5_POLICY => "default",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

See Also

  • kadm5_modify_principal() - Modifies a kerberos principal with the given parameters
  • kadm5_delete_principal() - Deletes a kerberos principal

kadm5_chpass_principal
kadm5_delete_principal
KADM5 Functions


Deletes a kerberos principal

kadm5_create_principal
kadm5_destroy
KADM5 Functions
PHP Manual

kadm5_delete_principal

(PECL kadm5 >= 0.2.3)

kadm5_delete_principal — Deletes a kerberos principal

Description

bool kadm5_delete_principal ( resource $handle , string $principal )

Removes the principal from the Kerberos database.

Parameters

handle

A KADM5 handle.

principal

The removed principal.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 kadm5_delete_principal() example

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_delete_principal($handle, "burbach@GONICUS.LOCAL");

kadm5_destroy($handle);
?>

See Also

  • kadm5_modify_principal() - Modifies a kerberos principal with the given parameters
  • kadm5_create_principal() - Creates a kerberos principal with the given parameters

kadm5_create_principal
kadm5_destroy
KADM5 Functions


Closes the connection to the admin server and releases all related resources

kadm5_delete_principal
kadm5_flush
KADM5 Functions
PHP Manual

kadm5_destroy

(PECL kadm5 >= 0.2.3)

kadm5_destroy — Closes the connection to the admin server and releases all related resources

Description

bool kadm5_destroy ( resource $handle )

Closes the connection to the admin server and releases all related resources.

Parameters

handle

A KADM5 handle.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • kadm5_init_with_password() - Opens a connection to the KADM5 library

kadm5_delete_principal
kadm5_flush
KADM5 Functions


Flush all changes to the Kerberos database

kadm5_destroy
kadm5_get_policies
KADM5 Functions
PHP Manual

kadm5_flush

(PECL kadm5 >= 0.2.3)

kadm5_flush — Flush all changes to the Kerberos database

Description

bool kadm5_flush ( resource $handle )

Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open.

Parameters

handle

A KADM5 handle.

Return Values

Returns TRUE on success or FALSE on failure.

kadm5_destroy
kadm5_get_policies
KADM5 Functions


Gets all policies from the Kerberos database

kadm5_flush
kadm5_get_principal
KADM5 Functions
PHP Manual

kadm5_get_policies

(PECL kadm5 >= 0.2.3)

kadm5_get_policies — Gets all policies from the Kerberos database

Description

array kadm5_get_policies ( resource $handle )

Gets an array containing the policies's names.

Parameters

handle

A KADM5 handle.

Return Values

Returns array of policies on success or FALSE on failure.

Examples

Example #1 kadm5_get_policies() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_policies</h1>\n";
foreach (kadm5_get_policies($handle) as $policy) {
    echo "$policy<br />\n";
}

kadm5_destroy($handle);
?>

kadm5_flush
kadm5_get_principal
KADM5 Functions


Gets the principal's entries from the Kerberos database

kadm5_get_policies
kadm5_get_principals
KADM5 Functions
PHP Manual

kadm5_get_principal

(PECL kadm5 >= 0.2.3)

kadm5_get_principal — Gets the principal's entries from the Kerberos database

Description

array kadm5_get_principal ( resource $handle , string $principal )

Gets the principal's entries from the Kerberos database.

Parameters

handle

A KADM5 handle.

principal

The principal.

Return Values

Returns array of options containing the following keys: KADM5_PRINCIPAL, KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_MOD_NAME, KADM5_MOD_TIME, KADM5_KVNO, KADM5_POLICY, KADM5_MAX_RLIFE, KADM5_LAST_SUCCESS, KADM5_LAST_FAILED, KADM5_FAIL_AUTH_COUNT on success or FALSE on failure.

Examples

Example #1 kadm5_get_principal() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );

foreach ($options as $key => $value) {
    echo "$key: $value<br />\n";
}

kadm5_destroy($handle);
?>

See Also

  • kadm5_get_principals() - Gets all principals from the Kerberos database

kadm5_get_policies
kadm5_get_principals
KADM5 Functions


Gets all principals from the Kerberos database

kadm5_get_principal
kadm5_init_with_password
KADM5 Functions
PHP Manual

kadm5_get_principals

(PECL kadm5 >= 0.2.3)

kadm5_get_principals — Gets all principals from the Kerberos database

Description

array kadm5_get_principals ( resource $handle )

kadm5_get_principals() returns an array containing the principals's names.

Parameters

handle

A KADM5 handle.

Return Values

Returns array of principals on success or FALSE on failure.

Examples

Example #1 kadm5_get_principals() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_principals</h1>\n";
foreach (kadm5_get_principals($handle) as $principal) {
    echo "$principal<br />\n";
}

kadm5_destroy($handle);
?>

See Also

  • kadm5_get_principal() - Gets the principal's entries from the Kerberos database

kadm5_get_principal
kadm5_init_with_password
KADM5 Functions


Opens a connection to the KADM5 library

kadm5_get_principals
kadm5_modify_principal
KADM5 Functions
PHP Manual

kadm5_init_with_password

(PECL kadm5 >= 0.2.3)

kadm5_init_with_password — Opens a connection to the KADM5 library

Description

resource kadm5_init_with_password ( string $admin_server , string $realm , string $principal , string $password )

Opens a connection with the KADM5 library using the principal and the given password to obtain initial credentials from the admin_server .

Parameters

admin_server

The server.

realm

Defines the authentication domain for the connection.

principal

The principal.

password

If password is omitted or is NULL, a random key will be generated.

Return Values

Returns a KADM5 handle on success or FALSE on failure.

Examples

Example #1 KADM5 initialization example

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
                 KADM5_POLICY => "default",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

Notes

Note: Connection should be closed after use with kadm5_destroy().

See Also

  • kadm5_destroy() - Closes the connection to the admin server and releases all related resources

kadm5_get_principals
kadm5_modify_principal
KADM5 Functions


Modifies a kerberos principal with the given parameters

kadm5_init_with_password
Radius
KADM5 Functions
PHP Manual

kadm5_modify_principal

(PECL kadm5 >= 0.2.3)

kadm5_modify_principal — Modifies a kerberos principal with the given parameters

Description

bool kadm5_modify_principal ( resource $handle , string $principal , array $options )

Modifies a principal according to the given options .

Parameters

handle

A KADM5 handle.

principal

The principal.

options

It is possible to specify several optional parameters within the array options . Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE. KADM5_FAIL_AUTH_COUNT.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Example of modifying principal

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH;
$options = array(KADM5_PRINC_EXPIRE_TIME => 3451234,
                 KADM5_POLICY => "gonicus",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

kadm5_destroy($handle);
?>

See Also

  • kadm5_create_principal() - Creates a kerberos principal with the given parameters
  • kadm5_delete_principal() - Deletes a kerberos principal

kadm5_init_with_password
Radius
KADM5 Functions


Combined linear congruential generator

is_nan
log10
Math Functions
PHP Manual

lcg_value

(PHP 4, PHP 5)

lcg_value — Combined linear congruential generator

Description

float lcg_value ( void )

lcg_value() returns a pseudo random number in the range of (0, 1). The function combines two CGs with periods of 2^31 - 85 and 2^31 - 249. The period of this function is equal to the product of both primes.

Return Values

A pseudo random float value in the range of (0, 1)

See Also

  • rand() - Generate a random integer
  • mt_rand() - Generate a better random value

is_nan
log10
Math Functions


Changes group ownership of symlink

is_writeable
lchown
Filesystem Functions
PHP Manual

lchgrp

(PHP 5 >= 5.1.2)

lchgrp — Changes group ownership of symlink

Description

bool lchgrp ( string $filename , mixed $group )

Attempts to change the group of the symlink filename to group .

Only the superuser may change the group of a symlink arbitrarily; other users may change the group of a symlink to any group of which that user is a member.

Parameters

filename

Path to the symlink.

group

The group specified by name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing the group of a symbolic link

<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);

lchgrp($link, 8);
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: This function is not implemented on Windows platforms.

See Also

  • chgrp() - Changes file group
  • lchown() - Changes user ownership of symlink
  • chown() - Changes file owner
  • chmod() - Changes file mode

is_writeable
lchown
Filesystem Functions


Changes user ownership of symlink

lchgrp
link
Filesystem Functions
PHP Manual

lchown

(PHP 5 >= 5.1.2)

lchown — Changes user ownership of symlink

Description

bool lchown ( string $filename , mixed $user )

Attempts to change the owner of the symlink filename to user user .

Only the superuser may change the owner of a symlink.

Parameters

filename

Path to the file.

user

User name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing the owner of a symbolic link

<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);

lchown($link, 8);
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: This function is not implemented on Windows platforms.

See Also

  • chown() - Changes file owner
  • lchgrp() - Changes group ownership of symlink
  • chgrp() - Changes file group
  • chmod() - Changes file mode

lchgrp
link
Filesystem Functions


Create a hard link

lchown
linkinfo
Filesystem Functions
PHP Manual

link

(PHP 4, PHP 5)

link — Create a hard link

Description

bool link ( string $from_path , string $to_path )

link() creates a hard link.

Parameters

from_path

The link name.

to_path

Target of the link.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: For Windows only: This function requires PHP to run in an elevated mode or with the UAC disabled.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Examples

Example #1 Creating a simple hard link

<?php

$from_path = 'source.ext';  // This is the file that already exists
$to_path   = 'newfile.ext'; // This the filename that you want to link it to

link($from_path, $to_path);
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

See Also

  • symlink() - Creates a symbolic link
  • readlink() - Returns the target of a symbolic link
  • linkinfo() - Gets information about a link

lchown
linkinfo
Filesystem Functions


Gets information about a link

link
lstat
Filesystem Functions
PHP Manual

linkinfo

(PHP 4, PHP 5)

linkinfo — Gets information about a link

Description

int linkinfo ( string $path )

Gets information about a link.

This function is used to verify if a link (pointed to by path ) really exists (using the same method as the S_ISLNK macro defined in stat.h).

Parameters

path

Path to the link.

Return Values

linkinfo() returns the st_dev field of the Unix C stat structure returned by the lstat system call. Returns 0 or FALSE in case of error.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Examples

Example #1 linkinfo() example

<?php

echo linkinfo('/vmlinuz'); // 835

?>

See Also

  • symlink() - Creates a symbolic link
  • link() - Create a hard link
  • readlink() - Returns the target of a symbolic link

link
lstat
Filesystem Functions


Get the default Locale

i18n Functions
locale_set_default
i18n Functions
PHP Manual

locale_get_default

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

locale_get_default — Get the default Locale

Description

string locale_get_default ( void )

This function returns the default Locale, which is used by PHP to localize certain features. Please note that this isn't influenced by setlocale() or the system settings.

Return Values

Returns a string with the current Locale.

Examples

Example #1 A locale_get_default() example

<?php

// get the default Locale
echo locale_get_default();

//set a new Locale...
locale_set_default('pt_PT');

// ... and print it
echo locale_get_default();

?>

The above example will output:

en_US_POSIX
pt_PT

See Also

  • locale_set_default() - sets the default runtime locale

i18n Functions
locale_set_default
i18n Functions


Set the default Locale

locale_get_default
iconv
i18n Functions
PHP Manual

locale_set_default

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

locale_set_default — Set the default Locale

Description

bool locale_set_default ( string $name )

Sets the default Locale for PHP programs. Please note that this has nothing to do with setlocale() nor with the system locale.

Parameters

name

The new Locale name. A comprehensive list of the supported locales is available at » http://demo.icu-project.org/icu-bin/locexp.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A locale_set_default() example

This example demonstrates a possible usage of locale_set_default() to localize the sort() functions.

<?php

// the list of the strings to sort
$array = array(
    'caramelo',
    'cacto',
    'caçada'
);

// set our locale (Portuguese, in this case)
locale_set_default('pt_PT');

// sort using the locale we previously set
sort($array, SORT_LOCALE_STRING);

print_r($array);
?>

The above example will output:

Array
(
    [0] => caçada
    [1] => cacto
    [2] => caramelo
)

If we didn't use the locale, PHP would sort the string using the ASCII characters value, thus returning (wrongly):

Array
(
    [0] => cacto
    [1] => caramelo
    [2] => caçada
)

See Also

  • locale_get_default() - Gets the default locale value from the INTL global 'default_locale'

locale_get_default
iconv
i18n Functions


Get the local time

idate
microtime
Date/Time Functions
PHP Manual

localtime

(PHP 4, PHP 5)

localtime — Get the local time

Description

array localtime ([ int $timestamp = time() [, bool $is_associative = false ]] )

The localtime() function returns an array identical to that of the structure returned by the C function call.

Parameters

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

is_associative

If set to FALSE or not supplied then the array is returned as a regular, numerically indexed array. If the argument is set to TRUE then localtime() returns an associative array containing all the different elements of the structure returned by the C function call to localtime. The names of the different keys of the associative array are as follows:

  • "tm_sec" - seconds
  • "tm_min" - minutes
  • "tm_hour" - hour
  • "tm_mday" - day of the month Months are from 0 (Jan) to 11 (Dec) and days of the week are from 0 (Sun) to 6 (Sat).
  • "tm_mon" - month of the year, starting with 0 for January
  • "tm_year" - Years since 1900
  • "tm_wday" - Day of the week
  • "tm_yday" - Day of the year
  • "tm_isdst" - Is daylight savings time in effect

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 localtime() example

<?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

The above example will output something similar to:

Array
(
    [0] => 24
    [1] => 3
    [2] => 19
    [3] => 3
    [4] => 3
    [5] => 105
    [6] => 0
    [7] => 92
    [8] => 1
)

Array
(
    [tm_sec] => 24
    [tm_min] => 3
    [tm_hour] => 19
    [tm_mday] => 3
    [tm_mon] => 3
    [tm_year] => 105
    [tm_wday] => 0
    [tm_yday] => 92
    [tm_isdst] => 1
)

idate
microtime
Date/Time Functions


Natural logarithm

log1p
max
Math Functions
PHP Manual

log

(PHP 4, PHP 5)

log — Natural logarithm

Description

float log ( float $arg [, float $base = M_E ] )

If the optional base parameter is specified, log() returns logbase arg , otherwise log() returns the natural logarithm of arg .

Parameters

arg

The value to calculate the logarithm for

base

The optional logarithmic base to use (defaults to 'e' and so to the natural logarithm).

Return Values

The logarithm of arg to base , if given, or the natural logarithm.

Changelog

Version | Description
Since 4.3.0 | The optional parameter base became available. For older versions you can calculate the logarithm in base b of a number n, but using the mathematical identity: logb(n) = log(n)/log(b), where log is the neperian (or natural) logarithm.

See Also

  • log10() - Base-10 logarithm
  • exp() - Calculates the exponent of e
  • pow() - Exponential expression

log1p
max
Math Functions


Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

log10
log
Math Functions
PHP Manual

log1p

(PHP 4 >= 4.1.0, PHP 5)

log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

Description

float log1p ( float $number )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

log1p() returns log(1 + number ) computed in a way that is accurate even when the value of number is close to zero. log() might only return log(1) in this case due to lack of precision.

Parameters

number

The argument to process

Return Values

log(1 + number )

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • expm1() - Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
  • log() - Natural logarithm
  • log10() - Base-10 logarithm

log10
log
Math Functions


Base-10 logarithm

lcg_value
log1p
Math Functions
PHP Manual

log10

(PHP 4, PHP 5)

log10 — Base-10 logarithm

Description

float log10 ( float $arg )

Returns the base-10 logarithm of arg .

Parameters

arg

The argument to process

Return Values

The base-10 logarithm of arg

See Also

  • log() - Natural logarithm

lcg_value
log1p
Math Functions


Gives information about a file or symbolic link

linkinfo
mkdir
Filesystem Functions
PHP Manual

lstat

(PHP 4, PHP 5)

lstat — Gives information about a file or symbolic link

Description

array lstat ( string $filename )

Gathers the statistics of the file or symbolic link named by filename .

Parameters

filename

Path to a file or a symbolic link.

Return Values

See the manual page for stat() for information on the structure of the array that lstat() returns. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.

Examples

Example #1 Comparison of stat() and lstat()

<?php
symlink('uploads.php', 'uploads');

// Contrast information for uploads.php and uploads
array_diff(stat('uploads'), lstat('uploads'));
?>

The above example will output something similar to:

Information that differs between the two files.

Array
(
    [ino] => 97236376
    [mode] => 33188
    [size] => 34
    [atime] => 1223580003
    [mtime] => 1223581848
    [ctime] => 1223581848
    [blocks] => 8
)

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • stat() - Gives information about a file

linkinfo
mkdir
Filesystem Functions


LZF compression

LZF Functions
lzf_decompress
LZF Functions
PHP Manual

lzf_compress

(PECL lzf >= 0.1.0)

lzf_compress — LZF compression

Description

string lzf_compress ( string $data )

lzf_compress() compresses the given data string using LZF encoding.

Parameters

data

The string to compress.

Return Values

Returns the compressed data or FALSE if an error occurred.

See Also

  • lzf_decompress() - LZF decompression

LZF Functions
lzf_decompress
LZF Functions


LZF decompression

lzf_compress
lzf_optimized_for
LZF Functions
PHP Manual

lzf_decompress

(PECL lzf >= 0.1.0)

lzf_decompress — LZF decompression

Description

string lzf_decompress ( string $data )

lzf_compress() decompresses the given data string containing lzf encoded data.

Parameters

data

The compressed string.

Return Values

Returns the decompressed data or FALSE if an error occurred.

See Also

  • lzf_compress() - LZF compression

lzf_compress
lzf_optimized_for
LZF Functions


Determines what LZF extension was optimized for

lzf_decompress
Phar
LZF Functions
PHP Manual

lzf_optimized_for

(PECL lzf >= 1.0.0)

lzf_optimized_for — Determines what LZF extension was optimized for

Description

int lzf_optimized_for ( void )

Determines what was LZF extension optimized for during compilation.

Return Values

Returns 1 if LZF was optimized for speed, 0 for compression.

lzf_decompress
Phar
LZF Functions


Check to see if a transaction has completed

MCVE Functions
m_completeauthorizations
MCVE Functions
PHP Manual

m_checkstatus

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_checkstatus — Check to see if a transaction has completed

Description

int m_checkstatus ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

MCVE Functions
m_completeauthorizations
MCVE Functions


Number of complete authorizations in queue, returning an array of their identifiers

m_checkstatus
m_connect
MCVE Functions
PHP Manual

m_completeauthorizations

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_completeauthorizations — Number of complete authorizations in queue, returning an array of their identifiers

Description

int m_completeauthorizations ( resource $conn , int &$array )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

array

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

m_checkstatus
m_connect
MCVE Functions


Establish the connection to MCVE

m_completeauthorizations
m_connectionerror
MCVE Functions
PHP Manual

m_connect

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_connect — Establish the connection to MCVE

Description

int m_connect ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

m_completeauthorizations
m_connectionerror
MCVE Functions


Get a textual representation of why a connection failed

m_connect
m_deletetrans
MCVE Functions
PHP Manual

m_connectionerror

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_connectionerror — Get a textual representation of why a connection failed

Description

string m_connectionerror ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

m_connect
m_deletetrans
MCVE Functions


Delete specified transaction from MCVE_CONN structure

m_connectionerror
m_destroyconn
MCVE Functions
PHP Manual

m_deletetrans

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_deletetrans — Delete specified transaction from MCVE_CONN structure

Description

bool m_deletetrans ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

m_connectionerror
m_destroyconn
MCVE Functions


Destroy the connection and MCVE_CONN structure

m_deletetrans
m_destroyengine
MCVE Functions
PHP Manual

m_destroyconn

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_destroyconn — Destroy the connection and MCVE_CONN structure

Description

bool m_destroyconn ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

Returns TRUE.

See Also

  • m_initconn() - Create and initialize an MCVE_CONN structure

m_deletetrans
m_destroyengine
MCVE Functions


Free memory associated with IP/SSL connectivity

m_destroyconn
m_getcell
MCVE Functions
PHP Manual

m_destroyengine

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_destroyengine — Free memory associated with IP/SSL connectivity

Description

void m_destroyengine ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.

m_destroyconn
m_getcell
MCVE Functions


Get a specific cell from a comma delimited response by column name

m_destroyengine
m_getcellbynum
MCVE Functions
PHP Manual

m_getcell

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_getcell — Get a specific cell from a comma delimited response by column name

Description

string m_getcell ( resource $conn , int $identifier , string $column , int $row )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

column

row

Return Values

m_destroyengine
m_getcellbynum
MCVE Functions


Get a specific cell from a comma delimited response by column number

m_getcell
m_getcommadelimited
MCVE Functions
PHP Manual

m_getcellbynum

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_getcellbynum — Get a specific cell from a comma delimited response by column number

Description

string m_getcellbynum ( resource $conn , int $identifier , int $column , int $row )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

column

row

Return Values

m_getcell
m_getcommadelimited
MCVE Functions


Get the RAW comma delimited data returned from MCVE

m_getcellbynum
m_getheader
MCVE Functions
PHP Manual

m_getcommadelimited

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_getcommadelimited — Get the RAW comma delimited data returned from MCVE

Description

string m_getcommadelimited ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

m_getcellbynum
m_getheader
MCVE Functions


Get the name of the column in a comma-delimited response

m_getcommadelimited
m_initconn
MCVE Functions
PHP Manual

m_getheader

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_getheader — Get the name of the column in a comma-delimited response

Description

string m_getheader ( resource $conn , int $identifier , int $column_num )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

column_num

Return Values

m_getcommadelimited
m_initconn
MCVE Functions


Create and initialize an MCVE_CONN structure

m_getheader
m_initengine
MCVE Functions
PHP Manual

m_initconn

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_initconn — Create and initialize an MCVE_CONN structure

Description

resource m_initconn ( void )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns an MCVE_CONN resource.

See Also

  • m_destroyconn() - Destroy the connection and MCVE_CONN structure

m_getheader
m_initengine
MCVE Functions


Ready the client for IP/SSL Communication

m_initconn
m_iscommadelimited
MCVE Functions
PHP Manual

m_initengine

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_initengine — Ready the client for IP/SSL Communication

Description

int m_initengine ( string $location )
Warning

This function is currently not documented; only its argument list is available.

Parameters

location

Return Values

m_initconn
m_iscommadelimited
MCVE Functions


Checks to see if response is comma delimited

m_initengine
m_maxconntimeout
MCVE Functions
PHP Manual

m_iscommadelimited

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_iscommadelimited — Checks to see if response is comma delimited

Description

int m_iscommadelimited ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

m_initengine
m_maxconntimeout
MCVE Functions


The maximum amount of time the API will attempt a connection to MCVE

m_iscommadelimited
m_monitor
MCVE Functions
PHP Manual

m_maxconntimeout

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_maxconntimeout — The maximum amount of time the API will attempt a connection to MCVE

Description

bool m_maxconntimeout ( resource $conn , int $secs )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

secs

Return Values

m_iscommadelimited
m_monitor
MCVE Functions


Perform communication with MCVE (send/receive data) Non-blocking

m_maxconntimeout
m_numcolumns
MCVE Functions
PHP Manual

m_monitor

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_monitor — Perform communication with MCVE (send/receive data) Non-blocking

Description

int m_monitor ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

m_maxconntimeout
m_numcolumns
MCVE Functions


Number of columns returned in a comma delimited response

m_monitor
m_numrows
MCVE Functions
PHP Manual

m_numcolumns

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_numcolumns — Number of columns returned in a comma delimited response

Description

int m_numcolumns ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

m_monitor
m_numrows
MCVE Functions


Number of rows returned in a comma delimited response

m_numcolumns
m_parsecommadelimited
MCVE Functions
PHP Manual

m_numrows

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_numrows — Number of rows returned in a comma delimited response

Description

int m_numrows ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

m_numcolumns
m_parsecommadelimited
MCVE Functions


Parse the comma delimited response so m_getcell, etc will work

m_numrows
m_responsekeys
MCVE Functions
PHP Manual

m_parsecommadelimited

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_parsecommadelimited — Parse the comma delimited response so m_getcell, etc will work

Description

int m_parsecommadelimited ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

m_numrows
m_responsekeys
MCVE Functions


Returns array of strings which represents the keys that can be used for response parameters on this transaction

m_parsecommadelimited
m_responseparam
MCVE Functions
PHP Manual

m_responsekeys

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

m_responsekeys — Returns array of strings which represents the keys that can be used for response parameters on this transaction

Description

array m_responsekeys ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

m_parsecommadelimited
m_responseparam
MCVE Functions


Get a custom response parameter

m_responsekeys
m_returnstatus
MCVE Functions
PHP Manual

m_responseparam

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_responseparam — Get a custom response parameter

Description

string m_responseparam ( resource $conn , int $identifier , string $key )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

key

Return Values

m_responsekeys
m_returnstatus
MCVE Functions


Check to see if the transaction was successful

m_responseparam
m_setblocking
MCVE Functions
PHP Manual

m_returnstatus

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_returnstatus — Check to see if the transaction was successful

Description

int m_returnstatus ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

m_responseparam
m_setblocking
MCVE Functions


Set blocking/non-blocking mode for connection

m_returnstatus
m_setdropfile
MCVE Functions
PHP Manual

m_setblocking

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_setblocking — Set blocking/non-blocking mode for connection

Description

int m_setblocking ( resource $conn , int $tf )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values

m_returnstatus
m_setdropfile
MCVE Functions


Set the connection method to Drop-File

m_setblocking
m_setip
MCVE Functions
PHP Manual

m_setdropfile

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_setdropfile — Set the connection method to Drop-File

Description

int m_setdropfile ( resource $conn , string $directory )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

directory

Return Values

m_setblocking
m_setip
MCVE Functions


Set the connection method to IP

m_setdropfile
m_setssl_cafile
MCVE Functions
PHP Manual

m_setip

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_setip — Set the connection method to IP

Description

int m_setip ( resource $conn , string $host , int $port )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

host

port

Return Values

m_setdropfile
m_setssl_cafile
MCVE Functions


Set the connection method to SSL

m_setssl_files
m_settimeout
MCVE Functions
PHP Manual

m_setssl

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_setssl — Set the connection method to SSL

Description

int m_setssl ( resource $conn , string $host , int $port )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

host

port

Return Values

m_setssl_files
m_settimeout
MCVE Functions


Set SSL CA (Certificate Authority) file for verification of server certificate

m_setip
m_setssl_files
MCVE Functions
PHP Manual

m_setssl_cafile

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

m_setssl_cafile — Set SSL CA (Certificate Authority) file for verification of server certificate

Description

int m_setssl_cafile ( resource $conn , string $cafile )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

cafile

Return Values

m_setip
m_setssl_files
MCVE Functions


Set certificate key files and certificates if server requires client certificate verification

m_setssl_cafile
m_setssl
MCVE Functions
PHP Manual

m_setssl_files

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_setssl_files — Set certificate key files and certificates if server requires client certificate verification

Description

int m_setssl_files ( resource $conn , string $sslkeyfile , string $sslcertfile )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

sslkeyfile

sslcertfile

Return Values

m_setssl_cafile
m_setssl
MCVE Functions


Set maximum transaction time (per trans)

m_setssl
m_sslcert_gen_hash
MCVE Functions
PHP Manual

m_settimeout

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_settimeout — Set maximum transaction time (per trans)

Description

int m_settimeout ( resource $conn , int $seconds )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

seconds

Return Values

m_setssl
m_sslcert_gen_hash
MCVE Functions


Generate hash for SSL client certificate verification

m_settimeout
m_transactionssent
MCVE Functions
PHP Manual

m_sslcert_gen_hash

(PECL mcve >= 5.2.0)

m_sslcert_gen_hash — Generate hash for SSL client certificate verification

Description

string m_sslcert_gen_hash ( string $filename )
Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

Return Values

m_settimeout
m_transactionssent
MCVE Functions


Check to see if outgoing buffer is clear

m_sslcert_gen_hash
m_transinqueue
MCVE Functions
PHP Manual

m_transactionssent

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transactionssent — Check to see if outgoing buffer is clear

Description

int m_transactionssent ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

m_sslcert_gen_hash
m_transinqueue
MCVE Functions


Number of transactions in client-queue

m_transactionssent
m_transkeyval
MCVE Functions
PHP Manual

m_transinqueue

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transinqueue — Number of transactions in client-queue

Description

int m_transinqueue ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

m_transactionssent
m_transkeyval
MCVE Functions


Add key/value pair to a transaction. Replaces deprecated transparam()

m_transinqueue
m_transnew
MCVE Functions
PHP Manual

m_transkeyval

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

m_transkeyval — Add key/value pair to a transaction. Replaces deprecated transparam()

Description

int m_transkeyval ( resource $conn , int $identifier , string $key , string $value )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

key

value

Return Values

m_transinqueue
m_transnew
MCVE Functions


Start a new transaction

m_transkeyval
m_transsend
MCVE Functions
PHP Manual

m_transnew

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transnew — Start a new transaction

Description

int m_transnew ( resource $conn )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

m_transkeyval
m_transsend
MCVE Functions


Finalize and send the transaction

m_transnew
m_uwait
MCVE Functions
PHP Manual

m_transsend

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transsend — Finalize and send the transaction

Description

int m_transsend ( resource $conn , int $identifier )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values

m_transnew
m_uwait
MCVE Functions


Wait x microsecs

m_transsend
m_validateidentifier
MCVE Functions
PHP Manual

m_uwait

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_uwait — Wait x microsecs

Description

int m_uwait ( int $microsecs )
Warning

This function is currently not documented; only its argument list is available.

Parameters

microsecs

Return Values

m_transsend
m_validateidentifier
MCVE Functions


Whether or not to validate the passed identifier on any transaction it is passed to

m_uwait
m_verifyconnection
MCVE Functions
PHP Manual

m_validateidentifier

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

m_validateidentifier — Whether or not to validate the passed identifier on any transaction it is passed to

Description

int m_validateidentifier ( resource $conn , int $tf )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values

m_uwait
m_verifyconnection
MCVE Functions


Set whether or not to PING upon connect to verify connection

m_validateidentifier
m_verifysslcert
MCVE Functions
PHP Manual

m_verifyconnection

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_verifyconnection — Set whether or not to PING upon connect to verify connection

Description

bool m_verifyconnection ( resource $conn , int $tf )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values

m_validateidentifier
m_verifysslcert
MCVE Functions


Set whether or not to verify the server ssl certificate

m_verifyconnection
SPPLUS
MCVE Functions
PHP Manual

m_verifysslcert

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_verifysslcert — Set whether or not to verify the server ssl certificate

Description

bool m_verifysslcert ( resource $conn , int $tf )
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values

m_verifyconnection
SPPLUS
MCVE Functions


Alias of set_magic_quotes_runtime

ini_set
main
PHP Options/Info Functions
PHP Manual

magic_quotes_runtime

(PHP 4, PHP 5)

magic_quotes_runtime — Alias of set_magic_quotes_runtime()

Description

This function is an alias of: set_magic_quotes_runtime()

ini_set
main
PHP Options/Info Functions


Send mail

ezmlm_hash
Mailparse
Mail Functions
PHP Manual

mail

(PHP 4, PHP 5)

mail — Send mail

Description

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

Sends an email.

Parameters

to

Receiver, or receivers of the mail.

The formatting of this string must comply with » RFC 2822. Some examples are:

  • user@example.com
  • user@example.com, anotheruser@example.com
  • User <user@example.com>
  • User <user@example.com>, Another User <anotheruser@example.com>

subject

Subject of the email to be sent.

Caution

Subject must satisfy » RFC 2047.

message

Message to be sent.

Each line should be separated with a LF (\n). Lines should not be larger than 70 characters.

Caution

(Windows only) When PHP is talking to a SMTP server directly, if a full stop is found on the start of a line, it is removed. To counter-act this, replace these occurrences with a double dot.

<?php
$text = str_replace("\n.", "\n..", $text);
?>

additional_headers (optional)

String to be inserted at the end of the email header.

This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n).

Note: When sending mail, the mail must contain a From header. This can be set with the additional_headers parameter, or a default can be set in php.ini.
Failing to do this will result in an error message similar to Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. The From header sets also Return-Path under Windows.

Note: If messages are not received, try using a LF (\n) only. Some poor quality Unix mail transfer agents replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

additional_parameters (optional)

The additional_parameters parameter can be used to pass additional flags as command line options to the program configured to be used when sending mail, as defined by the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail with the -f sendmail option.

The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users.

Return Values

Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

Changelog

Version | Description
4.3.0 (Windows only) | All custom headers (like From, Cc, Bcc and Date) are supported, and are not case-sensitive. (As custom headers are not interpreted by the MTA in the first place, but are parsed by PHP, PHP < 4.3 only supported the Cc header element and was case-sensitive).
4.2.3 | The additional_parameters parameter is disabled in safe_mode and the mail() function will expose a warning message and return FALSE when used.
4.0.5 | The additional_parameters parameter was added.

Examples

Example #1 Sending mail.

Using mail() to send a simple email:

<?php
// The message
$message = "Line 1\nLine 2\nLine 3";

// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70);

// Send
mail('caffeinated@example.com', 'My Subject', $message);
?>

Example #2 Sending mail with extra headers.

The addition of basic headers, telling the MUA the From and Reply-To addresses:

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

Example #3 Sending mail with an additional command line parameter.

The additional_parameters parameter can be used to pass an additional parameter to the program configured to use when sending mail using the sendmail_path.

<?php
mail('nobody@example.com', 'the subject', 'the message', null,
   '-fwebmaster@example.com');
?>

Example #4 Sending HTML email

It is also possible to send HTML email with mail().

<?php
// multiple recipients
$to  = 'aidan@example.com' . ', '; // note the comma
$to .= 'wez@example.com';

// subject
$subject = 'Birthday Reminders for August';

// message
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);
?>

Note: If intending to send HTML or otherwise Complex mails, it is recommended to use the PEAR package » PEAR::Mail_Mime.

Notes

Note: The Windows implementation of mail() differs in many ways from the Unix implementation. First, it doesn't use a local binary for composing messages but only operates on direct sockets which means a MTA is needed listening on a network socket (which can either on the localhost or a remote machine).
Second, the custom headers like From:, Cc:, Bcc: and Date: are not interpreted by the MTA in the first place, but are parsed by PHP.
As such, the to parameter should not be an address in the form of "Something <someone@example.com>". The mail command may not parse this properly while talking with the MTA.

Note: It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient.
For the sending of large amounts of email, see the » PEAR::Mail, and » PEAR::Mail_Queue packages.

Note: The following RFCs may be useful: » RFC 1896, » RFC 2045, » RFC 2046, » RFC 2047, » RFC 2048, » RFC 2049, and » RFC 2822.

See Also

  • imap_mail() - Send an email message
  • » PEAR::Mail
  • » PEAR::Mail_Mime

ezmlm_hash
Mailparse
Mail Functions


Gets the best way of encoding

Mailparse Functions
mailparse_msg_create
Mailparse Functions
PHP Manual

mailparse_determine_best_xfer_encoding

(PECL mailparse >= 0.9.0)

mailparse_determine_best_xfer_encoding — Gets the best way of encoding

Description

string mailparse_determine_best_xfer_encoding ( resource $fp )

Figures out the best way of encoding the content read from the given file pointer.

Parameters

fp

A valid file pointer, which must be seek-able.

Return Values

Returns one of the character encodings supported by the mbstring module.

Examples

Example #1 mailparse_determine_best_xfer_encoding() example

<?php

$fp = fopen('somemail.eml', 'r');
echo 'Best encoding: ' . mailparse_determine_best_xfer_encoding($fp);

?>

The above example will output something similar to:

Best encoding: 7bit

Mailparse Functions
mailparse_msg_create
Mailparse Functions


Create a mime mail resource

mailparse_determine_best_xfer_encoding
mailparse_msg_extract_part_file
Mailparse Functions
PHP Manual

mailparse_msg_create

(PECL mailparse >= 0.9.0)

mailparse_msg_create — Create a mime mail resource

Description

resource mailparse_msg_create ( void )

Create a MIME mail resource.

Return Values

Returns a handle that can be used to parse a message.

See Also

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_parse_file() - Parses a file

mailparse_determine_best_xfer_encoding
mailparse_msg_extract_part_file
Mailparse Functions


Extracts/decodes a message section

mailparse_msg_extract_part_file
mailparse_msg_extract_whole_part_file
Mailparse Functions
PHP Manual

mailparse_msg_extract_part

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part — Extracts/decodes a message section

Description

void mailparse_msg_extract_part ( resource $mimemail , string $msgbody [, callback $callbackfunc ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mimemail

A valid MIME resource.

msgbody

callbackfunc

Return Values

No value is returned.

See Also

  • mailparse_msg_extract_part_file() - Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file() - Extracts a message section including headers without decoding the transfer encoding

mailparse_msg_extract_part_file
mailparse_msg_extract_whole_part_file
Mailparse Functions


Extracts/decodes a message section

mailparse_msg_create
mailparse_msg_extract_part
Mailparse Functions
PHP Manual

mailparse_msg_extract_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part_file — Extracts/decodes a message section

Description

string mailparse_msg_extract_part_file ( resource $mimemail , mixed $filename [, callback $callbackfunc ] )

Extracts/decodes a message section from the supplied filename.

The contents of the section will be decoded according to their transfer encoding - base64, quoted-printable and uuencoded text are supported.

Parameters

mimemail

A valid MIME resource, created with mailparse_msg_create().

filename

Can be a file name or a valid stream resource.

callbackfunc

If set, this must be either a valid callback that will be passed the extracted section, or NULL to make this function return the extracted section.

If not specified, the contents will be sent to "stdout".

Return Values

If callbackfunc is not NULL returns TRUE on success.

If callbackfunc is set to NULL, returns the extracted section as a string.

Returns FALSE on error.

See Also

  • mailparse_msg_extract_part() - Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file() - Extracts a message section including headers without decoding the transfer encoding

mailparse_msg_create
mailparse_msg_extract_part
Mailparse Functions


Extracts a message section including headers without decoding the transfer encoding

mailparse_msg_extract_part
mailparse_msg_free
Mailparse Functions
PHP Manual

mailparse_msg_extract_whole_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding

Description

string mailparse_msg_extract_whole_part_file ( resource $mimemail , string $filename [, callback $callbackfunc ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mimemail

A valid MIME resource.

filename

callbackfunc

Return Values

See Also

  • mailparse_msg_extract_part() - Extracts/decodes a message section
  • mailparse_msg_extract_part_file() - Extracts/decodes a message section

mailparse_msg_extract_part
mailparse_msg_free
Mailparse Functions


Frees a MIME resource

mailparse_msg_extract_whole_part_file
mailparse_msg_get_part_data
Mailparse Functions
PHP Manual

mailparse_msg_free

(PECL mailparse >= 0.9.0)

mailparse_msg_free — Frees a MIME resource

Description

bool mailparse_msg_free ( resource $mimemail )

Frees a MIME resource.

Parameters

mimemail

A valid MIME resource allocated by mailparse_msg_create() or mailparse_msg_parse_file().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mailparse_msg_create() - Create a mime mail resource
  • mailparse_msg_parse_file() - Parses a file

mailparse_msg_extract_whole_part_file
mailparse_msg_get_part_data
Mailparse Functions


Returns a handle on a given section in a mimemessage

mailparse_msg_get_part_data
mailparse_msg_get_structure
Mailparse Functions
PHP Manual

mailparse_msg_get_part

(PECL mailparse >= 0.9.0)

mailparse_msg_get_part — Returns a handle on a given section in a mimemessage

Description

resource mailparse_msg_get_part ( resource $mimemail , string $mimesection )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mimemail

A valid MIME resource.

mimesection

mailparse_msg_get_part_data
mailparse_msg_get_structure
Mailparse Functions


Returns an associative array of info about the message

mailparse_msg_free
mailparse_msg_get_part
Mailparse Functions
PHP Manual

mailparse_msg_get_part_data

(PECL mailparse >= 0.9.0)

mailparse_msg_get_part_data — Returns an associative array of info about the message

Description

array mailparse_msg_get_part_data ( resource $mimemail )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mimemail

A valid MIME resource.

mailparse_msg_free
mailparse_msg_get_part
Mailparse Functions


Returns an array of mime section names in the supplied message

mailparse_msg_get_part
mailparse_msg_parse_file
Mailparse Functions
PHP Manual

mailparse_msg_get_structure

(PECL mailparse >= 0.9.0)

mailparse_msg_get_structure — Returns an array of mime section names in the supplied message

Description

array mailparse_msg_get_structure ( resource $mimemail )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mimemail

A valid MIME resource.

mailparse_msg_get_part
mailparse_msg_parse_file
Mailparse Functions


Incrementally parse data into buffer

mailparse_msg_parse_file
mailparse_rfc822_parse_addresses
Mailparse Functions
PHP Manual

mailparse_msg_parse

(PECL mailparse >= 0.9.0)

mailparse_msg_parse — Incrementally parse data into buffer

Description

bool mailparse_msg_parse ( resource $mimemail , string $data )

Incrementally parse data into the supplied mime mail resource.

This function allow you to stream portions of a file at a time, rather than read and parse the whole thing.

Parameters

mimemail

A valid MIME resource.

data

Return Values

Returns TRUE on success or FALSE on failure.

mailparse_msg_parse_file
mailparse_rfc822_parse_addresses
Mailparse Functions


Parses a file

mailparse_msg_get_structure
mailparse_msg_parse
Mailparse Functions
PHP Manual

mailparse_msg_parse_file

(PECL mailparse >= 0.9.0)

mailparse_msg_parse_file — Parses a file

Description

resource mailparse_msg_parse_file ( string $filename )

Parses a file. This is the optimal way of parsing a mail file that you have on disk.

Parameters

filename

Path to the file holding the message. The file is opened and streamed through the parser.

Return Values

Returns a MIME resource representing the structure, or FALSE on error.

See Also

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_create() - Create a mime mail resource

mailparse_msg_get_structure
mailparse_msg_parse
Mailparse Functions


Parse RFC 822 compliant addresses

mailparse_msg_parse
mailparse_stream_encode
Mailparse Functions
PHP Manual

mailparse_rfc822_parse_addresses

(PECL mailparse >= 0.9.0)

mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses

Description

array mailparse_rfc822_parse_addresses ( string $addresses )

Parses a » RFC 822 compliant recipient list, such as that found in the To: header.

Parameters

addresses

A string containing addresses, like in: Wez Furlong <wez@example.com>, doe@example.com

Note: This string must not include the header name.

Return Values

Returns an array of associative arrays with the following keys for each recipient:

display | The recipient name, for display purpose. If this part is not set for a recipient, this key will hold the same value as address.
address | The email address
is_group | TRUE if the recipient is a newsgroup, FALSE otherwise.

Examples

Example #1 mailparse_rfc822_parse_addresses() example

<?php

$to = 'Wez Furlong <wez@example.com>, doe@example.com';
var_dump(mailparse_rfc822_parse_addresses($to));

?>

The above example will output:

array(2) {
  [0]=>
  array(3) {
    ["display"]=>
    string(11) "Wez Furlong"
    ["address"]=>
    string(15) "wez@example.com"
    ["is_group"]=>
    bool(false)
  }
  [1]=>
  array(3) {
    ["display"]=>
    string(15) "doe@example.com"
    ["address"]=>
    string(15) "doe@example.com"
    ["is_group"]=>
    bool(false)
  }
}

mailparse_msg_parse
mailparse_stream_encode
Mailparse Functions


Streams data from source file pointer, apply encoding and write to destfp

mailparse_rfc822_parse_addresses
mailparse_uudecode_all
Mailparse Functions
PHP Manual

mailparse_stream_encode

(PECL mailparse >= 0.9.0)

mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp

Description

bool mailparse_stream_encode ( resource $sourcefp , resource $destfp , string $encoding )

Streams data from the source file pointer, apply encoding and write to the destination file pointer.

Parameters

sourcefp

A valid file handle. The file is streamed through the parser.

destfp

The destination file handle in which the encoded data will be written.

encoding

One of the character encodings supported by the mbstring module.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mailparse_stream_encode() example

<?php

// email.eml contents: hello, this is some text=hello.
$fp = fopen('email.eml', 'r');

$dest = tmpfile();

mailparse_stream_encode($fp, $dest, "quoted-printable");

rewind($dest);

// Display new file contents
fpassthru($dest);

?>

The above example will output:

hello, this is some text=3Dhello.

mailparse_rfc822_parse_addresses
mailparse_uudecode_all
Mailparse Functions


Scans the data from fp and extract each embedded uuencoded file

mailparse_stream_encode
vpopmail
Mailparse Functions
PHP Manual

mailparse_uudecode_all

(PECL mailparse >= 0.9.0)

mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file

Description

array mailparse_uudecode_all ( resource $fp )

Scans the data from the given file pointer and extract each embedded uuencoded file into a temporary file.

Parameters

fp

A valid file pointer.

Return Values

Returns an array of associative arrays listing filename information.

filename | Path to the temporary file name created
origfilename | The original filename, for uuencoded parts only

The first filename entry is the message body. The next entries are the decoded uuencoded files.

Examples

Example #1 mailparse_uudecode_all() example

<?php

$text = <<<EOD
To: fred@example.com

hello, this is some text hello.
blah blah blah.

begin 644 test.txt
/=&AI<R!I<R!A('1E<W0*
`
end

EOD;

$fp = tmpfile();
fwrite($fp, $text);

$data = mailparse_uudecode_all($fp);

echo "BODY\n";
readfile($data[0]["filename"]);
echo "UUE ({$data[1]['origfilename']})\n";
readfile($data[1]["filename"]);

// Clean up
unlink($data[0]["filename"]);
unlink($data[1]["filename"]);

?>

The above example will output:

BODY
To: fred@example.com

hello, this is some text hello.
blah blah blah.

UUE (test.txt)
this is a test

mailparse_stream_encode
vpopmail
Mailparse Functions


Dummy for main

magic_quotes_runtime
memory_get_peak_usage
PHP Options/Info Functions
PHP Manual

main

main — Dummy for main()

Description

There is no function named main() except in the PHP source. In PHP 4.3.0, a new type of error handling in the PHP source (php_error_docref) was introduced. One feature is to provide links to a manual page in PHP error messages when the PHP directives html_errors (on by default) and docref_root (on by default until PHP 4.3.2) are set.

Sometimes error messages refer to a manual page for the function main() which is why this page exists. If you discover such a reference, please » file a bug report, indicating the PHP function caused the error that linked to main() and it will be fixed and properly documented.

Known errors that point to main()
Function name | No longer points here as of
include() | 5.1.0
include_once() | 5.1.0
require() | 5.1.0
require_once() | 5.1.0

See Also

  • html_errors
  • display_errors

magic_quotes_runtime
memory_get_peak_usage
PHP Options/Info Functions


Find highest value

log
min
Math Functions
PHP Manual

max

(PHP 4, PHP 5)

max — Find highest value

Description

mixed max ( array $values )
mixed max ( mixed $value1 , mixed $value2 [, mixed $value3... ] )

If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values.

Note: PHP will evaluate a non-numeric string as 0 if compared to integer, but still return the string if it's seen as the numerically highest value. If multiple arguments evaluate to 0, max() will return a numeric 0 if given, else the alphabetical highest string value will be returned.

Parameters

values

An array containing the values.

Return Values

max() returns the numerically highest of the parameter values. If multiple values can be considered of the same size, the one that is listed first will be returned.

When max() is given multiple arrays, the longest array is returned. If all the arrays have the same length, max() will use lexicographic ordering to find the return value.

When given a string it will be cast as an integer when comparing.

Examples

Example #1 Example uses of max()

<?php
echo max(1, 3, 5, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5

// When 'hello' is cast as integer it will be 0. Both the parameters are equally
// long, so the order they are given in determines the result
echo max(0, 'hello');     // 0
echo max('hello', 0);     // hello

echo max('42', 3); // '42'

// Here 0 > -1, so 'hello' is the return value.
echo max(-1, 'hello');    // hello

// With multiple arrays of different lengths, max returns the longest
$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)

// With multiple arrays of the same length, max compares from left to right
// using lexicographic order, so in our example: 2 == 2, but 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)

// If both an array and non-array are given, the array
// is always returned as it's seen as the largest
$val = max('string', array(2, 5, 7), 42);   // array(2, 5, 7)
?>

See Also

  • min() - Find lowest value
  • count() - Count all elements in an array, or properties in an object

log
min
Math Functions


Gets the number of affected rows in a previous MaxDB operation

MaxDB Functions
maxdb_autocommit
MaxDB Functions
PHP Manual

maxdb_affected_rows

maxdb->affected_rows

(PECL maxdb >= 1.0)

maxdb_affected_rows -- maxdb->affected_rows — Gets the number of affected rows in a previous MaxDB operation

Description

Procedural style:

int maxdb_affected_rows ( resource $link )

Object oriented style (property):

maxdb
int $affected_rows;

maxdb_affected_rows() returns the number of rows affected by the last INSERT, UPDATE, or DELETE query associated with the provided link parameter. If this number cannot be determined, this function will return -1.

Note: For SELECT statements maxdb_affected_rows() works like maxdb_num_rows().

The maxdb_affected_rows() function only works with queries which modify a table. In order to return the number of rows from a SELECT query, use the maxdb_num_rows() function instead.

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the number of rows affected can not be determined.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
$maxdb->query("CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", $maxdb->affected_rows);

$maxdb->query("ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
$maxdb->query("UPDATE mycustomer SET Status=1 WHERE cno > 50");
printf("Affected rows (UPDATE): %d\n", $maxdb->affected_rows);

/* delete rows */
$maxdb->query("DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", $maxdb->affected_rows);

/* select all rows */
$result = $maxdb->query("SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", $maxdb->affected_rows);

$result->close();

/* Delete table Language */
$maxdb->query("DROP TABLE mycustomer");

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
maxdb_query($link, "CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", maxdb_affected_rows($link));

maxdb_query($link, "ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
maxdb_query($link, "UPDATE mycustomer SET Status=1 WHERE cno > 50");
printf("Affected rows (UPDATE): %d\n", maxdb_affected_rows($link));

/* delete rows */
maxdb_query($link, "DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", maxdb_affected_rows($link));

/* select all rows */
$result = maxdb_query($link, "SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", maxdb_affected_rows($link));

maxdb_free_result($result);

/* Delete table Language */
maxdb_query($link, "DROP TABLE mycustomer");

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Affected rows (INSERT): 15
Affected rows (UPDATE): 15
Affected rows (DELETE): 0
Affected rows (SELECT): 15

See Also

  • maxdb_num_rows() - Gets the number of rows in a result
  • maxdb_info() - Retrieves information about the most recently executed query

MaxDB Functions
maxdb_autocommit
MaxDB Functions


Turns on or off auto-commiting database modifications

maxdb_affected_rows
maxdb_bind_param
MaxDB Functions
PHP Manual

maxdb_autocommit

maxdb->auto_commit

(PECL maxdb >= 1.0)

maxdb_autocommit -- maxdb->auto_commit — Turns on or off auto-commiting database modifications

Description

Procedural style:

bool maxdb_autocommit ( resource $link , bool $mode )

Object oriented style (method)

maxdb
bool auto_commit ( bool $mode )

maxdb_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link resource.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* turn autocommit on */
$maxdb->autocommit(TRUE);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
   exit();
}

/* turn autocommit on */
maxdb_autocommit($link, TRUE);

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

See Also

  • maxdb_commit() - Commits the current transaction
  • maxdb_rollback() - Rolls back current transaction

maxdb_affected_rows
maxdb_bind_param
MaxDB Functions


Alias of maxdb_stmt_bind_param

maxdb_autocommit
maxdb_bind_result
MaxDB Functions
PHP Manual

maxdb_bind_param

(PECL maxdb 1.0)

maxdb_bind_param — Alias of maxdb_stmt_bind_param()

Description

This function is an alias of: maxdb_stmt_bind_param()

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

maxdb_autocommit
maxdb_bind_result
MaxDB Functions


Alias of maxdb_stmt_bind_result

maxdb_bind_param
maxdb_change_user
MaxDB Functions
PHP Manual

maxdb_bind_result

(PECL maxdb 1.0)

maxdb_bind_result — Alias of maxdb_stmt_bind_result()

Description

This function is an alias of: maxdb_stmt_bind_result().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

maxdb_bind_param
maxdb_change_user
MaxDB Functions


Changes the user of the specified database connection

maxdb_bind_result
maxdb_character_set_name
MaxDB Functions
PHP Manual

maxdb_change_user

maxdb->change_user

(PECL maxdb >= 1.0)

maxdb_change_user -- maxdb->change_user — Changes the user of the specified database connection

Description

Procedural style:

bool maxdb_change_user ( resource $link , string $user , string $password , string $database )

Object oriented style (method):

maxdb
bool change_user ( string $user , string $password , string $database )

maxdb_change_user() is used to change the user of the specified database connection as given by the link parameter and to set the current database to that specified by the database parameter.

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

Note: Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php

/* connect database test */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT * FROM dual")) {
   $row = $result->fetch_row();
   printf("Result: %s\n", $row[0]);
   $result->free();
}

/* reset all and select a new database */
if (!$maxdb->change_user("DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT * FROM dual")) {
   $row = maxdb_fetch_row($result);
   printf("Result: %s\n", $row[0]);
   maxdb_free_result($result);
}

/* reset all and select a new database */
if (!maxdb_change_user($link, "DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Result: a
Database running

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_select_db() - Selects the default database for database queries

maxdb_bind_result
maxdb_character_set_name
MaxDB Functions


Returns the default character set for the database connection

maxdb_change_user
maxdb_client_encoding
MaxDB Functions
PHP Manual

maxdb_character_set_name

maxdb->character_set_name

(PECL maxdb >= 1.0)

maxdb_character_set_name -- maxdb->character_set_name — Returns the default character set for the database connection

Description

Procedural style:

string maxdb_character_set_name ( resource $link )

Object oriented style (method):

maxdb
string character_set_name ( void )

Returns the current character set for the database connection specified by the link parameter.

Return Values

The default character set for the current connection, either ascii or unicode.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Print current character set */
$charset = $maxdb->character_set_name();
printf ("Current character set is %s\n", $charset);

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Print current character set */
$charset = maxdb_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Current character set is ascii

See Also

  • maxdb_client_encoding() - Alias of maxdb_character_set_name
  • maxdb_real_escape_string() - Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

maxdb_change_user
maxdb_client_encoding
MaxDB Functions


Alias of maxdb_character_set_name

maxdb_character_set_name
maxdb_close_long_data
MaxDB Functions
PHP Manual

maxdb_client_encoding

(PECL maxdb 1.0)

maxdb_client_encoding — Alias of maxdb_character_set_name()

Description

This function is an alias of: maxdb_character_set_name().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

maxdb_character_set_name
maxdb_close_long_data
MaxDB Functions


Closes a previously opened database connection

maxdb_close_long_data
maxdb_commit
MaxDB Functions
PHP Manual

maxdb_close

maxdb->close

(PECL maxdb >= 1.0)

maxdb_close -- maxdb->close — Closes a previously opened database connection

Description

Procedural style:

bool maxdb_close ( resource $link )

Object oriented style (method):

maxdb
bool close ( void )

The maxdb_close() function closes a previously opened database connection specified by the link parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_real_connect() - Opens a connection to a MaxDB server

maxdb_close_long_data
maxdb_commit
MaxDB Functions


Alias of maxdb_stmt_close_long_data

maxdb_client_encoding
maxdb_close
MaxDB Functions
PHP Manual

maxdb_close_long_data

maxdb->close_long_data

(PECL maxdb >= 1.0)

maxdb_close_long_data -- maxdb->close_long_data — Alias of maxdb_stmt_close_long_data()

Description

This function is an alias of: maxdb_stmt_close_long_data().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

maxdb_client_encoding
maxdb_close
MaxDB Functions


Commits the current transaction

maxdb_close
maxdb_connect_errno
MaxDB Functions
PHP Manual

maxdb_commit

maxdb->commit

(PECL maxdb >= 1.0)

maxdb_commit -- maxdb->commit — Commits the current transaction

Description

Procedural style:

bool maxdb_commit ( resource $link )

Object oriented style (method)

maxdb
bool commit ( void )

Commits the current transaction for the database connection specified by the link parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* set autocommit to off */
$maxdb->autocommit(FALSE);

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query("CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
$maxdb->query("INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
$maxdb->query("INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
$maxdb->commit();

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* set autocommit to off */
maxdb_autocommit($link, FALSE);

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
maxdb_query($link, "INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
maxdb_query($link, "INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
maxdb_commit($link);

/* close connection */
maxdb_close($link);
?>

The above examples produces no output.

See Also

  • maxdb_autocommit() - Turns on or off auto-commiting database modifications
  • maxdb_rollback() - Rolls back current transaction

maxdb_close
maxdb_connect_errno
MaxDB Functions


Open a new connection to the MaxDB server

maxdb_connect_error
maxdb_data_seek
MaxDB Functions
PHP Manual

maxdb_connect

maxdb

(PECL maxdb >= 1.0)

maxdb_connect -- maxdb — Open a new connection to the MaxDB server

Description

Procedural style

resource maxdb_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket ]]]]]] )

Object oriented style (constructor):

maxdb
__construct ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket ]]]]]] )

The maxdb_connect() function attempts to open a connection to the MaxDB Server running on host which can be either a host name or an IP address. Passing the string "localhost" to this parameter, the local host is assumed. If successful, the maxdb_connect() will return an resource representing the connection to the database or FALSE on failure.

The username and password parameters specify the username and password under which to connect to the MaxDB server. If the password is not provided (the NULL value is passed), the MaxDB server will attempt to authenticate the user against the maxdb.default_pw in php.ini.

The dbname parameter if provided will specify the default database to be used when performing queries. If not provied, the entry maxdb.default_db in php.ini is used.

The port and socket parameters are ignored for the MaxDB server.

Return Values

Returns a resource which represents the connection to a MaxDB Server or FALSE if the connection failed.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("Host information: %s\n", $maxdb->host_info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("Host information: %s\n", maxdb_get_host_info($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Host information: localhost
maxdb_connect_error
maxdb_data_seek
MaxDB Functions


Returns the error code from last connect call

maxdb_commit
maxdb_connect_error
MaxDB Functions
PHP Manual

maxdb_connect_errno

(PECL maxdb >= 1.0)

maxdb_connect_errno — Returns the error code from last connect call

Description

int maxdb_connect_errno ( void )

The maxdb_connect_errno() function will return the last error code number for last call to maxdb_connect(). If no errors have occured, this function will return zero.

Return Values

An error code value for the last call to maxdb_connect(), if it failed. zero means no error occurred.

Examples

Example #1 maxdb_connect_errno sample

<?php
$link = maxdb_connect("localhost", "XXXXXXXX", "YYYYYYYYY");

if (!$link) {
   printf("Can't connect to localhost. Errorcode: %d\n", maxdb_connect_errno());
}
?>

The above example will output something similar to:

PHP Warning:  maxdb_connect(): -4008 POS(1) Unknown user name/password combination [08004] <...>
Can't connect to localhost. Errorcode: -4008

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

maxdb_commit
maxdb_connect_error
MaxDB Functions


Returns a string description of the last connect error

maxdb_connect_errno
maxdb_connect
MaxDB Functions
PHP Manual

maxdb_connect_error

(PECL maxdb >= 1.0)

maxdb_connect_error — Returns a string description of the last connect error

Description

string maxdb_connect_error ( void )

The maxdb_connect_error() function is identical to the corresponding maxdb_connect_errno() function in every way, except instead of returning an integer error code the maxdb_connect_error() function will return a string representation of the last error to occur for the last maxdb_connect() call. If no error has occured, this function will return an empty string.

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 maxdb_connect_error sample

<?php

$link = maxdb_connect("localhost", "nonexisting_user", "");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
}
?>

The above example will output something similar to:

PHP Warning:  maxdb_connect(): -4008 POS(1) Unknown user name/password combination <...>
Can't connect to localhost. Error: POS(1) Unknown user name/password combination

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

maxdb_connect_errno
maxdb_connect
MaxDB Functions


Adjusts the result pointer to an arbitary row in the result

maxdb_connect
maxdb_debug
MaxDB Functions
PHP Manual

maxdb_data_seek

result->data_seek

(PECL maxdb >= 1.0)

maxdb_data_seek -- result->data_seek — Adjusts the result pointer to an arbitary row in the result

Description

Procedural style:

bool maxdb_data_seek ( resource $result , int $offset )

Object oriented style (method):

result
bool data_seek ( int $offset )

The maxdb_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set represented by result . The offset parameter must be between zero and the total number of rows minus one (0..maxdb_num_rows() - 1).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER BY name";
if ($result = $maxdb->query( $query)) {

   /* seek to row no. 10 */
   $result->data_seek(10);

   /* fetch row */
   $row = $result->fetch_row();

   printf ("City: %s  State: %s\n", $row[0], $row[1]);

   /* free result set*/
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER BY name";

if ($result = maxdb_query($link, $query)) {

   /* seek to row no. 400 */
   maxdb_data_seek($result, 10);

   /* fetch row */
   $row = maxdb_fetch_row($result);

   printf ("City: %s  State: %s\n", $row[0], $row[1]);

   /* free result set*/
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

City: Irvine  State: CA

See Also

  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_num_rows() - Gets the number of rows in a result

maxdb_connect
maxdb_debug
MaxDB Functions


Performs debugging operations

maxdb_data_seek
maxdb_disable_reads_from_master
MaxDB Functions
PHP Manual

maxdb_debug

(PECL maxdb >= 1.0)

maxdb_debug — Performs debugging operations

Description

void maxdb_debug ( string $debug )

The maxdb_debug() can be used to trace the SQLDBC communication. The following strings can be used as a parameter to maxdb_debug():

  • TRACE SHORT ON|OFF - Enables/disables method call trace.
  • TRACE LONG ON|OFF - Enables/disables method argument and detail debug trace.
  • TRACE PACKET ON|OFF|<size> - Enables/disables packet trace, limiting the size of the traced object to the specified number of bytes, or 1000 if no size is specified.
  • TRACE SQL ON|OFF - Enables/disables high level api trace.
  • TRACE TIMESTAMP ON|OFF - Enables/disables a timestamp prefix on each line that is traced.
  • TRACE SIZE <size> - Limits the size of the trace file to <size> bytes, at least 8192 bytes are required.

Return Values

maxdb_debug() doesn't return any value.

Examples

Example #1 Procedural style

<?php

maxdb_debug("trace packet 200");

$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* close connection */
maxdb_close($link);
?>

The above example produces no output.

maxdb_data_seek
maxdb_disable_reads_from_master
MaxDB Functions


Disable reads from master

maxdb_debug
maxdb_disable_rpl_parse
MaxDB Functions
PHP Manual

maxdb_disable_reads_from_master

maxdb->disable_reads_from_master

(PECL maxdb >= 1.0)

maxdb_disable_reads_from_master -- maxdb->disable_reads_from_master — Disable reads from master

Description

Procedural style:

bool maxdb_disable_reads_from_master ( resource $link )

Object oriented style (method):

maxdb
void disable_reads_from_master ( void )
Warning

This function is currently not documented; only its argument list is available.

maxdb_debug
maxdb_disable_rpl_parse
MaxDB Functions


Disable RPL parse

maxdb_disable_reads_from_master
maxdb_dump_debug_info
MaxDB Functions
PHP Manual

maxdb_disable_rpl_parse

(PECL maxdb >= 1.0)

maxdb_disable_rpl_parse — Disable RPL parse

Description

bool maxdb_disable_rpl_parse ( resource $link )
Warning

This function is currently not documented; only its argument list is available.

maxdb_disable_reads_from_master
maxdb_dump_debug_info
MaxDB Functions


Dump debugging information into the log

maxdb_disable_rpl_parse
maxdb_embedded_connect
MaxDB Functions
PHP Manual

maxdb_dump_debug_info

(PECL maxdb >= 1.0)

maxdb_dump_debug_info — Dump debugging information into the log

Description

bool maxdb_dump_debug_info ( resource $link )
Warning

This function is currently not documented; only its argument list is available.

maxdb_disable_rpl_parse
maxdb_embedded_connect
MaxDB Functions


Open a connection to an embedded MaxDB server

maxdb_dump_debug_info
maxdb_enable_reads_from_master
MaxDB Functions
PHP Manual

maxdb_embedded_connect

(PECL maxdb >= 1.0)

maxdb_embedded_connect — Open a connection to an embedded MaxDB server

Description

resource maxdb_embedded_connect ([ string $dbname ] )
Warning

This function is currently not documented; only its argument list is available.

maxdb_dump_debug_info
maxdb_enable_reads_from_master
MaxDB Functions


Enable reads from master

maxdb_embedded_connect
maxdb_enable_rpl_parse
MaxDB Functions
PHP Manual

maxdb_enable_reads_from_master

(PECL maxdb >= 1.0)

maxdb_enable_reads_from_master — Enable reads from master

Description

bool maxdb_enable_reads_from_master ( resource $link )
Warning

This function is currently not documented; only its argument list is available.

maxdb_embedded_connect
maxdb_enable_rpl_parse
MaxDB Functions


Enable RPL parse

maxdb_enable_reads_from_master
maxdb_errno
MaxDB Functions
PHP Manual

maxdb_enable_rpl_parse

(PECL maxdb >= 1.0)

maxdb_enable_rpl_parse — Enable RPL parse

Description

bool maxdb_enable_rpl_parse ( resource $link )
Warning

This function is currently not documented; only its argument list is available.

maxdb_enable_reads_from_master
maxdb_errno
MaxDB Functions


Returns the error code for the most recent function call

maxdb_enable_rpl_parse
maxdb_error
MaxDB Functions
PHP Manual

maxdb_errno

maxdb->errno

(PECL maxdb >= 1.0)

maxdb_errno -- maxdb->errno — Returns the error code for the most recent function call

Description

Procedural style:

int maxdb_errno ( resource $link )

Object oriented style (property):

maxdb
int $errno;

The maxdb_errno() function will return the last error code for the most recent MaxDB function call that can succeed or fail with respect to the database link defined by the link parameter. If no errors have occured, this function will return zero.

Return Values

An error code value for the last call, if it failed. zero means no error occurred.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!$maxdb->query("SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", $maxdb->errno);
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!maxdb_query($link, "SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", maxdb_errno($link));
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] <...>
Errorcode: -4005

See Also

  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

maxdb_enable_rpl_parse
maxdb_error
MaxDB Functions


Returns a string description of the last error

maxdb_errno
maxdb_escape_string
MaxDB Functions
PHP Manual

maxdb_error

(PECL maxdb >= 1.0)

maxdb_error — Returns a string description of the last error

Description

Procedural style:

string maxdb_error ( resource $link )

Object oriented style (property)

maxdb
string $error;

The maxdb_error() function is identical to the corresponding maxdb_errno() function in every way, except instead of returning an integer error code the maxdb_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occured, this function will return an empty string.

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!$maxdb->query("SELECT xxx FROM hotel.city")) {
   printf("Errormessage: %s\n", $maxdb->error);
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!maxdb_query($link, "SELECT xxx FROM hotel.city")) {
   printf("Errormessgae: %s\n", maxdb_error($link));
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000]
Errormessgae: POS(8) Unknown column name:XXX

See Also

  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

maxdb_errno
maxdb_escape_string
MaxDB Functions


Alias of maxdb_real_escape_string

maxdb_error
maxdb_execute
MaxDB Functions
PHP Manual

maxdb_escape_string

(PECL maxdb 1.0)

maxdb_escape_string — Alias of maxdb_real_escape_string()

Description

This function is an alias of: maxdb_real_escape_string().

maxdb_error
maxdb_execute
MaxDB Functions


Alias of maxdb_stmt_execute

maxdb_escape_string
maxdb_fetch_array
MaxDB Functions
PHP Manual

maxdb_execute

(PECL maxdb 1.0)

maxdb_execute — Alias of maxdb_stmt_execute()

Description

This function is an alias of: maxdb_stmt_execute().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

maxdb_escape_string
maxdb_fetch_array
MaxDB Functions


Alias of maxdb_stmt_fetch

maxdb_fetch_row
maxdb_field_count
MaxDB Functions
PHP Manual

maxdb_fetch

(PECL maxdb 1.0)

maxdb_fetch — Alias of maxdb_stmt_fetch()

Description

This function is an alias of: maxdb_stmt_fetch().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

maxdb_fetch_row
maxdb_field_count
MaxDB Functions


Fetch a result row as an associative, a numeric array, or both

maxdb_execute
maxdb_fetch_assoc
MaxDB Functions
PHP Manual

maxdb_fetch_array

result->fetch_array

(PECL maxdb >= 1.0)

maxdb_fetch_array -- result->fetch_array — Fetch a result row as an associative, a numeric array, or both

Description

Procedural style:

mixed maxdb_fetch_array ( resource $result [, int $resulttype ] )

Object oriented style (method):

result
mixed fetch_array ([ int $resulttype ] )

Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

maxdb_fetch_array() is an extended version of the maxdb_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the maxdb_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.

The optional second argument resulttype is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MAXDB_ASSOC, MAXDB_ASSOC_UPPER, MAXDB_ASSOC_LOWER, MAXDB_NUM, or MAXDB_BOTH. By default the maxdb_fetch_array() function will assume MAXDB_BOTH, which is a combination of MAXDB_NUM and MAXDB_ASSOC for this parameter.

By using the MAXDB_ASSOC constant this function will behave identically to the maxdb_fetch_assoc(), while MAXDB_NUM will behave identically to the maxdb_fetch_row() function. The final option MAXDB_BOTH will create a single array with the attributes of both.

By using the MAXDB_ASSOC_UPPER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in upper case.

By using the MAXDB_ASSOC_LOWER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in lower case.

Return Values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";
$result = $maxdb->query($query);

/* numeric array */
$row = $result->fetch_array(MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result->fetch_array(MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);

/* associative and numeric array */
$row = $result->fetch_array(MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);

/* free result set */
$result->close();

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";
$result = maxdb_query($link, $query);

/* numeric array */
$row = maxdb_fetch_array($result, MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = maxdb_fetch_array($result, MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);

/* associative and numeric array */
$row = maxdb_fetch_array($result, MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);

/* free result set */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

New York (NY)
New York (NY)
Long Island (NY)

See Also

  • maxdb_fetch_assoc() - Fetch a result row as an associative array
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_fetch_resource()

maxdb_execute
maxdb_fetch_assoc
MaxDB Functions


Fetch a result row as an associative array

maxdb_fetch_array
maxdb_fetch_field_direct
MaxDB Functions
PHP Manual

maxdb_fetch_assoc

maxdb->fetch_assoc

(PECL maxdb >= 1.0)

maxdb_fetch_assoc -- maxdb->fetch_assoc — Fetch a result row as an associative array

Description

Procedural style:

array maxdb_fetch_assoc ( resource $result )

Object oriented style (method):

result
array fetch_assoc ( void )

Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

The maxdb_fetch_assoc() function is used to return an associative array representing the next row in the result set for the result represented by the result parameter, where each key in the array represents the name of one of the result set's columns.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using maxdb_fetch_row() or add alias names.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

Return Values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch associative array */
   while ($row = $result->fetch_assoc()) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch associative array */
   while ($row = maxdb_fetch_assoc($result)) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

See Also

  • maxdb_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_fetch_resource()

maxdb_fetch_array
maxdb_fetch_field_direct
MaxDB Functions


Returns the next field in the result set

maxdb_fetch_field_direct
maxdb_fetch_fields
MaxDB Functions
PHP Manual

maxdb_fetch_field

result->fetch_field

(PECL maxdb >= 1.0)

maxdb_fetch_field -- result->fetch_field — Returns the next field in the result set

Description

Procedural style:

mixed maxdb_fetch_field ( resource $result )

Object oriented style (method):

result
mixed fetch_field ( void )

The maxdb_fetch_field() returns the definition of one column of a result set as an resource. Call this function repeatedly to retrieve information about all columns in the result set. maxdb_fetch_field() returns FALSE when no more fields are left.

Return Values

Returns an resource which contains field definition information or FALSE if no field information is available.

Object properties
Property | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for all columns */
   while ($finfo = $result->fetch_field()) {

       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all fields */
   while ($finfo = maxdb_fetch_field($result)) {

       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field_direct() - Fetch meta-data for a single field
  • maxdb_fetch_fields() - Returns an array of resources representing the fields in a result set
  • maxdb_field_seek() - Set result pointer to a specified field offset

maxdb_fetch_field_direct
maxdb_fetch_fields
MaxDB Functions


Fetch meta-data for a single field

maxdb_fetch_assoc
maxdb_fetch_field
MaxDB Functions
PHP Manual

maxdb_fetch_field_direct

result->fetch_field_direct

(PECL maxdb >= 1.0)

maxdb_fetch_field_direct -- result->fetch_field_direct — Fetch meta-data for a single field

Description

Procedural style:

mixed maxdb_fetch_field_direct ( resource $result , int $fieldnr )

Object oriented style (method):

result
mixed fetch_field_direct ( int $fieldnr )

maxdb_fetch_field_direct() returns an resource which contains field definition information from specified resultset. The value of fieldnr must be in the range from 0 to number of fields - 1.

Return Values

Returns an resource which contains field definition information or FALSE if no field information for specified fieldnr is available.

Object attributes
Attribute | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY name";

if ($result = $maxdb->query($query)) {

   /* Get field information for column 'SurfaceArea' */
   $finfo = $result->fetch_field_direct(1);

   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n", $finfo->type);

   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY name";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for column 'cno' */
   $finfo = maxdb_fetch_field_direct($result, 1);

   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n", $finfo->type);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_fetch_fields() - Returns an array of resources representing the fields in a result set

maxdb_fetch_assoc
maxdb_fetch_field
MaxDB Functions


Returns an array of resources representing the fields in a result set

maxdb_fetch_field
maxdb_fetch_lengths
MaxDB Functions
PHP Manual

maxdb_fetch_fields

result->fetch_fields

(PECL maxdb >= 1.0)

maxdb_fetch_fields -- result->fetch_fields — Returns an array of resources representing the fields in a result set

Description

Procedural Style:

mixed maxdb_fetch_fields ( resource $result )

Object oriented style (method):

result
mixed fetch_fields ( void )

This function serves an identical purpose to the maxdb_fetch_field() function with the single difference that, instead of returning one resource at a time for each field, the columns are returned as an array of resources.

Return Values

Returns an array of resources which contains field definition information or FALSE if no field information is available.

Object properties
Property | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for all columns */
   $finfo = $result->fetch_fields();

   foreach ($finfo as $val) {
       printf("Name:     %s\n", $val->name);
       printf("Table:    %s\n", $val->table);
       printf("max. Len: %d\n", $val->max_length);
       printf("Flags:    %d\n", $val->flags);
       printf("Type:     %d\n\n", $val->type);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all columns */
   $finfo = maxdb_fetch_fields($result);

   foreach ($finfo as $val) {
       printf("Name:     %s\n", $val->name);
       printf("Table:    %s\n", $val->table);
       printf("max. Len: %d\n", $val->max_length);
       printf("Flags:    %d\n", $val->flags);
       printf("Type:     %d\n\n", $val->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_fetch_field_direct() - Fetch meta-data for a single field

maxdb_fetch_field
maxdb_fetch_lengths
MaxDB Functions


Returns the lengths of the columns of the current row in the result set

maxdb_fetch_fields
maxdb_fetch_object
MaxDB Functions
PHP Manual

maxdb_fetch_lengths

result->lengths

(PECL maxdb >= 1.0)

maxdb_fetch_lengths -- result->lengths — Returns the lengths of the columns of the current row in the result set

Description

Procedural style:

array maxdb_fetch_lengths ( resource $result )

Object oriented style (property):

result
array $lengths;

The maxdb_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set represented by the result parameter. If successful, a numerically indexed array representing the lengths of each column is returned or FALSE on failure.

Return Values

An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.

maxdb_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling maxdb_fetch_row/array/resource or after retrieving all rows in the result.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * from hotel.customer WHERE cno = 3000";

if ($result = $maxdb->query($query)) {

   $row = $result->fetch_row();

   /* display column lengths */
   foreach ($result->lengths as $i => $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * from hotel.customer WHERE cno = 3000";

if ($result = maxdb_query($link, $query)) {

   $row = maxdb_fetch_row($result);

   /* display column lengths */
   foreach (maxdb_fetch_lengths($result) as $i => $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Field  1 has Length  4
Field  2 has Length  3
Field  3 has Length  5
Field  4 has Length  6
Field  5 has Length  5
Field  6 has Length 21
maxdb_fetch_fields
maxdb_fetch_object
MaxDB Functions


Returns the current row of a result set as an object

maxdb_fetch_lengths
maxdb_fetch_row
MaxDB Functions
PHP Manual

maxdb_fetch_object

result->fetch_object

(PECL maxdb >= 1.0)

maxdb_fetch_object -- result->fetch_object — Returns the current row of a result set as an object

Description

Procedural style:

object maxdb_fetch_object ( object $result )

Object oriented style (method):

result
object fetch_object ( void )

The maxdb_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set. If no more rows exist in the current result set, NULL is returned.

Return Values

Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch object array */
   while ($obj = $result->fetch_object()) {
       printf ("%s (%s)\n", $obj->NAME, $obj->STATE);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch object array */
   while ($obj = maxdb_fetch_object($result)) {
       printf ("%s (%s)\n", $obj->NAME, $obj->STATE);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

See Also

  • maxdb_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_assoc() - Fetch a result row as an associative array
  • maxdb_fetch_row() - Get a result row as an enumerated array

maxdb_fetch_lengths
maxdb_fetch_row
MaxDB Functions


Get a result row as an enumerated array

maxdb_fetch_object
maxdb_fetch
MaxDB Functions
PHP Manual

maxdb_fetch_row

result->fetch_row

(PECL maxdb >= 1.0)

maxdb_fetch_row -- result->fetch_row — Get a result row as an enumerated array

Description

Procedural style:

mixed maxdb_fetch_row ( resource $result )

Object oriented style (method):

result
mixed fetch_row ( void )

Returns an array that corresponds to the fetched row, or NULL if there are no more rows.

maxdb_fetch_row() fetches one row of data from the result set represented by result and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to the maxdb_fetch_row() function will return the next row within the result set, or FALSE if there are no more rows.

Return Values

maxdb_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.

Note: This function sets NULL fields to the PHP NULL value.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch enumerated array */
   while ($row = $result->fetch_row()) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch enumerated array */
   while ($row = maxdb_fetch_row($result)) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

See Also

  • maxdb_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_assoc() - Fetch a result row as an associative array
  • maxdb_fetch_resource()

maxdb_fetch_object
maxdb_fetch
MaxDB Functions


Returns the number of columns for the most recent query

maxdb_fetch
maxdb_field_seek
MaxDB Functions
PHP Manual

maxdb_field_count

maxdb->field_count

(PECL maxdb >= 1.0)

maxdb_field_count -- maxdb->field_count — Returns the number of columns for the most recent query

Description

Procedural style:

int maxdb_field_count ( resource $link )

Object oriented style (method):

maxdb
int field_count ( void )

Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the maxdb_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

Return Values

An integer representing the number of fields in a result set.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query( "CREATE TABLE friends (id int, name varchar(20))");

$maxdb->query( "INSERT INTO friends VALUES (1,'Hartmut')");
$maxdb->query( "INSERT INTO friends VALUES (2, 'Ulf')");

if ($maxdb->field_count()) {
   /* this was a select/show or describe query */
   $result = $maxdb->store_result();

   /* process resultset */
   $row = $result->fetch_row();

   /* free resultset */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE friends (id int, name varchar(20))");

maxdb_query($link, "INSERT INTO friends VALUES (1,'Hartmut')");
maxdb_query($link, "INSERT INTO friends VALUES (2, 'Ulf')");

if (maxdb_field_count($link)) {
   /* this was a select/show or describe query */
   $result = maxdb_store_result($link);

   /* process resultset */
   $row = maxdb_fetch_row($result);

   /* free resultset */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example produces no output.

maxdb_fetch
maxdb_field_seek
MaxDB Functions


Set result pointer to a specified field offset

maxdb_field_count
maxdb_field_tell
MaxDB Functions
PHP Manual

maxdb_field_seek

result->field_seek

(PECL maxdb >= 1.0)

maxdb_field_seek -- result->field_seek — Set result pointer to a specified field offset

Description

Procedural style:

bool maxdb_field_seek ( resource $result , int $fieldnr )

Object oriented style (method):

result
bool field_seek ( int $fieldnr )

Sets the field cursor to the given offset. The next call to maxdb_fetch_field() will retrieve the field definition of the column associated with that offset.

Note: To seek to the beginning of a row, pass an offset value of zero.

Return Values

maxdb_field_seek() returns previuos value of field cursor.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for 2nd column */
   $result->field_seek(1);
   $finfo = $result->fetch_field();

   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n\n", $finfo->type);

   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for 2nd column */
   maxdb_field_seek($result, 1);
   $finfo = maxdb_fetch_field($result);

   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n\n", $finfo->type);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

See Also

  • maxdb_fetch_field() - Returns the next field in the result set

maxdb_field_count
maxdb_field_tell
MaxDB Functions


Get current field offset of a result pointer

maxdb_field_seek
maxdb_free_result
MaxDB Functions
PHP Manual

maxdb_field_tell

result->current_field

(PECL maxdb >= 1.0)

maxdb_field_tell -- result->current_field — Get current field offset of a result pointer

Description

Procedural style:

int maxdb_field_tell ( resource $result )

Object oriented style (property):

result
int $current_field ;

Returns the position of the field cursor used for the last maxdb_fetch_field() call. This value can be used as an argument to maxdb_field_seek().

Return Values

Returns current offset of field cursor.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for all columns */
   while ($finfo = $result->fetch_field()) {

       /* get fieldpointer offset */
       $currentfield = $result->current_field;

       printf("Column    %d:\n", $currentfield);
       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all fields */
   while ($finfo = maxdb_fetch_field($result)) {

       /* get fieldpointer offset */
       $currentfield = maxdb_field_tell($result);

       printf("Column    %d:\n", $currentfield);
       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Column    1:
Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Column    2:
Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_field_seek() - Set result pointer to a specified field offset

maxdb_field_seek
maxdb_free_result
MaxDB Functions


Frees the memory associated with a result

maxdb_field_tell
maxdb_get_client_info
MaxDB Functions
PHP Manual

maxdb_free_result

result->free

(PECL maxdb >= 1.0)

maxdb_free_result -- result->free — Frees the memory associated with a result

Description

Procedural style:

void maxdb_free_result ( resource $result )

Object oriented style (method):

result
void free ( void )

The maxdb_free_result() function frees the memory associated with the result represented by the result parameter, which was allocated by maxdb_query(), maxdb_store_result() or maxdb_use_result().

Note: You should always free your result with maxdb_free_result(), when your result resource is not needed anymore.

Return Values

This function doesn't return any value.

See Also

  • maxdb_query() - Performs a query on the database
  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_field_tell
maxdb_get_client_info
MaxDB Functions


Returns the MaxDB client version as a string

maxdb_free_result
maxdb_get_client_version
MaxDB Functions
PHP Manual

maxdb_get_client_info

(PECL maxdb >= 1.0)

maxdb_get_client_info — Returns the MaxDB client version as a string

Description

string maxdb_get_client_info ( void )

The maxdb_get_client_info() function is used to return a string representing the client version being used in the MaxDB extension.

Return Values

A string that represents the MaxDB client library version

Examples

Example #1 maxdb_get_client_info

<?php

/* We don't need a connection to determine
   the version of MaxDB client library */

printf("Client library version: %s\n", maxdb_get_client_info());
?>

The above example will output something similar to:

Client library version: libSQLDBC <...>

See Also

  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_info() - Returns the version of the MaxDB server
  • maxdb_get_server_version() - Returns the version of the MaxDB server as an integer

maxdb_free_result
maxdb_get_client_version
MaxDB Functions


Get MaxDB client info

maxdb_get_client_info
maxdb_get_host_info
MaxDB Functions
PHP Manual

maxdb_get_client_version

(PECL maxdb >= 1.0)

maxdb_get_client_version — Get MaxDB client info

Description

int maxdb_get_client_version ( void )

Returns client version number as an integer.

Return Values

A number that represents the MaxDB client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 7.5.0 is returned as 70500.

This is useful to quickly determine the version of the client library to know if some capability exists.

Examples

Example #1 maxdb_get_client_version

<?php

/* We don't need a connection to determine
   the version of MaxDB client library */

printf("Client library version: %d\n", maxdb_get_client_version());
?>

The above example will output something similar to:

Client library version: 7.<...>

See Also

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_server_info() - Returns the version of the MaxDB server
  • maxdb_get_server_version() - Returns the version of the MaxDB server as an integer

maxdb_get_client_info
maxdb_get_host_info
MaxDB Functions


Returns a string representing the type of connection used

maxdb_get_client_version
maxdb_get_metadata
MaxDB Functions
PHP Manual

maxdb_get_host_info

maxdb->get_host_info

(PECL maxdb >= 1.0)

maxdb_get_host_info -- maxdb->get_host_info — Returns a string representing the type of connection used

Description

Procdural style:

string maxdb_get_host_info ( resource $link )

Object oriented style (property):

maxdb
string $host_info;

The maxdb_get_host_info() function returns a string describing the connection represented by the link parameter is using.

Return Values

A character string representing the server hostname and the connection type.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print host information */
printf("Host info: %s\n", $maxdb->host_info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print host information */
printf("Host info: %s\n", maxdb_get_host_info($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Host info: localhost

See Also

  • maxdb_get_proto_info() - Returns the version of the MaxDB protocol used

maxdb_get_client_version
maxdb_get_metadata
MaxDB Functions


Alias of maxdb_stmt_result_metadata

maxdb_get_host_info
maxdb_get_proto_info
MaxDB Functions
PHP Manual

maxdb_get_metadata

(PECL maxdb 1.0)

maxdb_get_metadata — Alias of maxdb_stmt_result_metadata()

Description

This function is an alias of: maxdb_stmt_result_metadata().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

maxdb_get_host_info
maxdb_get_proto_info
MaxDB Functions


Returns the version of the MaxDB protocol used

maxdb_get_metadata
maxdb_get_server_info
MaxDB Functions
PHP Manual

maxdb_get_proto_info

maxdb->protocol_version

(PECL maxdb >= 1.0)

maxdb_get_proto_info -- maxdb->protocol_version — Returns the version of the MaxDB protocol used

Description

Procedural style:

int maxdb_get_proto_info ( resource $link )

Object oriented style (property):

maxdb
string $protocol_version;

Returns an integer representing the MaxDB protocol version used by the connection represented by the link parameter.

Return Values

Returns an integer representing the protocol version (constant 10).

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $maxdb->protocol_version);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print protocol version */
printf("Protocol version: %d\n", maxdb_get_proto_info($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Protocol version: 10

See Also

  • maxdb_get_host_info() - Returns a string representing the type of connection used

maxdb_get_metadata
maxdb_get_server_info
MaxDB Functions


Returns the version of the MaxDB server

maxdb_get_proto_info
maxdb_get_server_version
MaxDB Functions
PHP Manual

maxdb_get_server_info

maxdb->server_info

(PECL maxdb >= 1.0)

maxdb_get_server_info -- maxdb->server_info — Returns the version of the MaxDB server

Description

Procedural style:

string maxdb_get_server_info ( resource $link )

Object oriented style (property):

maxdb
string $server_info;

Returns a string representing the version of the MaxDB server that the MaxDB extension is connected to (represented by the link parameter).

Return Values

A character string representing the server version.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %s\n", $maxdb->server_info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %s\n", maxdb_get_server_info($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Server version: Kernel    7<...>

See Also

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_version() - Returns the version of the MaxDB server as an integer

maxdb_get_proto_info
maxdb_get_server_version
MaxDB Functions


Returns the version of the MaxDB server as an integer

maxdb_get_server_info
maxdb_info
MaxDB Functions
PHP Manual

maxdb_get_server_version

(PECL maxdb >= 1.0)

maxdb_get_server_version — Returns the version of the MaxDB server as an integer

Description

Procedural style:

int maxdb_get_server_version ( resource $link )

Object oriented style (property):

maxdb
int $server_version;

The maxdb_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.

The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 7.5.0 is 70500).

Return Values

An integer representing the server version.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %d\n", $maxdb->server_version);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %d\n", maxdb_get_server_version($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Server version: 7<...>

See Also

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_info() - Returns the version of the MaxDB server

maxdb_get_server_info
maxdb_info
MaxDB Functions


Retrieves information about the most recently executed query

maxdb_get_server_version
maxdb_init
MaxDB Functions
PHP Manual

maxdb_info

maxdb->info

(PECL maxdb >= 1.0)

maxdb_info -- maxdb->info — Retrieves information about the most recently executed query

Description

Procedural style:

string maxdb_info ( resource $link )

Object oriented style (property)

maxdb
string $info;

The maxdb_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

Possible maxdb_info return values
Query type | Example result string
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0

Note: Queries which do not fall into one of the above formats are not supported. In these situations, maxdb_info() will return an empty string.

Return Values

A character string representing additional information about the most recently executed query.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
$maxdb->query("INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", $maxdb->info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
maxdb_query($link, "INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", maxdb_info($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Records: 25 Duplicates: 0 Warnings: 0

See Also

  • maxdb_affected_rows() - Gets the number of affected rows in a previous MaxDB operation
  • maxdb_warning_count() - Returns the number of warnings from the last query for the given link
  • maxdb_num_rows() - Gets the number of rows in a result

maxdb_get_server_version
maxdb_init
MaxDB Functions


Initializes MaxDB and returns an resource for use with maxdb_real_connect

maxdb_info
maxdb_insert_id
MaxDB Functions
PHP Manual

maxdb_init

(PECL maxdb >= 1.0)

maxdb_init — Initializes MaxDB and returns an resource for use with maxdb_real_connect

Description

resource maxdb_init ( void )

Allocates or initializes a MaxDB resource suitable for maxdb_options() and maxdb_real_connect().

Note: Any subsequent calls to any maxdb function (except maxdb_options()) will fail until maxdb_real_connect() was called.

Return Values

Returns an resource.

See Also

  • maxdb_options() - Set options
  • maxdb_close() - Closes a previously opened database connection
  • maxdb_real_connect() - Opens a connection to a MaxDB server
  • maxdb_connect() - Open a new connection to the MaxDB server

maxdb_info
maxdb_insert_id
MaxDB Functions


Returns the auto generated id used in the last query

maxdb_init
maxdb_kill
MaxDB Functions
PHP Manual

maxdb_insert_id

maxdb->insert_id

(PECL maxdb >= 1.0)

maxdb_insert_id -- maxdb->insert_id — Returns the auto generated id used in the last query

Description

Procedural style:

mixed maxdb_insert_id ( resource $link )

Object oriented style (property):

maxdb
mixed $insert_id;

The maxdb_insert_id() function returns the ID generated by a query on a table with a column having the DEFAULT SERIAL attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the DEFAULT SERIAL attribute, this function will return zero.

Return Values

The value of the DEFAULT SERIAL field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an DEFAULT_SERIAL value.

Note: If the number is greater than maximal int value, maxdb_insert_id() will return a string.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query("CREATE TABLE mycity LIKE hotel.city");
$maxdb->query("ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
$maxdb->query($query);

printf ("New Record has id %d.\n", $maxdb->insert_id);

/* drop table */
$maxdb->query("DROP TABLE mycity");

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE mycity LIKE hotel.city");
maxdb_query($link, "ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
maxdb_query($link, $query);

printf ("New Record has id %d.\n", maxdb_insert_id($link));

/* drop table */
maxdb_query($link, "DROP TABLE mycity");

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

New Record has id 1.
maxdb_init
maxdb_kill
MaxDB Functions


Disconnects from a MaxDB server

maxdb_insert_id
maxdb_master_query
MaxDB Functions
PHP Manual

maxdb_kill

maxdb->kill

(PECL maxdb >= 1.0)

maxdb_kill -- maxdb->kill — Disconnects from a MaxDB server

Description

Procedural style:

bool maxdb_kill ( resource $link , int $processid )

Object oriented style (method)

maxdb
bool kill ( int $processid )

This function is used to disconnect from a MaxDB server specified by the processid parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = $maxdb->thread_id;

/* Kill connection */
$maxdb->kill($thread_id);

/* This should produce an error */
if (!$maxdb->query("CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", $maxdb->error);
   exit;
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = maxdb_thread_id($link);

/* Kill connection */
maxdb_kill($link, $thread_id);

/* This should produce an error */
if (!maxdb_query($link, "CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", maxdb_error($link));
   exit;
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Error: Session not connected

See Also

  • maxdb_thread_id() - Returns the thread ID for the current connection

maxdb_insert_id
maxdb_master_query
MaxDB Functions


Enforce execution of a query on the master in a master/slave setup

maxdb_kill
maxdb_more_results
MaxDB Functions
PHP Manual

maxdb_master_query

(PECL maxdb >= 1.0)

maxdb_master_query — Enforce execution of a query on the master in a master/slave setup

Description

bool maxdb_master_query ( resource $link , string $query )
Warning

This function is currently not documented; only its argument list is available.

maxdb_kill
maxdb_more_results
MaxDB Functions


Check if there any more query results from a multi query

maxdb_master_query
maxdb_multi_query
MaxDB Functions
PHP Manual

maxdb_more_results

maxdb->more_results

(PECL maxdb >= 1.0)

maxdb_more_results -- maxdb->more_results — Check if there any more query results from a multi query

Description

bool maxdb_more_results ( resource $link )

maxdb_more_results() indicates if one or more result sets are available from a previous call to maxdb_multi_query().

Return Values

Always FALSE.

Examples

See maxdb_multi_query().

See Also

  • maxdb_multi_query() - Performs a query on the database
  • maxdb_next_result() - Prepare next result from multi_query
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_master_query
maxdb_multi_query
MaxDB Functions


Performs a query on the database

maxdb_more_results
maxdb_next_result
MaxDB Functions
PHP Manual

maxdb_multi_query

maxdb->multi_query

(PECL maxdb >= 1.0)

maxdb_multi_query -- maxdb->multi_query — Performs a query on the database

Description

Procedural style:

bool maxdb_multi_query ( resource $link , string $query )

Object oriented style (method):

maxdb
bool multi_query ( string $query )

The maxdb_multi_query() works like the function maxdb_query(). Multiple queries are not yet supported.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM dual";

/* execute multi query */
if ($maxdb->multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb->store_result()) {
           while ($row = $result->fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result->close();
       }
       /* print divider */
       if ($maxdb->more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb->next_result());
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * FROM dual";

/* execute multi query */
if (maxdb_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = maxdb_store_result($link)) {
           while ($row = maxdb_fetch_row($result)) {
               printf("%s\n", $row[0]);
           }
           maxdb_free_result($result);
       }
       /* print divider */
       if (maxdb_more_results($link)) {
           printf("-----------------\n");
       }
   } while (maxdb_next_result($link));
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

a

See Also

  • maxdb_use_result() - Initiate a result set retrieval
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_next_result() - Prepare next result from multi_query
  • maxdb_more_results() - Check if there any more query results from a multi query

maxdb_more_results
maxdb_next_result
MaxDB Functions


Prepare next result from multi_query

maxdb_multi_query
maxdb_num_fields
MaxDB Functions
PHP Manual

maxdb_next_result

maxdb->next_result

(PECL maxdb >= 1.0)

maxdb_next_result -- maxdb->next_result — Prepare next result from multi_query

Description

bool maxdb_next_result ( resource $link )

Since multiple queries are not yet supported, maxdb_next_result() returns always FALSE.

Return Values

Returns FALSE.

See Also

  • maxdb_multi_query() - Performs a query on the database
  • maxdb_more_results() - Check if there any more query results from a multi query
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_multi_query
maxdb_num_fields
MaxDB Functions


Get the number of fields in a result

maxdb_next_result
maxdb_num_rows
MaxDB Functions
PHP Manual

maxdb_num_fields

result->field_count

(PECL maxdb >= 1.0)

maxdb_num_fields -- result->field_count — Get the number of fields in a result

Description

Procedural style:

int maxdb_num_fields ( resource $result )

Object oriented style (property):

result
int $field_count;

maxdb_num_fields() returns the number of fields from specified result set.

Return Values

The number of fields from a result set

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = $result->field_count;

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = maxdb_num_fields($result);

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Result set has 3 fields.

See Also

  • maxdb_fetch_field() - Returns the next field in the result set

maxdb_next_result
maxdb_num_rows
MaxDB Functions


Gets the number of rows in a result

maxdb_num_fields
maxdb_options
MaxDB Functions
PHP Manual

maxdb_num_rows

(PECL maxdb >= 1.0)

maxdb_num_rows — Gets the number of rows in a result

Description

Procedural style:

int maxdb_num_rows ( resource $result )

Object oriented style (property):

maxdb
int $num_rows;

Returns the number of rows in the result set.

The use of maxdb_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets maxdb_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.

Return Values

Returns number of rows in the result set.

Note: If the number of rows is greater than maximal int value, the number will be returned as a string.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = $result->num_rows;

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = maxdb_num_rows($result);

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Result set has 15 rows.

See Also

  • maxdb_affected_rows() - Gets the number of affected rows in a previous MaxDB operation
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval
  • maxdb_query() - Performs a query on the database

maxdb_num_fields
maxdb_options
MaxDB Functions


Set options

maxdb_num_rows
maxdb_param_count
MaxDB Functions
PHP Manual

maxdb_options

maxdb->options

(PECL maxdb >= 1.0)

maxdb_options -- maxdb->options — Set options

Description

Procedural style:

bool maxdb_options ( resource $link , int $option , mixed $value )

Object oriented style (method)

maxdb
bool options ( int $option , mixed $value )

maxdb_options() can be used to set extra connect options and affect behavior for a connection.

This function may be called multiple times to set several options.

maxdb_options() should be called after maxdb_init() and before maxdb_real_connect().

The parameter option is the option that you want to set, the value is the value for the option. For detailed description of the options see » http://maxdb.sap.com/documentation/ The parameter option can be one of the following values:

Valid options
Name | Description
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment.
MAXDB_APPLICATION | The application to be connected to the database.
MAXDB_APPVERSION | The version of the application.
MAXDB_SQLMODE | The SQL mode.
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not.
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system.
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released.
MAXDB_PACKETCOUNT | The number of different request packets used for the connection.
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use.
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See maxdb_real_connect().

See Also

  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_real_connect() - Opens a connection to a MaxDB server

maxdb_num_rows
maxdb_param_count
MaxDB Functions


Alias of maxdb_stmt_param_count

maxdb_options
maxdb_ping
MaxDB Functions
PHP Manual

maxdb_param_count

(PECL maxdb 1.0)

maxdb_param_count — Alias of maxdb_stmt_param_count()

Description

This function is an alias of: maxdb_stmt_param_count().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

maxdb_options
maxdb_ping
MaxDB Functions


Pings a server connection, or tries to reconnect if the connection has gone down

maxdb_param_count
maxdb_prepare
MaxDB Functions
PHP Manual

maxdb_ping

maxdb->ping

(PECL maxdb >= 1.0)

maxdb_ping -- maxdb->ping — Pings a server connection, or tries to reconnect if the connection has gone down

Description

Procedural style:

bool maxdb_ping ( resource $link )

Object oriented style (method):

maxdb
bool ping ( void )

Checks whether the connection to the server is working. If it has gone down, and global option maxdb.reconnect is enabled an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* check if server is alive */
if ($maxdb->ping()) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", $maxdb->error);
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* check if server is alive */
if (maxdb_ping($link)) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", maxdb_error($link));
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Our connection is ok!
maxdb_param_count
maxdb_prepare
MaxDB Functions


Prepare a SQL statement for execution

maxdb_ping
maxdb_query
MaxDB Functions
PHP Manual

maxdb_prepare

maxdb->prepare

(PECL maxdb >= 1.0)

maxdb_prepare -- maxdb->prepare — Prepare a SQL statement for execution

Description

Procedure style:

resource maxdb_prepare ( resource $link , string $query )

Object oriented style (method)

stmt
resource prepare ( string $query )

maxdb_prepare() prepares the SQL query pointed to by the null-terminated string query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.

Note: You should not add a terminating semicolon or \g to the statement.

The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.

Return Values

maxdb_prepare() returns a statement resource or FALSE if an error occured.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Rosemont";

/* create a prepared statement */
if ($stmt = $maxdb->prepare("SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   $stmt->bind_param("s", $city);

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($district);

   /* fetch value */
   $stmt->fetch();

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Rosemont";

/* create a prepared statement */
if ($stmt = maxdb_prepare($link, "SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   maxdb_stmt_bind_param($stmt, "s", $city);

   /* execute query */
   maxdb_stmt_execute($stmt);

  /* bind result variables */
   maxdb_stmt_bind_result($stmt, $district);

   /* fetch value */
   maxdb_stmt_fetch($stmt);

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Rosemont is in district IL

See Also

  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • maxdb_stmt_close() - Closes a prepared statement

maxdb_ping
maxdb_query
MaxDB Functions


Performs a query on the database

maxdb_prepare
maxdb_real_connect
MaxDB Functions
PHP Manual

maxdb_query

maxdb->query

(PECL maxdb >= 1.0)

maxdb_query -- maxdb->query — Performs a query on the database

Description

Procedural style:

mixed maxdb_query ( resource $link , string $query [, int $resultmode ] )

Object oriented style (method):

maxdb
mixed query ( string $query )

The maxdb_query() function is used to simplify the act of performing a query against the database represented by the link parameter.

Return Values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN maxdb_query() will return a result resource.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Create table doesn't return a resultset */
if ($maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $maxdb->query("SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", $result->num_rows);

   /* free result set */
   $result->close();
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = $maxdb->query("SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   $result->close();
}

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Create table doesn't return a resultset */
if (maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = maxdb_query($link, "SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", maxdb_num_rows($result));

   /* free result set */
   maxdb_free_result($result);
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = maxdb_query($link, "SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   maxdb_free_result($result);
}

maxdb_close($link);
?>

The above example will output something similar to:

Table mycity successfully created.
Select returned 25 rows.

See Also

  • maxdb_real_query() - Execute an SQL query
  • maxdb_multi_query() - Performs a query on the database
  • maxdb_free_result() - Frees the memory associated with a result

maxdb_prepare
maxdb_real_connect
MaxDB Functions


Opens a connection to a MaxDB server

maxdb_query
maxdb_real_escape_string
MaxDB Functions
PHP Manual

maxdb_real_connect

maxdb->real_connect

(PECL maxdb >= 1.0)

maxdb_real_connect -- maxdb->real_connect — Opens a connection to a MaxDB server

Description

Procedural style

bool maxdb_real_connect ( resource $link [, string $hostname [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket ]]]]]] )

Object oriented style (method)

maxdb
bool real_connect ([ string $hostname [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket ]]]]]] )

maxdb_real_connect() attempts to establish a connection to a MaxDB database engine running on hostname .

This function differs from maxdb_connect():

  • maxdb_real_connect() needs a valid resource which has to be created by function maxdb_init()

  • With function maxdb_options() you can set various options for connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php

/* create a connection object which is not connected */
$maxdb = maxdb_init();

/* set connection options */
$maxdb->options(MAXDB_UNICODE, "FALSE");
$maxdb->options(MAXDB_TIMEOUT, 5);

/* connect to server */
$maxdb->real_connect('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("Connection: %s\n.", $maxdb->host_info);

$maxdb->close();
?>

Example #2 Procedural style

<?php

/* create a connection object which is not connected */
$link = maxdb_init();

/* set connection options */
maxdb_options($link, MAXDB_UNICODE, "FALSE");
maxdb_options($link, MAXDB_TIMEOUT, 5);

/* connect to server */
maxdb_real_connect($link, 'localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("Connection: %s\n.", maxdb_get_host_info($link));

maxdb_close($link);
?>

The above example will output something similar to:

Connection: localhost <...>

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_options() - Set options
  • maxdb_ssl_set() - Used for establishing secure connections using SSL
  • maxdb_close() - Closes a previously opened database connection

maxdb_query
maxdb_real_escape_string
MaxDB Functions


Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

maxdb_real_connect
maxdb_real_query
MaxDB Functions
PHP Manual

maxdb_real_escape_string

maxdb->real_escape_string

(PECL maxdb >= 1.0)

maxdb_real_escape_string -- maxdb->real_escape_string — Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

Description

Procedural style:

string maxdb_real_escape_string ( resource $link , string $escapestr )

Object oriented style (method):

maxdb
string real_escape_sring ( string $escapestr )

This function is used to create a legal SQL string that you can use in a SQL statement. The string escapestr is encoded to an escaped SQL string, taking into account the current character set of the connection.

Characters encoded are ', ".

Return Values

Returns an escaped string.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$maxdb->query("INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", $maxdb->sqlstate);
}

$city = $maxdb->real_escape_string($city);

/* this query with escaped $city will work */
if ($maxdb->query("INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", $maxdb->affected_rows);
}

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!maxdb_query($link, "INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", maxdb_sqlstate($link));
}

$city = maxdb_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (maxdb_query($link, "INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", maxdb_affected_rows($link));
}

maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -5016 POS(43) Missing delimiter: ) <...>
Error: 42000
1 Row inserted.

See Also

  • maxdb_character_set_name() - Returns the default character set for the database connection

maxdb_real_connect
maxdb_real_query
MaxDB Functions


Execute an SQL query

maxdb_real_escape_string
maxdb_report
MaxDB Functions
PHP Manual

maxdb_real_query

maxdb->real_query

(PECL maxdb >= 1.0)

maxdb_real_query -- maxdb->real_query — Execute an SQL query

Description

Procedural style

bool maxdb_real_query ( resource $link , string $query )

Object oriented style (method):

maxdb
bool real_query ( string $query )

The maxdb_real_query() is functionally identical with the maxdb_query().

Note: In order to determine if a given query should return a result set or not, see maxdb_field_count().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • maxdb_query() - Performs a query on the database
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_real_escape_string
maxdb_report
MaxDB Functions


Enables or disables internal report functions

maxdb_real_query
maxdb_rollback
MaxDB Functions
PHP Manual

maxdb_report

(PECL maxdb 1.0)

maxdb_report — Enables or disables internal report functions

Description

bool maxdb_report ( int $flags )

Parameters

flags

One of the MAXDB_REPORT_XXX constants.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural style

<?php
/* activate reporting */
maxdb_report(MAXDB_REPORT_ERROR);

$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* this query should report an error */
$result = maxdb_query($link,"SELECT Name FROM Nonexistingtable WHERE population > 50000");

maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -4004 POS(18) Unknown table name:NONEXISTINGTABLE <...>
maxdb_real_query
maxdb_rollback
MaxDB Functions


Rolls back current transaction

maxdb_report
maxdb_rpl_parse_enabled
MaxDB Functions
PHP Manual

maxdb_rollback

maxdb->rollback

(PECL maxdb >= 1.0)

maxdb_rollback -- maxdb->rollback — Rolls back current transaction

Description

bool maxdb_rollback ( resource $link )
maxdb
bool rollback ( void )

Rollbacks the current transaction for the database specified by the link parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* disable autocommit */
$maxdb->autocommit(FALSE);

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
$maxdb->commit();

/* delete all rows */
$maxdb->query("DELETE FROM temp.mycity");

if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result->fetch_row();
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   $result->close();
}

/* Rollback */
$maxdb->rollback();

if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result->fetch_row();
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   $result->close();
}

/* Drop table myCity */
$maxdb->query("DROP TABLE temp.mycity");

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* disable autocommit */
maxdb_autocommit($link, FALSE);

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
maxdb_commit($link);

/* delete all rows */
maxdb_query($link, "DELETE FROM temp.mycity");

if ($result = maxdb_query($link, "SELECT COUNT(*) FROM temp.mycity")) {
   $row = maxdb_fetch_row($result);
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   maxdb_free_result($result);
}

/* Rollback */
maxdb_rollback($link);

if ($result = maxdb_query($link, "SELECT COUNT(*) FROM temp.mycity")) {
   $row = maxdb_fetch_row($result);
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   maxdb_free_result($result);
}

/* Drop table myCity */
maxdb_query($link, "DROP TABLE temp.mycity");

maxdb_close($link);
?>

The above example will output something similar to:

0 rows in table mycity.
25 rows in table mycity (after rollback).

See Also

  • maxdb_commit() - Commits the current transaction
  • maxdb_autocommit() - Turns on or off auto-commiting database modifications

maxdb_report
maxdb_rpl_parse_enabled
MaxDB Functions


Check if RPL parse is enabled

maxdb_rollback
maxdb_rpl_probe
MaxDB Functions
PHP Manual

maxdb_rpl_parse_enabled

(PECL maxdb >= 1.0)

maxdb_rpl_parse_enabled — Check if RPL parse is enabled

Description

int maxdb_rpl_parse_enabled ( resource $link )
Warning

This function is currently not documented; only its argument list is available.

maxdb_rollback
maxdb_rpl_probe
MaxDB Functions


RPL probe

maxdb_rpl_parse_enabled
maxdb_rpl_query_type
MaxDB Functions
PHP Manual

maxdb_rpl_probe

(PECL maxdb >= 1.0)

maxdb_rpl_probe — RPL probe

Description

bool maxdb_rpl_probe ( resource $link )
Warning

This function is currently not documented; only its argument list is available.

maxdb_rpl_parse_enabled
maxdb_rpl_query_type
MaxDB Functions


Returns RPL query type

maxdb_rpl_probe
maxdb_select_db
MaxDB Functions
PHP Manual

maxdb_rpl_query_type

maxdb->rpl_query_type

(PECL maxdb >= 1.0)

maxdb_rpl_query_type -- maxdb->rpl_query_type — Returns RPL query type

Description

int maxdb_rpl_query_type ( resource $link )

Object oriented style (method)

maxdb
int rpl_query_type ( void )
Warning

This function is currently not documented; only its argument list is available.

maxdb_rpl_probe
maxdb_select_db
MaxDB Functions


Selects the default database for database queries

maxdb_rpl_query_type
maxdb_send_long_data
MaxDB Functions
PHP Manual

maxdb_select_db

maxdb->select_db

(PECL maxdb >= 1.0)

maxdb_select_db -- maxdb->select_db — Selects the default database for database queries

Description

bool maxdb_select_db ( resource $link , string $dbname )

The maxdb_select_db() function selects the default database (specified by the dbname parameter) to be used when performing queries against the database connection represented by the link parameter.

Note: This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in maxdb_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* return name of current default database */
if ($result = $maxdb->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result->fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result->close();
}

/* change db to non existing db */
$maxdb->select_db("XXXXXXXX");

/* return name of current default database */
if ($result = $maxdb->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result->fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result->close();
}

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* return name of current default database */
if ($result = maxdb_query($link, "SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = maxdb_fetch_row($result);
   printf("Default database is %s.\n", $row[0]);
   maxdb_free_result($result);
}

/* change db to non existing db */
maxdb_select_db($link, "XXXXXXXX");

/* return name of current default database */
if ($result = maxdb_query($link, "SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = maxdb_fetch_row($result);
   printf("Default database is %s.\n", $row[0]);
   maxdb_free_result($result);
}

maxdb_close($link);
?>

The above example will output something similar to:

Default database is <...>.

Warning: maxdb_select_db(): -10709 Connection failed (RTE:database not running) <...>

Warning: maxdb_query(): -10821 Session not connected [] <...>

Warning: maxdb_close(): -10821 Session not connected [] <...>

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_real_connect() - Opens a connection to a MaxDB server

maxdb_rpl_query_type
maxdb_send_long_data
MaxDB Functions


Alias of maxdb_stmt_send_long_data

maxdb_select_db
maxdb_send_query
MaxDB Functions
PHP Manual

maxdb_send_long_data

(PECL maxdb >= 1.0)

maxdb_send_long_data — Alias of maxdb_stmt_send_long_data()

Description

This function is an alias of: maxdb_stmt_send_long_data().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.

maxdb_select_db
maxdb_send_query
MaxDB Functions


Send the query and return

maxdb_send_long_data
maxdb_server_end
MaxDB Functions
PHP Manual

maxdb_send_query

maxdb->send_query

(PECL maxdb >= 1.0)

maxdb_send_query -- maxdb->send_query — Send the query and return

Description

bool maxdb_send_query ( resource $link , string $query )

Object oriented style (method)

maxdb
bool send_query ( string $query )
Warning

This function is currently not documented; only its argument list is available.

maxdb_send_long_data
maxdb_server_end
MaxDB Functions


Shut down the embedded server

maxdb_send_query
maxdb_server_init
MaxDB Functions
PHP Manual

maxdb_server_end

(PECL maxdb >= 1.0)

maxdb_server_end — Shut down the embedded server

Description

void maxdb_server_end ( void )
Warning

This function is currently not documented; only its argument list is available.

maxdb_send_query
maxdb_server_init
MaxDB Functions


Initialize embedded server

maxdb_server_end
maxdb_set_opt
MaxDB Functions
PHP Manual

maxdb_server_init

(PECL maxdb >= 1.0)

maxdb_server_init — Initialize embedded server

Description

bool maxdb_server_init ([ array $server [, array $groups ]] )
Warning

This function is currently not documented; only its argument list is available.

maxdb_server_end
maxdb_set_opt
MaxDB Functions


Alias of maxdb_options

maxdb_server_init
maxdb_sqlstate
MaxDB Functions
PHP Manual

maxdb_set_opt

(PECL maxdb 1.0)

maxdb_set_opt — Alias of maxdb_options()

Description

This function is an alias of: maxdb_options().

maxdb_server_init
maxdb_sqlstate
MaxDB Functions


Returns the SQLSTATE error from previous MaxDB operation

maxdb_set_opt
maxdb_ssl_set
MaxDB Functions
PHP Manual

maxdb_sqlstate

maxdb->sqlstate

(PECL maxdb >= 1.0)

maxdb_sqlstate -- maxdb->sqlstate — Returns the SQLSTATE error from previous MaxDB operation

Description

Procedural style:

string maxdb_sqlstate ( resource $link )

Object oriented style (property):

maxdb
string $sqlstate;

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.

Note: Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Return Values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Table City already exists, so we should get an error */
if (!$maxdb->query("CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", $maxdb->sqlstate);
}

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Table City already exists, so we should get an error */
if (!maxdb_query($link, "CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", maxdb_sqlstate($link));
}

maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -6000 POS(20) Duplicate table name:CITY [I6000] <...>
Error - SQLSTATE I6000.

See Also

  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error

maxdb_set_opt
maxdb_ssl_set
MaxDB Functions


Used for establishing secure connections using SSL

maxdb_sqlstate
maxdb_stat
MaxDB Functions
PHP Manual

maxdb_ssl_set

maxdb->ssl_set

(PECL maxdb >= 1.0)

maxdb_ssl_set -- maxdb->ssl_set — Used for establishing secure connections using SSL

Description

Procedural style:

bool maxdb_ssl_set ( resource $link , string $key , string $cert , string $ca , string $capath , string $cipher )

Object oriented style (method):

maxdb
bool ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )
Warning

This function is currently not documented; only its argument list is available.

maxdb_sqlstate
maxdb_stat
MaxDB Functions


Gets the current system status

maxdb_ssl_set
maxdb_stmt_affected_rows
MaxDB Functions
PHP Manual

maxdb_stat

maxdb->stat

(PECL maxdb >= 1.0)

maxdb_stat -- maxdb->stat — Gets the current system status

Description

Procedural style:

string maxdb_stat ( resource $link )

Object oriented style (method):

maxdb
string maxdb->stat ( void )

maxdb_stat() returns a string containing several information about the MaxDB server running.

Return Values

A string describing the server status. FALSE if an error occurred.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("System status: %s\n", $maxdb->stat());

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("System status: %s\n", maxdb_stat($link));

maxdb_close($link);
?>

The above example will output something similar to:

System status: Kernel    7<...>

See Also

  • maxdb_get_server_info() - Returns the version of the MaxDB server

maxdb_ssl_set
maxdb_stmt_affected_rows
MaxDB Functions


Returns the total number of rows changed, deleted, or inserted by the last executed statement

maxdb_stat
maxdb_stmt_bind_param
MaxDB Functions
PHP Manual

maxdb_stmt_affected_rows

maxdb_stmt->affected_rows

(PECL maxdb >= 1.0)

maxdb_stmt_affected_rows -- maxdb_stmt->affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement

Description

Procedural style :

int maxdb_stmt_affected_rows ( resource $stmt )

Object oriented style (property):

stmt
int $affected_rows;

maxdb_stmt_affected_rows() returns the number of rows affected by INSERT, UPDATE, or DELETE query. If the last query was invalid or the number of rows can not determined, this function will return -1.

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error or the number of rows can not determined.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* create temp table */
$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";

/* prepare statement */
if ($stmt = $maxdb->prepare($query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   $stmt->bind_param("s", $code);

   /* execute statement */
   $stmt->execute();

   printf("rows inserted: %d\n", $stmt->affected_rows);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* create temp table */
maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";

/* prepare statement */
if ($stmt = maxdb_prepare($link, $query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   maxdb_stmt_bind_param($stmt, "s", $code);

   /* execute statement */
   maxdb_stmt_execute($stmt);

   printf("rows inserted: %d\n", maxdb_stmt_affected_rows($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

rows inserted: 4

See Also

  • maxdb_stmt_num_rows() - Return the number of rows in statements result set
  • maxdb_prepare() - Prepare a SQL statement for execution

maxdb_stat
maxdb_stmt_bind_param
MaxDB Functions


Binds variables to a prepared statement as parameters

maxdb_stmt_affected_rows
maxdb_stmt_bind_result
MaxDB Functions
PHP Manual

maxdb_stmt_bind_param

stmt->bind_param

(PECL maxdb >= 1.0)

maxdb_stmt_bind_param -- stmt->bind_param — Binds variables to a prepared statement as parameters

Description

Procedural style:

bool maxdb_stmt_bind_param ( resource $stmt , string $types , mixed &$var1 [, mixed &$... ] )

Object oriented style (method):

stmt
bool bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

Procedural style (extended syntax):

bool maxdb_stmt_bind_param ( resource $stmt , string $types , array &$var )

Object oriented style (method) (extended syntax):

stmt
bool bind_param ( string $types , array &$var )

maxdb_stmt_bind_param() is used to bind variables for the parameter markers in the SQL statement that was passed to maxdb_prepare(). The string types contains one or more characters which specify the types for the corresponding bind variables.

The extended syntax of maxdb_stmt_bind_param() allows to give the parameters as an array instead of a variable list of PHP variables to the function. If the array variable has not been used before calling maxdb_stmt_bind_param(), it has to be initialized as an emtpy array. See the examples how to use maxdb_stmt_bind_param() with extended syntax.

Variables for SELECT INTO SQL statements can also be bound using maxdb_stmt_bind_param(). Parameters for database procedures can be bound using maxdb_stmt_bind_param(). See the examples how to use maxdb_stmt_bind_param() in this cases.

If a variable bound as INTO variable to a SQL statement was used before, the content of this variable is overwritten by the data of the SELECT INTO statement. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().

For INOUT parameters of database procedures the content of the bound INOUT variable is overwritten by the output value of the database procedure. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().

Type specification chars
Character | Description
i | corresponding variable has type integer
d | corresponding variable has type double
s | corresponding variable has type string
b | corresponding variable is a blob and will be sent in packages

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");
$stmt->bind_param('sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", $maxdb->affected_rows);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query ($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query ($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = maxdb_prepare($link, "INSERT INTO temp.mycity VALUES (?, ?, ?)");
maxdb_stmt_bind_param($stmt, 'sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
maxdb_stmt_execute($stmt);

printf("%d Row inserted.\n", maxdb_stmt_affected_rows($stmt));

/* close statement and connection */
maxdb_stmt_close($stmt);

/* Clean up table CountryLanguage */
maxdb_query($link, "DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", maxdb_affected_rows($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

1 Row inserted.
1 Row deleted.

Example #3 Procedural style (SELECT INTO)

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "SELECT price INTO ? FROM hotel.room where hno = ? and type = ?");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

$hno = "50";
$rtype = "suite";

maxdb_stmt_bind_param($stmt, 'dss', $price, $hno, $rtype);
maxdb_stmt_execute($stmt);

printf ("%f\n", $price);

maxdb_stmt_close ($stmt);
?>

The above example will output something similar to:

21.600000

Example #4 Procedural style (DB procedure)

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP DBPROC test_proc");
maxdb_report (MAXDB_REPORT_ERROR);

$query = "create dbproc test_proc (INOUT e_text char(72)) AS select * from SYSDBA.DUAL; fetch into :e_text;";

maxdb_query($link, $query);

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "CALL test_proc (?)");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

maxdb_stmt_bind_param($stmt, 's', $result);
maxdb_stmt_execute($stmt);

printf ("%s\n", $result);

maxdb_stmt_close ($stmt);
?>

The above example will output something similar to:

a

Example #5 Object oriented style (extended syntax)

<?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");

$arr = array();

$stmt->bind_param('iss', $arr);

$arr[0] = 11111;
$arr[1] = 'Georgetown';
$arr[2] = 'NY';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", maxdb_stmt_affected_rows($stmt));

$arr[0] = 22222;
$arr[1] = 'New Orleans';
$arr[2] = 'LA';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

$result = $maxdb->query("SELECT * from temp.mycity WHERE zip = '11111' OR zip = '22222'");
if ($result) {
  while ($row = $result->fetch_row()) {
    printf ("%s %s %s\n", $row[0], $row[1], $row[2]);
  }
}

/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
$maxdb->query("DELETE FROM temp.mycity WHERE name='New Orleans'");
printf("%d Rows deleted.\n", $maxdb->affected_rows);

/* close connection */
$maxdb->close();
?>

The above example will output something similar to:

1 Row inserted.
1 Row inserted.
11111 Georgetown NY
22222 New Orleans LA
2 Rows deleted.

See Also

  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_prepare() - Prepare a SQL statement for execution
  • maxdb_stmt_send_long_data() - Send data in blocks
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error

maxdb_stmt_affected_rows
maxdb_stmt_bind_result
MaxDB Functions


Binds variables to a prepared statement for result storage

maxdb_stmt_bind_param
maxdb_stmt_close_long_data
MaxDB Functions
PHP Manual

maxdb_stmt_bind_result

stmt->bind_result

(PECL maxdb >= 1.0)

maxdb_stmt_bind_result -- stmt->bind_result — Binds variables to a prepared statement for result storage

Description

Procedural style:

bool maxdb_stmt_bind_result ( resource $stmt , mixed &$var1 [, mixed &$... ] )

Object oriented style (method):

stmt
bool bind_result ( mixed &$var1 [, mixed &$... ] )

maxdb_stmt_bind_result() is used to associate (bind) columns in the result set to variables. When maxdb_stmt_fetch() is called to fetch data, the MaxDB client/server protocol places the data for the bound columns into the specified variables var1, ... .

Note: Note that all columns must be bound prior to calling maxdb_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.
A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time maxdb_stmt_fetch() is called.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* prepare statement */
if ($stmt = $maxdb->prepare("SELECT zip, name FROM hotel.city ORDER BY name")) {
   $stmt->execute();

   /* bind variables to prepared statement */
   $stmt->bind_result($col1, $col2);

   /* fetch values */
   while ($stmt->fetch()) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   $stmt->close();
}
/* close connection */
$maxdb->close();

?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* prepare statement */
if ($stmt = maxdb_prepare($link, "SELECT zip, name FROM hotel.city ORDER BY name")) {
   maxdb_stmt_execute($stmt);

   /* bind variables to prepared statement */
   maxdb_stmt_bind_result($stmt, $col1, $col2);

   /* fetch values */
   while (maxdb_stmt_fetch($stmt)) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

12203 Albany
60601 Chicago
60615 Chicago
45211 Cincinnati
33575 Clearwater
75243 Dallas
32018 Daytona Beach
33441 Deerfield Beach
48226 Detroit
90029 Hollywood
92714 Irvine
90804 Long Beach
11788 Long Island
90018 Los Angeles
70112 New Orleans
10019 New York
10580 New York
92262 Palm Springs
97213 Portland
60018 Rosemont
95054 Santa Clara
20903 Silver Spring
20005 Washington
20019 Washington
20037 Washington

See Also

  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_prepare() - Prepare a SQL statement for execution
  • maxdb_stmt_prepare() - Prepare a SQL statement for execution
  • maxdb_stmt_init() - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error

maxdb_stmt_bind_param
maxdb_stmt_close_long_data
MaxDB Functions


Closes a prepared statement

maxdb_stmt_close_long_data
maxdb_stmt_data_seek
MaxDB Functions
PHP Manual

maxdb_stmt_close

maxdb_stmt->close

(PECL maxdb >= 1.0)

maxdb_stmt_close -- maxdb_stmt->close — Closes a prepared statement

Description

Procedural style:

bool maxdb_stmt_close ( resource $stmt )

Object oriented style (method):

maxdb_stmt
bool maxdb_stmt->close ( void )

Closes a prepared statement. maxdb_stmt_close() also deallocates the statement handle pointed to by stmt . If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • maxdb_prepare() - Prepare a SQL statement for execution

maxdb_stmt_close_long_data
maxdb_stmt_data_seek
MaxDB Functions


Ends a sequence of maxdb_stmt_send_long_data

maxdb_stmt_bind_result
maxdb_stmt_close
MaxDB Functions
PHP Manual

maxdb_stmt_close_long_data

stmt->close_long_data

(PECL maxdb 1.0)

maxdb_stmt_close_long_data -- stmt->close_long_data — Ends a sequence of maxdb_stmt_send_long_data()

Description

Procedural style:

bool maxdb_stmt_close_long_data ( resource $stmt , int $param_nr )

Object oriented style (method):

maxdb_stmt
bool maxdb_stmt->close_long_data ( void )

This function has to be called after a sequence of maxdb_stmt_send_long_data(), that was started after maxdb_execute().

param_nr indicates which parameter to associate the end of data with. Parameters are numbered beginning with 0.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • maxdb_prepare() - Prepare a SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters

maxdb_stmt_bind_result
maxdb_stmt_close
MaxDB Functions


Seeks to an arbitray row in statement result set

maxdb_stmt_close
maxdb_stmt_errno
MaxDB Functions
PHP Manual

maxdb_stmt_data_seek

stmt->data_seek

(PECL maxdb >= 1.0)

maxdb_stmt_data_seek -- stmt->data_seek — Seeks to an arbitray row in statement result set

Description

Procedural style:

bool maxdb_stmt_data_seek ( resource $statement , int $offset )

Object oriented style (method):

stmt
bool data_seek ( int $offset )

The maxdb_stmt_data_seek() function seeks to an arbitrary result pointer specified by the offset in the statement result set represented by statement . The offset parameter must be between zero and the total number of rows minus one (0..maxdb_stmt_num_rows() - 1).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($name, $code);

   /* store result */
   $stmt->store_result();

   /* seek to row no. 5 */
   $stmt->data_seek(5);

   /* fetch values */
   $stmt->fetch();

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $name, $code);

   /* store result */
   maxdb_stmt_store_result($stmt);

   /* seek to row no. 5 */
   maxdb_stmt_data_seek($stmt, 5);

   /* fetch values */
   maxdb_stmt_fetch($stmt);

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

City: Dallas  Zip: 75243

See Also

  • maxdb_prepare() - Prepare a SQL statement for execution

maxdb_stmt_close
maxdb_stmt_errno
MaxDB Functions


Returns the error code for the most recent statement call

maxdb_stmt_data_seek
maxdb_stmt_error
MaxDB Functions
PHP Manual

maxdb_stmt_errno

maxdb_stmt->errno

(PECL maxdb >= 1.0)

maxdb_stmt_errno -- maxdb_stmt->errno — Returns the error code for the most recent statement call

Description

Procedural style :

int maxdb_stmt_errno ( resource $stmt )

Object oriented style (property):

stmt
int $errno;

For the statement specified by stmt, maxdb_stmt_errno() returns the error code for the most recently invoked statement function that can succeed or fail.

Note: For possible error codes see documentation of SQLDBC: » http://maxdb.sap.com/documentation/.

Return Values

An error code value. Zero means no error occurred.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %d.\n", $stmt->errno);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %d.\n", maxdb_stmt_errno($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: -4004.

See Also

  • maxdb_stmt_error() - Returns a string description for last statement error
  • maxdb_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

maxdb_stmt_data_seek
maxdb_stmt_error
MaxDB Functions


Returns a string description for last statement error

maxdb_stmt_errno
maxdb_stmt_execute
MaxDB Functions
PHP Manual

maxdb_stmt_error

maxdb_stmt->error

(PECL maxdb >= 1.0)

maxdb_stmt_error -- maxdb_stmt->error — Returns a string description for last statement error

Description

Procedural style:

string maxdb_stmt_error ( resource $stmt )

Object oriented style (property):

stmt
string $error;

For the statement specified by stmt, maxdb_stmt_error() returns a containing the error message for the most recently invoked statement function that can succeed or fail.

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %s.\n", $stmt->error);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %s.\n", maxdb_stmt_error($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: POS(23) Unknown table name:MYCITY.

See Also

  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

maxdb_stmt_errno
maxdb_stmt_execute
MaxDB Functions


Executes a prepared Query

maxdb_stmt_error
maxdb_stmt_fetch
MaxDB Functions
PHP Manual

maxdb_stmt_execute

stmt->execute

(PECL maxdb >= 1.0)

maxdb_stmt_execute -- stmt->execute — Executes a prepared Query

Description

Procedural style:

bool maxdb_stmt_execute ( resource $stmt )

Object oriented style (method):

stmt
bool execute ( void )

The maxdb_stmt_execute() function executes a query that has been previously prepared using the maxdb_prepare() function represented by the stmt resource. When executed any parameter markers which exist will automatically be replaced with the appropiate data.

If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the maxdb_stmt_affected_rows() function. Likewise, if the query yields a result set the maxdb_fetch() function is used.

Note: When using maxdb_stmt_execute(), the maxdb_fetch() function must be used to fetch the data prior to preforming any additional queries.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = $maxdb->prepare($query);

$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';

/* Execute the statement */
$stmt->execute();

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';

/* Execute the statement */
$stmt->execute();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = $maxdb->query($query)) {
   while ($row = $result->fetch_row()) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   $result->close();
}

/* remove table */
$maxdb->query("DROP TABLE temp.mycity");

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = maxdb_prepare($link, $query);

maxdb_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';

/* Execute the statement */
maxdb_stmt_execute($stmt);

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';

/* Execute the statement */
maxdb_stmt_execute($stmt);

/* close statement */
maxdb_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = maxdb_query($link, $query)) {
   while ($row = maxdb_fetch_row($result)) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   maxdb_free_result($result);
}

/* remove table */
maxdb_query($link, "DROP TABLE temp.mycity");

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

11111 (Georgetown,NY)
22222 (Hubbatown,CA)

See Also

  • maxdb_prepare() - Prepare a SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters

maxdb_stmt_error
maxdb_stmt_fetch
MaxDB Functions


Fetch results from a prepared statement into the bound variables

maxdb_stmt_execute
maxdb_stmt_free_result
MaxDB Functions
PHP Manual

maxdb_stmt_fetch

stmt->fetch

(PECL maxdb >= 1.0)

maxdb_stmt_fetch -- stmt->fetch — Fetch results from a prepared statement into the bound variables

Description

Procedural style:

bool maxdb_stmt_fetch ( resource $stmt )

Object oriented style (method):

stmt
bool fetch ( void )

maxdb_stmt_fetch() returns row data using the variables bound by maxdb_stmt_bind_result().

Note: Note that all columns must be bound by the application before calling maxdb_stmt_fetch().

Return Values

Return values
Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occured
NULL | No more rows/data exists

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER by name";

if ($stmt = $maxdb->prepare($query)) {

   /* execute statement */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($name, $code);

   /* fetch values */
   while ($stmt->fetch()) {
       printf ("%s (%s)\n", $name, $code);
   }

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER by name";

if ($stmt = maxdb_prepare($link, $query)) {

   /* execute statement */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $name, $code);

   /* fetch values */
   while (maxdb_stmt_fetch($stmt)) {
       printf ("%s (%s)\n", $name, $code);
   }

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

12203 (Albany)
60601 (Chicago)
60615 (Chicago)
45211 (Cincinnati)
33575 (Clearwater)
75243 (Dallas)
32018 (Daytona Beach)
33441 (Deerfield Beach)
48226 (Detroit)
90029 (Hollywood)
92714 (Irvine)
90804 (Long Beach)
11788 (Long Island)
90018 (Los Angeles)
70112 (New Orleans)
10019 (New York)
10580 (New York)
92262 (Palm Springs)
97213 (Portland)
60018 (Rosemont)
95054 (Santa Clara)
20903 (Silver Spring)
20005 (Washington)
20019 (Washington)
20037 (Washington)

See Also

  • maxdb_prepare() - Prepare a SQL statement for execution
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error
  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage

maxdb_stmt_execute
maxdb_stmt_free_result
MaxDB Functions


Frees stored result memory for the given statement handle

maxdb_stmt_fetch
maxdb_stmt_init
MaxDB Functions
PHP Manual

maxdb_stmt_free_result

stmt->free_result

(PECL maxdb >= 1.0)

maxdb_stmt_free_result -- stmt->free_result — Frees stored result memory for the given statement handle

Description

Procedural style:

void maxdb_stmt_free_result ( resource $stmt )

Object oriented style (method):

stmt
void free_result ( void )

The maxdb_stmt_free_result() function frees the result memory associated with the statement represented by the stmt parameter, which was allocated by maxdb_stmt_store_result().

Return Values

This function doesn't return any value.

See Also

  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement

maxdb_stmt_fetch
maxdb_stmt_init
MaxDB Functions


Initializes a statement and returns an resource for use with maxdb_stmt_prepare

maxdb_stmt_free_result
maxdb_stmt_num_rows
MaxDB Functions
PHP Manual

maxdb_stmt_init

maxdb->stmt_init

(PECL maxdb >= 1.0)

maxdb_stmt_init -- maxdb->stmt_init — Initializes a statement and returns an resource for use with maxdb_stmt_prepare

Description

Procedural style :

resource maxdb_stmt_init ( resource $link )

Object oriented style (property):

maxdb
object stmt_init ( void )

Allocates and initializes a statement resource suitable for maxdb_stmt_prepare().

Note: Any subsequent calls to any maxdb_stmt function will fail until maxdb_stmt_prepare() was called.

Return Values

Returns an resource.

See Also

  • maxdb_stmt_prepare() - Prepare a SQL statement for execution

maxdb_stmt_free_result
maxdb_stmt_num_rows
MaxDB Functions


Return the number of rows in statements result set

maxdb_stmt_init
maxdb_stmt_param_count
MaxDB Functions
PHP Manual

maxdb_stmt_num_rows

stmt->num_rows

(PECL maxdb >= 1.0)

maxdb_stmt_num_rows -- stmt->num_rows — Return the number of rows in statements result set

Description

Procedural style :

int maxdb_stmt_num_rows ( resource $stmt )

Object oriented style (property):

stmt
int $num_rows;

Returns the number of rows in the result set.

Return Values

An integer representing the number of rows in result set.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* store result */
   $stmt->store_result();

   printf("Number of rows: %d.\n", $stmt->num_rows);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* store result */
   maxdb_stmt_store_result($stmt);

   printf("Number of rows: %d.\n", maxdb_stmt_num_rows($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Number of rows: 25.

See Also

  • maxdb_stmt_affected_rows() - Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • maxdb_prepare() - Prepare a SQL statement for execution
  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement

maxdb_stmt_init
maxdb_stmt_param_count
MaxDB Functions


Returns the number of parameter for the given statement

maxdb_stmt_num_rows
maxdb_stmt_prepare
MaxDB Functions
PHP Manual

maxdb_stmt_param_count

stmt->param_count

(PECL maxdb >= 1.0)

maxdb_stmt_param_count -- stmt->param_count — Returns the number of parameter for the given statement

Description

Procedural style:

int maxdb_stmt_param_count ( resource $stmt )

Object oriented style (property):

stmt
int $param_count;

maxdb_stmt_param_count() returns the number of parameter markers present in the prepared statement.

Return Values

returns an integer representing the number of parameters.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($stmt = $maxdb->prepare("SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = $stmt->param_count;
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($stmt = maxdb_prepare($link, "SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = maxdb_stmt_param_count($stmt);
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Statement has 2 markers.

See Also

  • maxdb_prepare() - Prepare a SQL statement for execution

maxdb_stmt_num_rows
maxdb_stmt_prepare
MaxDB Functions


Prepare a SQL statement for execution

maxdb_stmt_param_count
maxdb_stmt_reset
MaxDB Functions
PHP Manual

maxdb_stmt_prepare

stmt->prepare

(PECL maxdb >= 1.0)

maxdb_stmt_prepare -- stmt->prepare — Prepare a SQL statement for execution

Description

Procedure style:

bool maxdb_stmt_prepare ( resource $stmt , string $query )

Object oriented style (method)

stmt
mixed prepare ( string $query )

maxdb_stmt_prepare() prepares the SQL query pointed to by the null-terminated string query. The statement resource has to be allocated by maxdb_stmt_init(). The query must consist of a single SQL statement.

Note: You should not add a terminating semicolon or \g to the statement.

The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Portland";

/* create a prepared statement */
$stmt =  $maxdb->stmt_init();
if ($stmt->prepare("SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   $stmt->bind_param("s", $city);

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($district);

   /* fetch value */
   $stmt->fetch();

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Portland";

/* create a prepared statement */
$stmt = maxdb_stmt_init($link);
if (maxdb_stmt_prepare($stmt, "SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   maxdb_stmt_bind_param($stmt, "s", $city);

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $district);

   /* fetch value */
   maxdb_stmt_fetch($stmt);

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Portland is in district OR

See Also

  • maxdb_stmt_init() - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • maxdb_stmt_close() - Closes a prepared statement

maxdb_stmt_param_count
maxdb_stmt_reset
MaxDB Functions


Resets a prepared statement

maxdb_stmt_prepare
maxdb_stmt_result_metadata
MaxDB Functions
PHP Manual

maxdb_stmt_reset

stmt->reset

(PECL maxdb >= 1.0)

maxdb_stmt_reset -- stmt->reset — Resets a prepared statement

Description

Procedural style:

bool maxdb_stmt_reset ( resource $stmt )

Object oriented style (method):

stmt
bool reset ( void )
Warning

This function is currently not documented; only its argument list is available.

maxdb_stmt_prepare
maxdb_stmt_result_metadata
MaxDB Functions


Returns result set metadata from a prepared statement

maxdb_stmt_reset
maxdb_stmt_send_long_data
MaxDB Functions
PHP Manual

maxdb_stmt_result_metadata

(PECL maxdb >= 1.0)

maxdb_stmt_result_metadata — Returns result set metadata from a prepared statement

Description

Procedural style:

resource maxdb_stmt_result_metadata ( resource $stmt )

Object oriented style (method):

stmt
resource result_metadata ( void )

If a statement passed to maxdb_prepare() is one that produces a result set, maxdb_stmt_result_metadata() returns the result resource that can be used to process the meta information such as total number of fields and individual field information.

Note: This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:

  • maxdb_num_fields()

  • maxdb_fetch_field()

  • maxdb_fetch_field_direct()

  • maxdb_fetch_fields()

  • maxdb_field_count()

  • maxdb_field_seek()

  • maxdb_field_tell()

  • maxdb_free_result()

The result set structure should be freed when you are done with it, which you can do by passing it to maxdb_free_result()

Note: The result set returned by maxdb_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with maxdb_fetch().

Return Values

maxdb_stmt_result_metadata() returns a result resource or FALSE if an error occured.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

$maxdb->query("CREATE TABLE temp.friends (id int, name varchar(20))");

$maxdb->query("INSERT INTO temp.friends VALUES (1,'Hartmut')");
$maxdb->query("INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = $maxdb->prepare("SELECT id, name FROM temp.friends");
$stmt->execute();

/* get resultset for metadata */
$result = $stmt->result_metadata();

/* retrieve field information from metadata result set */
$field = $result->fetch_field();

printf("Fieldname: %s\n", $field->name);

/* close resultset */
$result->close();

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

maxdb_query($link, "CREATE TABLE temp.friends (id int, name varchar(20))");

maxdb_query($link, "INSERT INTO temp.friends VALUES (1,'Hartmut')");
maxdb_query($link, "INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = maxdb_prepare($link, "SELECT id, name FROM temp.friends");
maxdb_stmt_execute($stmt);

/* get resultset for metadata */
$result = maxdb_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = maxdb_fetch_field($result);

printf("Fieldname: %s\n", $field->name);

/* close resultset */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Fieldname: ID

See Also

  • maxdb_prepare() - Prepare a SQL statement for execution
  • maxdb_free_result() - Frees the memory associated with a result

maxdb_stmt_reset
maxdb_stmt_send_long_data
MaxDB Functions


Send data in blocks

maxdb_stmt_result_metadata
maxdb_stmt_sqlstate
MaxDB Functions
PHP Manual

maxdb_stmt_send_long_data

stmt->send_long_data

(PECL maxdb 1.0)

maxdb_stmt_send_long_data -- stmt->send_long_data — Send data in blocks

Description

Procedural style:

bool maxdb_stmt_send_long_data ( resource $stmt , int $param_nr , string $data )

Object oriented style (method)

stmt
bool stmt_send_long_data ( int $param_nr , string $data )

Allows to send parameter data to the server in pieces (or chunks). This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.

param_nr indicates which parameter to associate the data with. Parameters are numbered beginning with 0. data is a string containing data to be sent.

Note: For efficiency reasons, this function should be used after calling maxdb_execute(). In this case, the data is not stored on the client side. The end of the sequence must end with a call to maxdb_stmt_close_long_data().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • maxdb_prepare() - Prepare a SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters

maxdb_stmt_result_metadata
maxdb_stmt_sqlstate
MaxDB Functions


Returns SQLSTATE error from previous statement operation

maxdb_stmt_send_long_data
maxdb_stmt_store_result
MaxDB Functions
PHP Manual

maxdb_stmt_sqlstate

(PECL maxdb >= 1.0)

maxdb_stmt_sqlstate — Returns SQLSTATE error from previous statement operation

Description

string maxdb_stmt_sqlstate ( resource $stmt )

Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.

Note: Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Return Values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %s.\n", $stmt->sqlstate);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %s.\n", maxdb_stmt_sqlstate($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: 42000.

See Also

  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error

maxdb_stmt_send_long_data
maxdb_stmt_store_result
MaxDB Functions


Transfers a result set from a prepared statement

maxdb_stmt_sqlstate
maxdb_store_result
MaxDB Functions
PHP Manual

maxdb_stmt_store_result

maxdb->store_result

(PECL maxdb >= 1.0)

maxdb_stmt_store_result -- maxdb->store_result — Transfers a result set from a prepared statement

Description

Procedural style:

bool maxdb_stmt_store_result ( resource $stmt )

Object oriented style (method):

maxdb
object store_result ( void )

maxdb_stmt_store_result() has no functionally effect and should not be used for retrieving data from MaxDB server.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* store result */
   $stmt->store_result();

   printf("Number of rows: %d.\n", $stmt->num_rows);

   /* free result */
   $stmt->free_result();

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* store result */
   maxdb_stmt_store_result($stmt);

   printf("Number of rows: %d.\n", maxdb_stmt_num_rows($stmt));

   /* free result */
   maxdb_stmt_free_result($stmt);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Number of rows: 25.

See Also

  • maxdb_prepare() - Prepare a SQL statement for execution
  • maxdb_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • maxdb_fetch() - Alias of maxdb_stmt_fetch

maxdb_stmt_sqlstate
maxdb_store_result
MaxDB Functions


Transfers a result set from the last query

maxdb_stmt_store_result
maxdb_thread_id
MaxDB Functions
PHP Manual

maxdb_store_result

maxdb->store_result

(PECL maxdb >= 1.0)

maxdb_store_result -- maxdb->store_result — Transfers a result set from the last query

Description

Procedural style:

resource maxdb_store_result ( resource $link )

Object oriented style (method):

maxdb
object store_result ( void )

This function has no functionally effect.

Return Values

Returns a result resource or FALSE if an error occurred.

Examples

See maxdb_multi_query().

See Also

  • maxdb_real_query() - Execute an SQL query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_stmt_store_result
maxdb_thread_id
MaxDB Functions


Returns the thread ID for the current connection

maxdb_store_result
maxdb_thread_safe
MaxDB Functions
PHP Manual

maxdb_thread_id

maxdb->thread_id

(PECL maxdb >= 1.0)

maxdb_thread_id -- maxdb->thread_id — Returns the thread ID for the current connection

Description

Procedural style:

int maxdb_thread_id ( resource $link )

Object oriented style (property):

maxdb
int $thread_id;

The maxdb_thread_id() function returns the thread ID for the current connection which can then be killed using the maxdb_kill() function. If the connection is lost and you reconnect with maxdb_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.

Note: The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.

Return Values

maxdb_thread_id() returns the Thread ID for the current connection.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = $maxdb->thread_id;

/* Kill connection */
$maxdb->kill($thread_id);

/* This should produce an error */
if (!$maxdb->query("CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", $maxdb->error);
   exit;
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = maxdb_thread_id($link);

/* Kill connection */
maxdb_kill($link, $thread_id);

/* This should produce an error */
if (!maxdb_query($link, "CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", maxdb_error($link));
   exit;
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -10821 Session not connected <...>
Error: Session not connected

See Also

  • maxdb_kill() - Disconnects from a MaxDB server

maxdb_store_result
maxdb_thread_safe
MaxDB Functions


Returns whether thread safety is given or not

maxdb_thread_id
maxdb_use_result
MaxDB Functions
PHP Manual

maxdb_thread_safe

(PECL maxdb >= 7.6.06.04)

maxdb_thread_safe — Returns whether thread safety is given or not

Description

Procedural style:

bool maxdb_thread_safe ( void )

maxdb_thread_safe() indicates whether the client library is compiled as thread-safe.

Return Values

TRUE if the client library is thread-safe, otherwise FALSE.

maxdb_thread_id
maxdb_use_result
MaxDB Functions


Initiate a result set retrieval

maxdb_thread_safe
maxdb_warning_count
MaxDB Functions
PHP Manual

maxdb_use_result

maxdb->use_result

(PECL maxdb >= 1.0)

maxdb_use_result -- maxdb->use_result — Initiate a result set retrieval

Description

Procedural style:

resource maxdb_use_result ( resource $link )

Object oriented style (method):

maxdb
resource use_result ( void )

maxdb_use_result() has no effect.

Return Values

Returns result or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM DUAL";

/* execute multi query */
if ($maxdb->multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb->use_result()) {
           while ($row = $result->fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result->close();
       }
       /* print divider */
       if ($maxdb->more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb->next_result());
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM DUAL";

/* execute multi query */
if (maxdb_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = maxdb_use_result($link)) {
           while ($row = maxdb_fetch_row($result)) {
               printf("%s\n", $row[0]);
           }
           maxdb_free_result($result);
       }
       /* print divider */
       if (maxdb_more_results($link)) {
           printf("-----------------\n");
       }
   } while (maxdb_next_result($link));
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

a

See Also

  • maxdb_real_query() - Execute an SQL query
  • maxdb_store_result() - Transfers a result set from the last query

maxdb_thread_safe
maxdb_warning_count
MaxDB Functions


Returns the number of warnings from the last query for the given link

maxdb_use_result
Mongo
MaxDB Functions
PHP Manual

maxdb_warning_count

maxdb->warning_count

(PECL maxdb >= 1.0)

maxdb_warning_count -- maxdb->warning_count — Returns the number of warnings from the last query for the given link

Description

Procedural style:

int maxdb_warning_count ( resource $link )

Object oriented style (property):

maxdb
int $warning_count;

maxdb_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.

Return Values

Number of warnings or zero if there are no warnings.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable city in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$maxdb->query($query);

printf ("Number of warning: %d\n", $maxdb->warning_count);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable long city name in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

maxdb_query($link, $query);

printf ("Number of warning: %d\n", maxdb_warning_count($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -8004 POS(62) Constant must be compatible with column type and length <...>
Number of warning: 0

See Also

  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

maxdb_use_result
Mongo
MaxDB Functions


Check if the string is valid for the specified encoding

Multibyte String Functions
mb_convert_case
Multibyte String Functions
PHP Manual

mb_check_encoding

(PHP 4 >= 4.4.3, PHP 5 >= 5.1.3)

mb_check_encoding — Check if the string is valid for the specified encoding

Description

bool mb_check_encoding ([ string $var = NULL [, string $encoding = mb_internal_encoding() ]] )

Checks if the specified byte stream is valid for the specified encoding. It is useful to prevent so-called "Invalid Encoding Attack".

Parameters

var

The byte stream to check. If it is omitted, this function checks all the input from the beginning of the request.

encoding

The expected encoding.

Return Values

Returns TRUE on success or FALSE on failure.

Multibyte String Functions
mb_convert_case
Multibyte String Functions


Perform case folding on a string

mb_check_encoding
mb_convert_encoding
Multibyte String Functions
PHP Manual

mb_convert_case

(PHP 4 >= 4.3.0, PHP 5)

mb_convert_case — Perform case folding on a string

Description

string mb_convert_case ( string $str , int $mode = MB_CASE_UPPER [, string $encoding = mb_internal_encoding() ] )

Performs case folding on a string, converted in the way specified by mode .

Parameters

str

The string being converted.

mode

The mode of the conversion. It can be one of MB_CASE_UPPER, MB_CASE_LOWER, or MB_CASE_TITLE.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

A case folded version of string converted in the way specified by mode .

Unicode

By contrast to the standard case folding functions such as strtolower() and strtoupper(), case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

For more information about the Unicode properties, please see » http://www.unicode.org/unicode/reports/tr21/.

Examples

Example #1 mb_convert_case() example

<?php
$str = "mary had a Little lamb and she loved it so";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // Prints Mary Had A Little Lamb And She Loved It So
?>

See Also

  • mb_strtolower() - Make a string lowercase
  • mb_strtoupper() - Make a string uppercase
  • strtolower() - Make a string lowercase
  • strtoupper() - Make a string uppercase
  • ucfirst() - Make a string's first character uppercase
  • ucwords() - Uppercase the first character of each word in a string

mb_check_encoding
mb_convert_encoding
Multibyte String Functions


Convert character encoding

mb_convert_case
mb_convert_kana
Multibyte String Functions
PHP Manual

mb_convert_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_encoding — Convert character encoding

Description

string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding ] )

Converts the character encoding of string str to to_encoding from optionally from_encoding .

Parameters

str

The string being encoded.

to_encoding

The type of encoding that str is being converted to.

from_encoding

Is specified by character code names before conversion. It is either an array, or a comma separated enumerated list. If from_encoding is not specified, the internal encoding will be used.

"auto" may be used, which expands to "ASCII,JIS,UTF-8,EUC-JP,SJIS".

Return Values

The encoded string.

Examples

Example #1 mb_convert_encoding() example

<?php
/* Convert internal character encoding to SJIS */
$str = mb_convert_encoding($str, "SJIS");

/* Convert EUC-JP to UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");

/* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");
?>

See Also

  • mb_detect_order() - Set/Get character encoding detection order

mb_convert_case
mb_convert_kana
Multibyte String Functions


Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

mb_convert_encoding
mb_convert_variables
Multibyte String Functions
PHP Manual

mb_convert_kana

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

Description

string mb_convert_kana ( string $str [, string $option = "KV" [, string $encoding ]] )

Performs a "han-kaku" - "zen-kaku" conversion for string str . This function is only useful for Japanese.

Parameters

str

The string being converted.

option

The conversion option.

Specify with a combination of following options.

Applicable Conversion Options
Option | Meaning
r | Convert "zen-kaku" alphabets to "han-kaku"
R | Convert "han-kaku" alphabets to "zen-kaku"
n | Convert "zen-kaku" numbers to "han-kaku"
N | Convert "han-kaku" numbers to "zen-kaku"
a | Convert "zen-kaku" alphabets and numbers to "han-kaku"
A | Convert "han-kaku" alphabets and numbers to "zen-kaku" (Characters included in "a", "A" options are U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E)
s | Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020)
S | Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000)
k | Convert "zen-kaku kata-kana" to "han-kaku kata-kana"
K | Convert "han-kaku kata-kana" to "zen-kaku kata-kana"
h | Convert "zen-kaku hira-gana" to "han-kaku kata-kana"
H | Convert "han-kaku kata-kana" to "zen-kaku hira-gana"
c | Convert "zen-kaku kata-kana" to "zen-kaku hira-gana"
C | Convert "zen-kaku hira-gana" to "zen-kaku kata-kana"
V | Collapse voiced sound notation and convert them into a character. Use with "K","H"

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The converted string.

Examples

Example #1 mb_convert_kana() example

<?php
/* Convert all "kana" to "zen-kaku" "kata-kana" */
$str = mb_convert_kana($str, "KVC");

/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana"
   and "zen-kaku" alpha-numeric to "han-kaku" */
$str = mb_convert_kana($str, "KVa");
?>

mb_convert_encoding
mb_convert_variables
Multibyte String Functions


Convert character code in variable(s)

mb_convert_kana
mb_decode_mimeheader
Multibyte String Functions
PHP Manual

mb_convert_variables

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_variables — Convert character code in variable(s)

Description

string mb_convert_variables ( string $to_encoding , mixed $from_encoding , mixed &$vars [, mixed &$... ] )

Converts character encoding of variables vars in encoding from_encoding to encoding to_encoding .

mb_convert_variables() join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object.

Parameters

to_encoding

The encoding that the string is being converted to.

from_encoding

from_encoding is specified as an array or comma separated string, it tries to detect encoding from from-coding . When from_encoding is omitted, detect_order is used.

vars

vars is the reference to the variable being converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.

...

Additional vars .

Return Values

The character encoding before conversion for success, or FALSE for failure.

Examples

Example #1 mb_convert_variables() example

<?php
/* Convert variables $post1, $post2 to internal encoding */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);
?>

mb_convert_kana
mb_decode_mimeheader
Multibyte String Functions


Decode string in MIME header field

mb_convert_variables
mb_decode_numericentity
Multibyte String Functions
PHP Manual

mb_decode_mimeheader

(PHP 4 >= 4.0.6, PHP 5)

mb_decode_mimeheader — Decode string in MIME header field

Description

string mb_decode_mimeheader ( string $str )

Decodes encoded-word string str in MIME header.

Parameters

str

The string being decoded.

Return Values

The decoded string in internal character encoding.

See Also

  • mb_encode_mimeheader() - Encode string for MIME header

mb_convert_variables
mb_decode_numericentity
Multibyte String Functions


Decode HTML numeric string reference to character

mb_decode_mimeheader
mb_detect_encoding
Multibyte String Functions
PHP Manual

mb_decode_numericentity

(PHP 4 >= 4.0.6, PHP 5)

mb_decode_numericentity — Decode HTML numeric string reference to character

Description

string mb_decode_numericentity ( string $str , array $convmap , string $encoding )

Convert numeric string reference of string str in a specified block to character.

Parameters

str

The string being decoded.

convmap

convmap is an array that specifies the code area to convert.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The converted string.

Examples

Example #1 convmap example

$convmap = array (
   int start_code1, int end_code1, int offset1, int mask1,
   int start_code2, int end_code2, int offset2, int mask2,
   ........
   int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN,
// then convert value to numeric string reference.

See Also

  • mb_encode_numericentity() - Encode character to HTML numeric string reference

mb_decode_mimeheader
mb_detect_encoding
Multibyte String Functions


Detect character encoding

mb_decode_numericentity
mb_detect_order
Multibyte String Functions
PHP Manual

mb_detect_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_detect_encoding — Detect character encoding

Description

string mb_detect_encoding ( string $str [, mixed $encoding_list = mb_detect_order() [, bool $strict = false ]] )

Detects character encoding in string str .

Parameters

str

The string being detected.

encoding_list

encoding_list is list of character encoding. Encoding order may be specified by array or comma separated list string.

If encoding_list is omitted, detect_order is used.

strict

strict specifies whether to use the strict encoding detection or not. Default is FALSE.

Return Values

The detected character encoding or FALSE if the encoding cannot be detected from the given string.

Examples

Example #1 mb_detect_encoding() example

<?php
/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
echo mb_detect_encoding($str, "auto");

/* Specify encoding_list character encoding by comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");

/* Use array to specify encoding_list  */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
echo mb_detect_encoding($str, $ary);
?>

See Also

  • mb_detect_order() - Set/Get character encoding detection order

mb_decode_numericentity
mb_detect_order
Multibyte String Functions


Set/Get character encoding detection order

mb_detect_encoding
mb_encode_mimeheader
Multibyte String Functions
PHP Manual

mb_detect_order

(PHP 4 >= 4.0.6, PHP 5)

mb_detect_order — Set/Get character encoding detection order

Description

mixed mb_detect_order ([ mixed $encoding_list ] )

Sets the automatic character encoding detection order to encoding_list .

Parameters

encoding_list

encoding_list is an array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP, SJIS")

If encoding_list is omitted, it returns the current character encoding detection order as array.

This setting affects mb_detect_encoding() and mb_send_mail().

mbstring currently implements the following encoding detection filters. If there is an invalid byte sequence for the following encodings, encoding detection will fail.

UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP

For ISO-8859-*, mbstring always detects as ISO-8859-*.

For UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always.

Example #1 Useless detect order example

; Always detect as ISO-8859-1
detect_order = ISO-8859-1, UTF-8

; Always detect as UTF-8, since ASCII/UTF-7 values are
; valid for UTF-8
detect_order = UTF-8, ASCII, UTF-7

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #2 mb_detect_order() examples

<?php
/* Set detection order by enumerated list */
mb_detect_order("eucjp-win,sjis-win,UTF-8");

/* Set detection order by array */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);

/* Display current detection order */
echo implode(", ", mb_detect_order());
?>

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_http_input() - Detect HTTP input character encoding
  • mb_http_output() - Set/Get HTTP output character encoding
  • mb_send_mail() - Send encoded mail

mb_detect_encoding
mb_encode_mimeheader
Multibyte String Functions


Encode string for MIME header

mb_detect_order
mb_encode_numericentity
Multibyte String Functions
PHP Manual

mb_encode_mimeheader

(PHP 4 >= 4.0.6, PHP 5)

mb_encode_mimeheader — Encode string for MIME header

Description

string mb_encode_mimeheader ( string $str [, string $charset [, string $transfer_encoding [, string $linefeed [, int $indent ]]]] )

Encodes a given string str by the MIME header encoding scheme.

Parameters

str

The string being encoded.

charset

charset specifies the name of the character set in which str is represented in. The default value is determined by the current NLS setting (mbstring.language). mb_internal_encoding() should be set to same encoding.

transfer_encoding

transfer_encoding specifies the scheme of MIME encoding. It should be either "B" (Base64) or "Q" (Quoted-Printable). Falls back to "B" if not given.

linefeed

linefeed specifies the EOL (end-of-line) marker with which mb_encode_mimeheader() performs line-folding (a » RFC term, the act of breaking a line longer than a certain length into multiple lines. The length is currently hard-coded to 74 characters). Falls back to "\r\n" (CRLF) if not given.

indent

Indentation of the first line (number of characters in the header before str ).

Return Values

A converted version of the string represented in ASCII.

Changelog

Version | Description
5.0.0 | The indent parameter was added.

Examples

Example #1 mb_encode_mimeheader() example

<?php
$name = ""; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = mb_encode_mimeheader($name, "UTF-7", "Q") . " <" . $mbox . "@" . $doma . ">";
echo $addr;
?>

Notes

Note: This function isn't designed to break lines at higher-level contextual break points (word boundaries, etc.). This behaviour may clutter up the original string with unexpected spaces.

See Also

  • mb_decode_mimeheader() - Decode string in MIME header field

mb_detect_order
mb_encode_numericentity
Multibyte String Functions


Encode character to HTML numeric string reference

mb_encode_mimeheader
mb_ereg_match
Multibyte String Functions
PHP Manual

mb_encode_numericentity

(PHP 4 >= 4.0.6, PHP 5)

mb_encode_numericentity — Encode character to HTML numeric string reference

Description

string mb_encode_numericentity ( string $str , array $convmap , string $encoding )

Converts specified character codes in string str from HTML numeric character reference to character code.

Parameters

str

The string being encoded.

convmap

convmap is array specifies code area to convert.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The converted string.

Examples

Example #1 convmap example

$convmap = array (
 int start_code1, int end_code1, int offset1, int mask1,
 int start_code2, int end_code2, int offset2, int mask2,
 ........
 int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, then
// it converts value to numeric string reference.

Examples

Example #2 mb_encode_numericentity() example

<?php
/* Convert Left side of ISO-8859-1 to HTML numeric character reference */
$convmap = array(0x80, 0xff, 0, 0xff);
$str = mb_encode_numericentity($str, $convmap, "ISO-8859-1");

/* Convert user defined SJIS-win code in block 95-104 to numeric
   string reference */
$convmap = array(
       0xe000, 0xe03e, 0x1040, 0xffff,
       0xe03f, 0xe0bb, 0x1041, 0xffff,
       0xe0bc, 0xe0fa, 0x1084, 0xffff,
       0xe0fb, 0xe177, 0x1085, 0xffff,
       0xe178, 0xe1b6, 0x10c8, 0xffff,
       0xe1b7, 0xe233, 0x10c9, 0xffff,
       0xe234, 0xe272, 0x110c, 0xffff,
       0xe273, 0xe2ef, 0x110d, 0xffff,
       0xe2f0, 0xe32e, 0x1150, 0xffff,
       0xe32f, 0xe3ab, 0x1151, 0xffff );
$str = mb_encode_numericentity($str, $convmap, "sjis-win");
?>

See Also

  • mb_decode_numericentity() - Decode HTML numeric string reference to character

mb_encode_mimeheader
mb_ereg_match
Multibyte String Functions


Regular expression match with multibyte support

mb_ereg_search
mb_eregi_replace
Multibyte String Functions
PHP Manual

mb_ereg

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg — Regular expression match with multibyte support

Description

int mb_ereg ( string $pattern , string $string [, array $regs ] )

Executes the regular expression match with multibyte support.

Parameters

pattern

The search pattern.

string

The search string.

regs

Contains a substring of the matched string.

Return Values

Executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional regs parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The function returns 1 if it matches with the empty string. If no matches are found or an error happens, FALSE will be returned.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_eregi() - Regular expression match ignoring case with multibyte support

mb_ereg_search
mb_eregi_replace
Multibyte String Functions


Regular expression match for multibyte string

mb_encode_numericentity
mb_ereg_replace
Multibyte String Functions
PHP Manual

mb_ereg_match

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_match — Regular expression match for multibyte string

Description

bool mb_ereg_match ( string $pattern , string $string [, string $option = "msr" ] )

A regular expression match for a multibyte string

Parameters

pattern

The regular expression pattern.

string

The string being evaluated.

option

Return Values

Returns TRUE if string matches the regular expression pattern , FALSE if not.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg() - Regular expression match with multibyte support

mb_encode_numericentity
mb_ereg_replace
Multibyte String Functions


Replace regular expression with multibyte support

mb_ereg_match
mb_ereg_search_getpos
Multibyte String Functions
PHP Manual

mb_ereg_replace

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_replace — Replace regular expression with multibyte support

Description

string mb_ereg_replace ( string $pattern , string $replacement , string $string [, string $option = "msr" ] )

Scans string for matches to pattern , then replaces the matched text with replacement

Parameters

pattern

The regular expression pattern.

Multibyte characters may be used in pattern .

replacement

The replacement text.

string

The string being checked.

option
Matching condition can be set by option parameter. If i is specified for this parameter, the case will be ignored. If x is specified, white space will be ignored. If m is specified, match will be executed in multiline mode and line break will be included in '.'. If p is specified, match will be executed in POSIX mode, line break will be considered as normal character. If e is specified, replacement string will be evaluated as PHP expression.

Return Values

The resultant string on success, or FALSE on error.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

Warning

Never use the e modifier when working on untrusted input. No automatic escaping will happen (as known from preg_replace()). Not taking care of this will most likely create remote code execution vulnerabilities in your application.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_eregi_replace() - Replace regular expression with multibyte support ignoring case

mb_ereg_match
mb_ereg_search_getpos
Multibyte String Functions


Multibyte regular expression match for predefined multibyte string

mb_ereg_search_setpos
mb_ereg
Multibyte String Functions
PHP Manual

mb_ereg_search

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search — Multibyte regular expression match for predefined multibyte string

Description

bool mb_ereg_search ([ string $pattern [, string $option = "ms" ]] )

Performs a multibyte regular expression match for a predefined multibyte string.

Parameters

pattern

The search pattern.

option

The search option.

Return Values

mb_ereg_search() returns TRUE if the multibyte string matches with the regular expression, or FALSE otherwise. The string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_setpos
mb_ereg
Multibyte String Functions


Returns start point for next regular expression match

mb_ereg_replace
mb_ereg_search_getregs
Multibyte String Functions
PHP Manual

mb_ereg_search_getpos

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_getpos — Returns start point for next regular expression match

Description

int mb_ereg_search_getpos ( void )

Returns the start point for the next regular expression match.

Parameters

This function has no parameters.

Return Values

mb_ereg_search_getpos() returns
the point to start regular expression match for
mb_ereg_search(),
mb_ereg_search_pos(),
mb_ereg_search_regs(). The position is
represented by bytes from the head of string.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_setpos() - Set start point of next regular expression match

mb_ereg_replace
mb_ereg_search_getregs
Multibyte String Functions


Retrieve the result from the last multibyte regular expression match

mb_ereg_search_getpos
mb_ereg_search_init
Multibyte String Functions
PHP Manual

mb_ereg_search_getregs

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match

Description

array mb_ereg_search_getregs ( void )

Retrieve the result from the last multibyte regular expression match

Parameters

This function has no parameters.

Return Values

An array including the sub-string of matched part by last mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). If there are some matches, the first element will have the matched sub-string, the second element will have the first part grouped with brackets, the third element will have the second part grouped with brackets, and so on. It returns FALSE on error;

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_getpos
mb_ereg_search_init
Multibyte String Functions


Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_getregs
mb_ereg_search_pos
Multibyte String Functions
PHP Manual

mb_ereg_search_init

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match

Description

bool mb_ereg_search_init ( string $string [, string $pattern [, string $option = "msr" ]] )

mb_ereg_search_init() sets string and pattern for a multibyte regular expression. These values are used for mb_ereg_search(), mb_ereg_search_pos(), and mb_ereg_search_regs().

Parameters

string

The search string.

pattern

The search pattern.

option

The search option.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_regs() - Returns the matched part of a multibyte regular expression

mb_ereg_search_getregs
mb_ereg_search_pos
Multibyte String Functions


Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

mb_ereg_search_init
mb_ereg_search_regs
Multibyte String Functions
PHP Manual

mb_ereg_search_pos

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

Description

array mb_ereg_search_pos ([ string $pattern [, string $option = "ms" ]] )

Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

The string for match is specified by mb_ereg_search_init(). If it is not specified, the previous one will be used.

Parameters

pattern

The search pattern.

option

The search option.

Return Values

An array including the position of a matched part for a multibyte regular expression. The first element of the array will be the beginning of matched part, the second element will be length (bytes) of matched part. It returns FALSE on error.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_init
mb_ereg_search_regs
Multibyte String Functions


Returns the matched part of a multibyte regular expression

mb_ereg_search_pos
mb_ereg_search_setpos
Multibyte String Functions
PHP Manual

mb_ereg_search_regs

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_regs — Returns the matched part of a multibyte regular expression

Description

array mb_ereg_search_regs ([ string $pattern [, string $option = "ms" ]] )

Returns the matched part of a multibyte regular expression.

Parameters

pattern

The search pattern.

option

The search option.

Return Values

mb_ereg_search_regs() executes the multibyte regular expression match, and if there are some matched part, it returns an array including substring of matched part as first element, the first grouped part with brackets as second element, the second grouped part as third element, and so on. It returns FALSE on error.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_pos
mb_ereg_search_setpos
Multibyte String Functions


Set start point of next regular expression match

mb_ereg_search_regs
mb_ereg_search
Multibyte String Functions
PHP Manual

mb_ereg_search_setpos

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_setpos — Set start point of next regular expression match

Description

bool mb_ereg_search_setpos ( int $position )

mb_ereg_search_setpos() sets the starting point of a match for mb_ereg_search().

Parameters

position

The position to set.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_regs
mb_ereg_search
Multibyte String Functions


Regular expression match ignoring case with multibyte support

mb_eregi_replace
mb_get_info
Multibyte String Functions
PHP Manual

mb_eregi

(PHP 4 >= 4.2.0, PHP 5)

mb_eregi — Regular expression match ignoring case with multibyte support

Description

int mb_eregi ( string $pattern , string $string [, array $regs ] )

Executes the case insensitive regular expression match with multibyte support.

Parameters

pattern

The regular expression pattern.

string

The string being searched.

regs

Contains a substring of the matched string.

Return Values

Executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional regs parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The function returns 1 if it matches with the empty string. If no matches are found or an error happens, FALSE will be returned.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg() - Regular expression match with multibyte support

mb_eregi_replace
mb_get_info
Multibyte String Functions


Replace regular expression with multibyte support ignoring case

mb_ereg
mb_eregi
Multibyte String Functions
PHP Manual

mb_eregi_replace

(PHP 4 >= 4.2.0, PHP 5)

mb_eregi_replace — Replace regular expression with multibyte support ignoring case

Description

string mb_eregi_replace ( string $pattern , string $replace , string $string [, string $option = "msri" ] )

Scans string for matches to pattern , then replaces the matched text with replacement .

Parameters

pattern

The regular expression pattern. Multibyte characters may be used. The case will be ignored.

replace

The replacement text.

string

The searched string.

option
option has the same meaning as in mb_ereg_replace().

Return Values

The resultant string or FALSE on error.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

Warning

Never use the e modifier when working on untrusted input. No automatic escaping will happen (as known from preg_replace()). Not taking care of this will most likely create remote code execution vulnerabilities in your application.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_replace() - Replace regular expression with multibyte support

mb_ereg
mb_eregi
Multibyte String Functions


Get internal settings of mbstring

mb_eregi
mb_http_input
Multibyte String Functions
PHP Manual

mb_get_info

(PHP 4 >= 4.2.0, PHP 5)

mb_get_info — Get internal settings of mbstring

Description

mixed mb_get_info ([ string $type = "all" ] )

mb_get_info() returns the internal setting parameters of mbstring.

Parameters

type

If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input", "func_overload", "mail_charset", "mail_header_encoding", "mail_body_encoding" will be returned.

If type is specified as "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.

Return Values

An array of type information if type is not specified, otherwise a specific type .

Changelog

Version | Description
5.1.3 | The entries "mail_charset", "mail_header_encoding", and "mail_body_encoding" were made available.
5.3.0 | The entry "http_output_conv_mimetypes" was made available.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_http_output() - Set/Get HTTP output character encoding

mb_eregi
mb_http_input
Multibyte String Functions


Detect HTTP input character encoding

mb_get_info
mb_http_output
Multibyte String Functions
PHP Manual

mb_http_input

(PHP 4 >= 4.0.6, PHP 5)

mb_http_input — Detect HTTP input character encoding

Description

mixed mb_http_input ([ string $type = "" ] )

Detects the HTTP input character encoding.

Parameters

type

Input string specifies the input type. "G" for GET, "P" for POST, "C" for COOKIE, "S" for string, "L" for list, and "I" for the whole list (will return array). If type is omitted, it returns the last input type processed.

Return Values

The character encoding name, as per the type . If mb_http_input() does not process specified HTTP input, it returns FALSE.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_http_output() - Set/Get HTTP output character encoding
  • mb_detect_order() - Set/Get character encoding detection order

mb_get_info
mb_http_output
Multibyte String Functions


Set/Get HTTP output character encoding

mb_http_input
mb_internal_encoding
Multibyte String Functions
PHP Manual

mb_http_output

(PHP 4 >= 4.0.6, PHP 5)

mb_http_output — Set/Get HTTP output character encoding

Description

mixed mb_http_output ([ string $encoding ] )

Set/Get the HTTP output character encoding. Output after this function is converted to encoding .

Parameters

encoding

If encoding is set, mb_http_output() sets the HTTP output character encoding to encoding .

If encoding is omitted, mb_http_output() returns the current HTTP output character encoding.

Return Values

If encoding is omitted, mb_http_output() returns the current HTTP output character encoding. Otherwise, Returns TRUE on success or FALSE on failure.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_http_input() - Detect HTTP input character encoding
  • mb_detect_order() - Set/Get character encoding detection order

mb_http_input
mb_internal_encoding
Multibyte String Functions


Set/Get internal character encoding

mb_http_output
mb_language
Multibyte String Functions
PHP Manual

mb_internal_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_internal_encoding — Set/Get internal character encoding

Description

mixed mb_internal_encoding ([ string $encoding = mb_internal_encoding() ] )

Set/Get the internal character encoding

Parameters

encoding

encoding is the character encoding name used for the HTTP input character encoding conversion, HTTP output character encoding conversion, and the default character encoding for string functions defined by the mbstring module.

Return Values

If encoding is set, then Returns TRUE on success or FALSE on failure. If encoding is omitted, then the current character encoding name is returned.

Examples

Example #1 mb_internal_encoding() example

<?php
/* Set internal character encoding to UTF-8 */
mb_internal_encoding("UTF-8");

/* Display current internal character encoding */
echo mb_internal_encoding();
?>

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_http_input() - Detect HTTP input character encoding
  • mb_http_output() - Set/Get HTTP output character encoding
  • mb_detect_order() - Set/Get character encoding detection order

mb_http_output
mb_language
Multibyte String Functions


Set/Get current language

mb_internal_encoding
mb_list_encodings
Multibyte String Functions
PHP Manual

mb_language

(PHP 4 >= 4.0.6, PHP 5)

mb_language — Set/Get current language

Description

mixed mb_language ([ string $language ] )

Set/Get the current language.

Parameters

language

Used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni" (UTF-8). mb_send_mail() uses this setting to encode e-mail.

Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.

Return Values

If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns the language name as a string. If no language is set previously, it then returns FALSE.

See Also

  • mb_send_mail() - Send encoded mail

mb_internal_encoding
mb_list_encodings
Multibyte String Functions


Returns an array of all supported encodings

mb_language
mb_output_handler
Multibyte String Functions
PHP Manual

mb_list_encodings

(PHP 5)

mb_list_encodings — Returns an array of all supported encodings

Description

array mb_list_encodings ( void )

Returns an array containing all supported encodings.

Parameters

This function has no parameters.

Return Values

Returns a numerically indexed array.

Errors/Exceptions

This function does not emit any errors.

Examples

Example #1 mb_list_encodings() example

<?php

print_r(mb_list_encodings());

?>

The above example will output something similar to:

Array
(
    [0] => pass
    [1] => auto
    [2] => wchar
    [3] => byte2be
    [4] => byte2le
    [5] => byte4be
    [6] => byte4le
    [7] => BASE64
    [8] => UUENCODE
    [9] => HTML-ENTITIES
    [10] => Quoted-Printable
    [11] => 7bit
    [12] => 8bit
    [13] => UCS-4
    [14] => UCS-4BE
    [15] => UCS-4LE
    [16] => UCS-2
    [17] => UCS-2BE
    [18] => UCS-2LE
    [19] => UTF-32
    [20] => UTF-32BE
    [21] => UTF-32LE
    [22] => UTF-16
    [23] => UTF-16BE
    [24] => UTF-16LE
    [25] => UTF-8
    [26] => UTF-7
    [27] => UTF7-IMAP
    [28] => ASCII
    [29] => EUC-JP
    [30] => SJIS
    [31] => eucJP-win
    [32] => SJIS-win
    [33] => JIS
    [34] => ISO-2022-JP
    [35] => Windows-1252
    [36] => ISO-8859-1
    [37] => ISO-8859-2
    [38] => ISO-8859-3
    [39] => ISO-8859-4
    [40] => ISO-8859-5
    [41] => ISO-8859-6
    [42] => ISO-8859-7
    [43] => ISO-8859-8
    [44] => ISO-8859-9
    [45] => ISO-8859-10
    [46] => ISO-8859-13
    [47] => ISO-8859-14
    [48] => ISO-8859-15
    [49] => EUC-CN
    [50] => CP936
    [51] => HZ
    [52] => EUC-TW
    [53] => BIG-5
    [54] => EUC-KR
    [55] => UHC
    [56] => ISO-2022-KR
    [57] => Windows-1251
    [58] => CP866
    [59] => KOI8-R
)

mb_language
mb_output_handler
Multibyte String Functions


Callback function converts character encoding in output buffer

mb_list_encodings
mb_parse_str
Multibyte String Functions
PHP Manual

mb_output_handler

(PHP 4 >= 4.0.6, PHP 5)

mb_output_handler — Callback function converts character encoding in output buffer

Description

string mb_output_handler ( string $contents , int $status )

mb_output_handler() is
ob_start() callback
function. mb_output_handler() converts
characters in the output buffer from internal character encoding to
HTTP output character encoding.

Parameters

contents

The contents of the output buffer.

status

The status of the output buffer.

Return Values

The converted string.

Changelog

Version Description
4.1.0

This handler now adds the charset HTTP header when the following conditions are met:

  • Does not set Content-Type, using header().
  • The default MIME type begins with text/.
  • The mbstring.http_input setting is something other than pass.

Examples

Example #1 mb_output_handler() example

<?php
mb_http_output("UTF-8");
ob_start("mb_output_handler");
?>

Notes

Note: If you want to output some binary data such as image from PHP script with PHP 4.3.0 or later, Content-Type: header must be send using header() before any binary data was send to client (e.g. header("Content-Type: image/png")). If Content-Type: header was send, output character encoding conversion will not be performed.
Note that if 'Content-Type: text/*' was send using header(), the sending data is regarded as text, encoding conversion will be performed using character encoding settings.
If you want to output some binary data such as image from PHP script with PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().

See Also

  • ob_start() - Turn on output buffering

mb_list_encodings
mb_parse_str
Multibyte String Functions


Parse GET/POST/COOKIE data and set global variable

mb_output_handler
mb_preferred_mime_name
Multibyte String Functions
PHP Manual

mb_parse_str

(PHP 4 >= 4.0.6, PHP 5)

mb_parse_str — Parse GET/POST/COOKIE data and set global variable

Description

bool mb_parse_str ( string $encoded_string [, array &$result ] )

Parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only be used for GET data for now. It parses URL encoded data, detects encoding, converts coding to internal encoding and set values to the result array or global variables.

Parameters

encoded_string

The URL encoded data.

result

An array containing decoded and character encoded converted values.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mb_detect_order() - Set/Get character encoding detection order
  • mb_internal_encoding() - Set/Get internal character encoding

mb_output_handler
mb_preferred_mime_name
Multibyte String Functions


Get MIME charset string

mb_parse_str
mb_regex_encoding
Multibyte String Functions
PHP Manual

mb_preferred_mime_name

(PHP 4 >= 4.0.6, PHP 5)

mb_preferred_mime_name — Get MIME charset string

Description

string mb_preferred_mime_name ( string $encoding )

Get a MIME charset string for a specific encoding.

Parameters

encoding

The encoding being checked.

Return Values

The MIME charset string for character encoding encoding .

Examples

Example #1 mb_preferred_mime_name() example

<?php
$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));
?>

mb_parse_str
mb_regex_encoding
Multibyte String Functions


Returns current encoding for multibyte regex as string

mb_preferred_mime_name
mb_regex_set_options
Multibyte String Functions
PHP Manual

mb_regex_encoding

(PHP 4 >= 4.2.0, PHP 5)

mb_regex_encoding — Returns current encoding for multibyte regex as string

Description

mixed mb_regex_encoding ([ string $encoding ] )

Returns the current encoding for a multibyte regex as a string.

Parameters

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

Returns the character encoding used by multibyte regex functions.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_ereg() - Regular expression match with multibyte support

mb_preferred_mime_name
mb_regex_set_options
Multibyte String Functions


Set/Get the default options for mbregex functions

mb_regex_encoding
mb_send_mail
Multibyte String Functions
PHP Manual

mb_regex_set_options

(PHP 4 >= 4.3.0, PHP 5)

mb_regex_set_options — Set/Get the default options for mbregex functions

Description

string mb_regex_set_options ([ string $options = "msr" ] )

Sets the default options described by options for multibyte regex functions.

Parameters

options

The options to set. This is a a string where each character is an option. To set a mode, the mode character must be the last one set, however there can only be set one mode but multiple options.

Regex options
Option | Meaning
i | Ambiguity match on
x | Enables extended pattern form
m | '.' matches with newlines
s | '^' -> '\A', '$' -> '\Z'
p | Same as both the m and s options
l | Finds longest matches
n | Ignores empty matches
e | eval() resulting code
Regex syntax modes
Mode | Meaning
j | Java (Sun java.util.regex)
u | GNU regex
g | grep
c | Emacs
r | Ruby
z | Perl
b | POSIX Basic regex
d | POSIX Extended regex

Return Values

The previous options. If options is omitted, it returns the string that describes the current options.

See Also

  • mb_split() - Split multibyte string using regular expression
  • mb_ereg() - Regular expression match with multibyte support
  • mb_eregi() - Regular expression match ignoring case with multibyte support

mb_regex_encoding
mb_send_mail
Multibyte String Functions


Send encoded mail

mb_regex_set_options
mb_split
Multibyte String Functions
PHP Manual

mb_send_mail

(PHP 4 >= 4.0.6, PHP 5)

mb_send_mail — Send encoded mail

Description

bool mb_send_mail ( string $to , string $subject , string $message [, string $additional_headers = NULL [, string $additional_parameter = NULL ]] )

Sends email. Headers and messages are converted and encoded according to the mb_language() setting. It's a wrapper function for mail(), so see also mail() for details.

Parameters

to

The mail addresses being sent to. Multiple recipients may be specified by putting a comma between each address in to . This parameter is not automatically encoded.

subject

The subject of the mail.

message

The message of the mail.

additional_headers

additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline ("\n").

additional_parameter

additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | The Content-Type and Content-Transfer-Encoding headers may be redefined as of PHP 5.0.0. Before this time, the values defined by mb_language() are always used.

See Also

  • mail() - Send mail
  • mb_encode_mimeheader() - Encode string for MIME header
  • mb_language() - Set/Get current language

mb_regex_set_options
mb_split
Multibyte String Functions


Split multibyte string using regular expression

mb_send_mail
mb_strcut
Multibyte String Functions
PHP Manual

mb_split

(PHP 4 >= 4.2.0, PHP 5)

mb_split — Split multibyte string using regular expression

Description

array mb_split ( string $pattern , string $string [, int $limit = -1 ] )

Split a multibyte string using regular expression pattern and returns the result as an array.

Parameters

pattern

The regular expression pattern.

string

The string being split.

limit
If optional parameter limit is specified, it will be split in limit elements as maximum.

Return Values

The result as an array.

Notes

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg() - Regular expression match with multibyte support

mb_send_mail
mb_strcut
Multibyte String Functions


Get part of string

mb_split
mb_strimwidth
Multibyte String Functions
PHP Manual

mb_strcut

(PHP 4 >= 4.0.6, PHP 5)

mb_strcut — Get part of string

Description

string mb_strcut ( string $str , int $start [, int $length [, string $encoding ]] )

mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character.

It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle of shift sequence.

Parameters

str

The string being cut.

start

The position that begins the cut.

length

The string being decoded.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

mb_strcut() returns the portion of str specified by the start and length parameters.

See Also

  • mb_substr() - Get part of string
  • mb_internal_encoding() - Set/Get internal character encoding

mb_split
mb_strimwidth
Multibyte String Functions


Get truncated string with specified width

mb_strcut
mb_stripos
Multibyte String Functions
PHP Manual

mb_strimwidth

(PHP 4 >= 4.0.6, PHP 5)

mb_strimwidth — Get truncated string with specified width

Description

string mb_strimwidth ( string $str , int $start , int $width [, string $trimmarker [, string $encoding ]] )

Truncates string str to specified width .

Parameters

str

The string being decoded.

start

The start position offset. Number of characters from the beginning of string. (First character is 0)

width

The width of the desired trim.

trimmarker

A string that is added to the end of string when string is truncated.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The truncated string. If trimmarker is set, trimmarker is appended to the return value.

Examples

Example #1 mb_strimwidth() example

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
// outputs Hello W...
?>

See Also

  • mb_strwidth() - Return width of string
  • mb_internal_encoding() - Set/Get internal character encoding

mb_strcut
mb_stripos
Multibyte String Functions


Finds position of first occurrence of a string within another, case insensitive

mb_strimwidth
mb_stristr
Multibyte String Functions
PHP Manual

mb_stripos

(PHP 5 >= 5.2.0)

mb_stripos — Finds position of first occurrence of a string within another, case insensitive

Description

int mb_stripos ( string $haystack , string $needle [, int $offset [, string $encoding ]] )

mb_stripos() returns the numeric position of the first occurrence of needle in the haystack string. Unlike mb_strpos(), mb_stripos() is case-insensitive. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the position of the first occurrence of needle

needle

The string to find in haystack

offset

The position in haystack to start searching

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Return the numeric position of the first occurrence of needle in the haystack string, or FALSE if needle is not found.

See Also

  • stripos() - Find position of first occurrence of a case-insensitive string
  • strpos() - Find position of first occurrence of a string
  • mb_strpos() - Find position of first occurrence of string in a string

mb_strimwidth
mb_stristr
Multibyte String Functions


Finds first occurrence of a string within another, case insensitive

mb_stripos
mb_strlen
Multibyte String Functions
PHP Manual

mb_stristr

(PHP 5 >= 5.2.0)

mb_stristr — Finds first occurrence of a string within another, case insensitive

Description

string mb_stristr ( string $haystack , string $needle [, bool $part = false [, string $encoding ]] )

mb_stristr() finds the first occurrence of needle in haystack and returns the portion of haystack . Unlike mb_strstr(), mb_stristr() is case-insensitive. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the first occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the first occurrence of needle . If set to FALSE, it returns all of haystack from the first occurrence of needle to the end,

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack , or FALSE if needle is not found.

See Also

  • stristr() - Case-insensitive strstr
  • strstr() - Find first occurrence of a string
  • mb_strstr() - Finds first occurrence of a string within another

mb_stripos
mb_strlen
Multibyte String Functions


Get string length

mb_stristr
mb_strpos
Multibyte String Functions
PHP Manual

mb_strlen

(PHP 4 >= 4.0.6, PHP 5)

mb_strlen — Get string length

Description

int mb_strlen ( string $str [, string $encoding ] )

Gets the length of a string.

Parameters

str

The string being checked for length.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

Returns the number of characters in string str having character encoding encoding . A multi-byte character is counted as 1.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • strlen() - Get string length

mb_stristr
mb_strpos
Multibyte String Functions


Find position of first occurrence of string in a string

mb_strlen
mb_strrchr
Multibyte String Functions
PHP Manual

mb_strpos

(PHP 4 >= 4.0.6, PHP 5)

mb_strpos — Find position of first occurrence of string in a string

Description

int mb_strpos ( string $haystack , string $needle [, int $offset [, string $encoding ]] )

Finds position of the first occurrence of a string in a string.

Performs a multi-byte safe strpos() operation based on number of characters. The first character's position is 0, the second character position is 1, and so on.

Parameters

haystack

The string being checked.

needle

The position counted from the beginning of haystack .

offset

The search offset. If it is not specified, 0 is used.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

Returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • strpos() - Find position of first occurrence of a string

mb_strlen
mb_strrchr
Multibyte String Functions


Finds the last occurrence of a character in a string within another

mb_strpos
mb_strrichr
Multibyte String Functions
PHP Manual

mb_strrchr

(PHP 5 >= 5.2.0)

mb_strrchr — Finds the last occurrence of a character in a string within another

Description

string mb_strrchr ( string $haystack , string $needle [, bool $part = false [, string $encoding ]] )

mb_strrchr() finds the last occurrence of needle in haystack and returns the portion of haystack . If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the last occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the last occurrence of needle . If set to FALSE, it returns all of haystack from the last occurrence of needle to the end,

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack . or FALSE if needle is not found.

See Also

  • strrchr() - Find the last occurrence of a character in a string
  • mb_strstr() - Finds first occurrence of a string within another
  • mb_strrichr() - Finds the last occurrence of a character in a string within another, case insensitive

mb_strpos
mb_strrichr
Multibyte String Functions


Finds the last occurrence of a character in a string within another, case insensitive

mb_strrchr
mb_strripos
Multibyte String Functions
PHP Manual

mb_strrichr

(PHP 5 >= 5.2.0)

mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive

Description

string mb_strrichr ( string $haystack , string $needle [, bool $part = false [, string $encoding ]] )

mb_strrichr() finds the last occurrence of needle in haystack and returns the portion of haystack . Unlike mb_strrchr(), mb_strrichr() is case-insensitive. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the last occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the last occurrence of needle . If set to FALSE, it returns all of haystack from the last occurrence of needle to the end,

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack . or FALSE if needle is not found.

See Also

  • mb_stristr() - Finds first occurrence of a string within another, case insensitive
  • mb_strrchr() - Finds the last occurrence of a character in a string within another

mb_strrchr
mb_strripos
Multibyte String Functions


Finds position of last occurrence of a string within another, case insensitive

mb_strrichr
mb_strrpos
Multibyte String Functions
PHP Manual

mb_strripos

(PHP 5 >= 5.2.0)

mb_strripos — Finds position of last occurrence of a string within another, case insensitive

Description

int mb_strripos ( string $haystack , string $needle [, int $offset [, string $encoding ]] )

mb_strripos() performs multi-byte safe strripos() operation based on number of characters. needle position is counted from the beginning of haystack . First character's position is 0. Second character position is 1. Unlike mb_strrpos(), mb_strripos() is case-insensitive.

Parameters

haystack

The string from which to get the position of the last occurrence of needle

needle

The string to find in haystack

offset

The position in haystack to start searching

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Return the numeric position of the last occurrence of needle in the haystack string, or FALSE if needle is not found.

See Also

  • strripos() - Find position of last occurrence of a case-insensitive string in a string
  • strrpos() - Find position of last occurrence of a char in a string
  • mb_strrpos() - Find position of last occurrence of a string in a string

mb_strrichr
mb_strrpos
Multibyte String Functions


Find position of last occurrence of a string in a string

mb_strripos
mb_strstr
Multibyte String Functions
PHP Manual

mb_strrpos

(PHP 4 >= 4.0.6, PHP 5)

mb_strrpos — Find position of last occurrence of a string in a string

Description

int mb_strrpos ( string $haystack , string $needle [, int $offset [, string $encoding ]] )

Performs a multibyte safe strrpos() operation based on the number of characters. needle position is counted from the beginning of haystack . First character's position is 0. Second character position is 1.

Parameters

haystack

The string being checked, for the last occurrence of needle

needle

The string to find in haystack .

offset
May be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string.
encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

Returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

Changelog

Version | Description
5.2.0 | Added the optional parameter offset .

Notes

Note: The encoding parameter was moved from the third position to the fourth in PHP 5.2.0. For backward compatibility, encoding can be specified as the third parameter, but doing so is deprecated and will be removed in the future.

Note: The internal encoding or the character encoding specified by mb_regex_encoding() will be used as the character encoding for this function.

See Also

  • mb_strpos() - Find position of first occurrence of string in a string
  • mb_internal_encoding() - Set/Get internal character encoding
  • strrpos() - Find position of last occurrence of a char in a string

mb_strripos
mb_strstr
Multibyte String Functions


Finds first occurrence of a string within another

mb_strrpos
mb_strtolower
Multibyte String Functions
PHP Manual

mb_strstr

(PHP 5 >= 5.2.0)

mb_strstr — Finds first occurrence of a string within another

Description

string mb_strstr ( string $haystack , string $needle [, bool $part = false [, string $encoding ]] )

mb_strstr() finds the first occurrence of needle in haystack and returns the portion of haystack . If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the first occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the first occurrence of needle . If set to FALSE, it returns all of haystack from the first occurrence of needle to the end,

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack , or FALSE if needle is not found.

See Also

  • stristr() - Case-insensitive strstr
  • strstr() - Find first occurrence of a string
  • mb_stristr() - Finds first occurrence of a string within another, case insensitive

mb_strrpos
mb_strtolower
Multibyte String Functions


Make a string lowercase

mb_strstr
mb_strtoupper
Multibyte String Functions
PHP Manual

mb_strtolower

(PHP 4 >= 4.3.0, PHP 5)

mb_strtolower — Make a string lowercase

Description

string mb_strtolower ( string $str [, string $encoding = mb_internal_encoding() ] )

Returns str with all alphabetic characters converted to lowercase.

Parameters

str

The string being lowercased.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

str with all alphabetic characters converted to lowercase.

Unicode

For more information about the Unicode properties, please see » http://www.unicode.org/unicode/reports/tr21/.

By contrast to strtolower(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

Examples

Example #1 mb_strtolower() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?>

See Also

  • mb_strtoupper() - Make a string uppercase
  • mb_convert_case() - Perform case folding on a string
  • strtolower() - Make a string lowercase

mb_strstr
mb_strtoupper
Multibyte String Functions


Make a string uppercase

mb_strtolower
mb_strwidth
Multibyte String Functions
PHP Manual

mb_strtoupper

(PHP 4 >= 4.3.0, PHP 5)

mb_strtoupper — Make a string uppercase

Description

string mb_strtoupper ( string $str [, string $encoding = mb_internal_encoding() ] )

Returns str with all alphabetic characters converted to uppercase.

Parameters

str

The string being uppercased.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

str with all alphabetic characters converted to uppercase.

Unicode

For more information about the Unicode properties, please see » http://www.unicode.org/unicode/reports/tr21/.

By contrast to strtoupper(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).

Examples

Example #1 mb_strtoupper() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>

See Also

  • mb_strtolower() - Make a string lowercase
  • mb_convert_case() - Perform case folding on a string
  • strtoupper() - Make a string uppercase

mb_strtolower
mb_strwidth
Multibyte String Functions


Return width of string

mb_strtoupper
mb_substitute_character
Multibyte String Functions
PHP Manual

mb_strwidth

(PHP 4 >= 4.0.6, PHP 5)

mb_strwidth — Return width of string

Description

int mb_strwidth ( string $str [, string $encoding ] )

Returns the width of string str .

Multi-byte characters are usually twice the width of single byte characters.

Characters width
Chars | Width
U+0000 - U+0019 | 0
U+0020 - U+1FFF | 1
U+2000 - U+FF60 | 2
U+FF61 - U+FF9F | 1
U+FFA0 - | 2

Parameters

str

The string being decoded.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The width of string str .

See Also

  • mb_strimwidth() - Get truncated string with specified width
  • mb_internal_encoding() - Set/Get internal character encoding

mb_strtoupper
mb_substitute_character
Multibyte String Functions


Set/Get substitution character

mb_strwidth
mb_substr_count
Multibyte String Functions
PHP Manual

mb_substitute_character

(PHP 4 >= 4.0.6, PHP 5)

mb_substitute_character — Set/Get substitution character

Description

mixed mb_substitute_character ([ mixed $substrchar ] )

Specifies a substitution character when input character encoding is invalid or character code does not exist in output character encoding. Invalid characters may be substituted NULL (no output), string or integer value (Unicode character code value).

This setting affects mb_convert_encoding(),
mb_convert_variables(),
mb_output_handler(),
and mb_send_mail().

Parameters

substrchar

Specify the Unicode value as an integer, or as one of the following strings:

  • "none" : no output
  • "long" : Output character code value (Example: U+3000,JIS+7E7E)

Return Values

If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns the Unicode value, or "none" or "long".

Examples

Example #1 mb_substitute_character() example

<?php
/* Set with Unicode U+3013 (GETA MARK) */
mb_substitute_character(0x3013);

/* Set hex format */
mb_substitute_character("long");

/* Display current setting */
echo mb_substitute_character();
?>

mb_strwidth
mb_substr_count
Multibyte String Functions


Get part of string

mb_substr_count
Pspell
Multibyte String Functions
PHP Manual

mb_substr

(PHP 4 >= 4.0.6, PHP 5)

mb_substr — Get part of string

Description

string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] )

Performs a multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str . First character's position is 0. Second character position is 1, and so on.

Parameters

str

The string being checked.

start

The first position used in str .

length

The maximum length of the returned string.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

mb_substr() returns the portion of str specified by the start and length parameters.

See Also

  • mb_strcut() - Get part of string
  • mb_internal_encoding() - Set/Get internal character encoding

mb_substr_count
Pspell
Multibyte String Functions


Count the number of substring occurrences

mb_substitute_character
mb_substr
Multibyte String Functions
PHP Manual

mb_substr_count

(PHP 4 >= 4.3.0, PHP 5)

mb_substr_count — Count the number of substring occurrences

Description

int mb_substr_count ( string $haystack , string $needle [, string $encoding ] )

Counts the number of times the needle substring occurs in the haystack string.

Parameters

haystack

The string being checked.

needle

The string being found.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The number of times the needle substring occurs in the haystack string.

Examples

Example #1 mb_substr_count() example

<?php
echo mb_substr_count("This is a test", "is"); // prints out 2
?>

See Also

  • mb_strpos() - Find position of first occurrence of string in a string
  • mb_substr() - Get part of string
  • substr_count() - Count the number of substring occurrences

mb_substitute_character
mb_substr
Multibyte String Functions


Encrypt/decrypt data in CBC mode

Mcrypt Functions
mcrypt_cfb
Mcrypt Functions
PHP Manual

mcrypt_cbc

(PHP 4, PHP 5)

mcrypt_cbc — Encrypt/decrypt data in CBC mode

Description

string mcrypt_cbc ( int $cipher , string $key , string $data , int $mode [, string $iv ] )
string mcrypt_cbc ( string $cipher , string $key , string $data , int $mode [, string $iv ] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

Mcrypt Functions
mcrypt_cfb
Mcrypt Functions


Encrypt/decrypt data in CFB mode

mcrypt_cbc
mcrypt_create_iv
Mcrypt Functions
PHP Manual

mcrypt_cfb

(PHP 4, PHP 5)

mcrypt_cfb — Encrypt/decrypt data in CFB mode

Description

string mcrypt_cfb ( int $cipher , string $key , string $data , int $mode , string $iv )
string mcrypt_cfb ( string $cipher , string $key , string $data , int $mode [, string $iv ] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_cbc
mcrypt_create_iv
Mcrypt Functions


Create an initialization vector (IV) from a random source

mcrypt_cfb
mcrypt_decrypt
Mcrypt Functions
PHP Manual

mcrypt_create_iv

(PHP 4, PHP 5)

mcrypt_create_iv — Create an initialization vector (IV) from a random source

Description

string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )

Create an initialization vector (IV) from a random source.

The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without losing security.

Parameters

size

Determines the size of the IV, parameter source (defaults to random value) specifies the source of the IV.

source

The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). Prior to 5.3.0, MCRYPT_RAND was the only one supported on Windows.

Return Values

Returns the initialization vector, or FALSE on error.

Changelog

Version | Description
5.3.0 | MCRYPT_DEV_RANDOM and MCRYPT_DEV_URANDOM became available on Windows platforms.
5.3.0 | It is no longer required to call srand() first. This is now done automatically.

Examples

Example #1 mcrypt_create_iv() example

<?php
    $size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
    $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
?>

See Also

  • » http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
  • » http://www.quadibloc.com/crypto/co0409.htm
  • Chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9)

mcrypt_cfb
mcrypt_decrypt
Mcrypt Functions


Decrypts crypttext with given parameters

mcrypt_create_iv
mcrypt_ecb
Mcrypt Functions
PHP Manual

mcrypt_decrypt

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_decrypt — Decrypts crypttext with given parameters

Description

string mcrypt_decrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] )

Decrypts the data and returns the unencrypted data.

Parameters

cipher

cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

key

key is the key with which the data is encrypted. If it's smaller that the required keysize, it is padded with '\0'.

data

data is the data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.

mode

mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

iv

The iv parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

Return Values

Returns the decrypted data as a string.

mcrypt_create_iv
mcrypt_ecb
Mcrypt Functions


Deprecated: Encrypt/decrypt data in ECB mode

mcrypt_decrypt
mcrypt_enc_get_algorithms_name
Mcrypt Functions
PHP Manual

mcrypt_ecb

(PHP 4, PHP 5)

mcrypt_ecb — Deprecated: Encrypt/decrypt data in ECB mode

Description

string mcrypt_ecb ( int $cipher , string $key , string $data , int $mode )
string mcrypt_ecb ( string $cipher , string $key , string $data , int $mode [, string $iv ] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function is deprecated and should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_decrypt
mcrypt_enc_get_algorithms_name
Mcrypt Functions


Returns the name of the opened algorithm

mcrypt_ecb
mcrypt_enc_get_block_size
Mcrypt Functions
PHP Manual

mcrypt_enc_get_algorithms_name

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm

Description

string mcrypt_enc_get_algorithms_name ( resource $td )

This function returns the name of the algorithm.

Parameters

td

The encryption descriptor.

Return Values

Returns the name of the opened algorithm as a string.

Examples

Example #1 mcrypt_enc_get_algorithms_name() example

<?php
$td = mcrypt_module_open(MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";

$td = mcrypt_module_open('cast-256', '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";
?>

The above example will output:

CAST-256
CAST-256

mcrypt_ecb
mcrypt_enc_get_block_size
Mcrypt Functions


Returns the blocksize of the opened algorithm

mcrypt_enc_get_algorithms_name
mcrypt_enc_get_iv_size
Mcrypt Functions
PHP Manual

mcrypt_enc_get_block_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm

Description

int mcrypt_enc_get_block_size ( resource $td )

Gets the blocksize of the opened algorithm.

Parameters

td

The encryption descriptor.

Return Values

Returns the block size of the specified algorithm in bytes.

mcrypt_enc_get_algorithms_name
mcrypt_enc_get_iv_size
Mcrypt Functions


Returns the size of the IV of the opened algorithm

mcrypt_enc_get_block_size
mcrypt_enc_get_key_size
Mcrypt Functions
PHP Manual

mcrypt_enc_get_iv_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm

Description

int mcrypt_enc_get_iv_size ( resource $td )

This function returns the size of the IV of the algorithm specified by the encryption descriptor in bytes. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.

Parameters

td

The encryption descriptor.

Return Values

Returns the size of the IV, or 0 if the IV is ignored in the algorithm.

mcrypt_enc_get_block_size
mcrypt_enc_get_key_size
Mcrypt Functions


Returns the maximum supported keysize of the opened mode

mcrypt_enc_get_iv_size
mcrypt_enc_get_modes_name
Mcrypt Functions
PHP Manual

mcrypt_enc_get_key_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode

Description

int mcrypt_enc_get_key_size ( resource $td )

Gets the maximum supported key size of the algorithm in bytes.

Parameters

td

The encryption descriptor.

Return Values

Returns the maximum supported key size of the algorithm in bytes.

mcrypt_enc_get_iv_size
mcrypt_enc_get_modes_name
Mcrypt Functions


Returns the name of the opened mode

mcrypt_enc_get_key_size
mcrypt_enc_get_supported_key_sizes
Mcrypt Functions
PHP Manual

mcrypt_enc_get_modes_name

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_modes_name — Returns the name of the opened mode

Description

string mcrypt_enc_get_modes_name ( resource $td )

This function returns the name of the mode.

Parameters

td

The encryption descriptor.

Return Values

Returns the name as a string.

Examples

Example #1 mcrypt_enc_get_modes_name() example

<?php
$td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_modes_name($td). "\n";

$td = mcrypt_module_open ('cast-256', '', 'ecb', '');
echo mcrypt_enc_get_modes_name($td). "\n";
?>

The above example will output:

CFB
ECB

mcrypt_enc_get_key_size
mcrypt_enc_get_supported_key_sizes
Mcrypt Functions


Returns an array with the supported keysizes of the opened algorithm

mcrypt_enc_get_modes_name
mcrypt_enc_is_block_algorithm_mode
Mcrypt Functions
PHP Manual

mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_enc_get_supported_key_sizes ( resource $td )

Gets the supported key sizes of the opened algorithm.

Parameters

td

The encryption descriptor.

Return Values

Returns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.

Examples

Example #1 mcrypt_enc_get_supported_key_sizes() example

<?php
    $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
    var_dump(mcrypt_enc_get_supported_key_sizes($td));
?>

This will print:

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}

mcrypt_enc_get_modes_name
mcrypt_enc_is_block_algorithm_mode
Mcrypt Functions


Checks whether the algorithm of the opened mode is a block algorithm

mcrypt_enc_is_block_algorithm_mode
mcrypt_enc_is_block_mode
Mcrypt Functions
PHP Manual

mcrypt_enc_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm

Description

bool mcrypt_enc_is_block_algorithm ( resource $td )

Tells whether the algorithm of the opened mode is a block algorithm.

Parameters

td

The encryption descriptor.

Return Values

Returns TRUE if the algorithm is a block algorithm or FALSE if it is a stream one.

mcrypt_enc_is_block_algorithm_mode
mcrypt_enc_is_block_mode
Mcrypt Functions


Checks whether the encryption of the opened mode works on blocks

mcrypt_enc_get_supported_key_sizes
mcrypt_enc_is_block_algorithm
Mcrypt Functions
PHP Manual

mcrypt_enc_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks

Description

bool mcrypt_enc_is_block_algorithm_mode ( resource $td )

Tells whether the algorithm of the opened mode works on blocks (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb)..

Parameters

td

The encryption descriptor.

Return Values

Returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE.

mcrypt_enc_get_supported_key_sizes
mcrypt_enc_is_block_algorithm
Mcrypt Functions


Checks whether the opened mode outputs blocks

mcrypt_enc_is_block_algorithm
mcrypt_enc_self_test
Mcrypt Functions
PHP Manual

mcrypt_enc_is_block_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks

Description

bool mcrypt_enc_is_block_mode ( resource $td )

Tells whether the opened mode outputs blocks (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).

Parameters

td

The encryption descriptor.

Return Values

Returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs bytes.

mcrypt_enc_is_block_algorithm
mcrypt_enc_self_test
Mcrypt Functions


Runs a self test on the opened module

mcrypt_enc_is_block_mode
mcrypt_encrypt
Mcrypt Functions
PHP Manual

mcrypt_enc_self_test

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_self_test — Runs a self test on the opened module

Description

int mcrypt_enc_self_test ( resource $td )

This function runs the self test on the algorithm specified by the descriptor td .

Parameters

td

The encryption descriptor.

Return Values

If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.

mcrypt_enc_is_block_mode
mcrypt_encrypt
Mcrypt Functions


Encrypts plaintext with given parameters

mcrypt_enc_self_test
mcrypt_generic_deinit
Mcrypt Functions
PHP Manual

mcrypt_encrypt

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_encrypt — Encrypts plaintext with given parameters

Description

string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] )

Encrypts the data and returns it.

Parameters

cipher

One of the MCRYPT_ciphername constants of the name of the algorithm as string.

key

The key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys.

It is recommended to use the mhash functions to create a key from a string.

data

The data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.

The returned crypttext can be larger that the size of the data that is given by data .

mode

One of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

iv

Used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

Return Values

Returns the encrypted data, as a string.

Examples

Example #1 mcrypt_encrypt() Example

<?php
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $key = "This is a very secret key";
    $text = "Meet me at 11 o'clock behind the monument.";
    echo strlen($text) . "\n";

    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    echo strlen($crypttext) . "\n";
?>

The above example will output:

42
64

See also mcrypt_module_open() for a more advanced API and an example.

mcrypt_enc_self_test
mcrypt_generic_deinit
Mcrypt Functions


This function encrypts data

mcrypt_generic_init
mcrypt_get_block_size
Mcrypt Functions
PHP Manual

mcrypt_generic

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic — This function encrypts data

Description

string mcrypt_generic ( resource $td , string $data )

This function encrypts data. The data is padded with "\0" to make sure the length of the data is n * blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer then the input, due to the padding of the data.

If you want to store the encrypted data in a database make sure to store the entire string as returned by mcrypt_generic, or the string will not entirely decrypt properly. If your original string is 10 characters long and the block size is 8 (use mcrypt_enc_get_block_size() to determine the blocksize), you would need at least 16 characters in your database field. Note the string returned by mdecrypt_generic() will be 16 characters as well...use rtrim($str, "\0") to remove the padding.

If you are for example storing the data in a MySQL database remember that varchar fields automatically have trailing spaces removed during insertion. As encrypted data can end in a space (ASCII 32), the data will be damaged by this removal. Store data in a tinyblob/tinytext (or larger) field instead.

Parameters

td

The encryption descriptor.

The encryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

data

The data to encrypt.

Return Values

Returns the encrypted data.

See Also

  • mdecrypt_generic() - Decrypt data
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption
  • mcrypt_generic_deinit() - This function deinitializes an encryption module

mcrypt_generic_init
mcrypt_get_block_size
Mcrypt Functions


This function deinitializes an encryption module

mcrypt_encrypt
mcrypt_generic_end
Mcrypt Functions
PHP Manual

mcrypt_generic_deinit

(PHP 4 >= 4.0.7, PHP 5)

mcrypt_generic_deinit — This function deinitializes an encryption module

Description

bool mcrypt_generic_deinit ( resource $td )

This function terminates encryption specified by the encryption descriptor (td ). It clears all buffers, but does not close the module. You need to call mcrypt_module_close() yourself. (But PHP does this for you at the end of the script.)

Parameters

td

The encryption descriptor.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption

mcrypt_encrypt
mcrypt_generic_end
Mcrypt Functions


This function terminates encryption

mcrypt_generic_deinit
mcrypt_generic_init
Mcrypt Functions
PHP Manual

mcrypt_generic_end

(PHP 4 >= 4.0.2, PHP 5 <= 5.1.6)

mcrypt_generic_end — This function terminates encryption

Description

bool mcrypt_generic_end ( resource $td )

Warning

This function is deprecated, use mcrypt_generic_deinit() instead. It can cause crashes when used with mcrypt_module_close() due to multiple buffer frees.

This function terminates encryption specified by the encryption descriptor (td ). Actually it clears all buffers, and closes all the modules used. Returns FALSE on error, or TRUE on success.

mcrypt_generic_deinit
mcrypt_generic_init
Mcrypt Functions


This function initializes all buffers needed for encryption

mcrypt_generic_end
mcrypt_generic
Mcrypt Functions
PHP Manual

mcrypt_generic_init

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic_init — This function initializes all buffers needed for encryption

Description

int mcrypt_generic_init ( resource $td , string $key , string $iv )

You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().

Parameters

td

The encryption descriptor.

key

The maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller than this is legal.

iv

The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to use it you should set it to zeros, but this is not recommended.

Return Values

The function returns a negative value on error, -3 when the key length was incorrect, -4 when there was a memory allocation problem and any other return value is an unknown error. If an error occurs a warning will be displayed accordingly. FALSE is returned if incorrect parameters were passed.

See Also

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

mcrypt_generic_end
mcrypt_generic
Mcrypt Functions


Get the block size of the specified cipher

mcrypt_generic
mcrypt_get_cipher_name
Mcrypt Functions
PHP Manual

mcrypt_get_block_size

(PHP 4, PHP 5)

mcrypt_get_block_size — Get the block size of the specified cipher

Description

int mcrypt_get_block_size ( int $cipher )
int mcrypt_get_block_size ( string $cipher , string $module )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption mode).

It is more useful to use the mcrypt_enc_get_block_size() function as this uses the resource returned by mcrypt_module_open().

Parameters

cipher

One of the MCRYPT_ciphername constants or the name of the algorithm as string.

module

The module.

Return Values

Gets the block size, as an integer.

Examples

Example #1 mcrypt_get_block_size() example

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.

<?php

echo mcrypt_get_block_size('tripledes', 'ecb'); // 8

?>

See Also

  • mcrypt_get_key_size() - Get the key size of the specified cipher
  • mcrypt_enc_get_block_size() - Returns the blocksize of the opened algorithm
  • mcrypt_encrypt() - Encrypts plaintext with given parameters

mcrypt_generic
mcrypt_get_cipher_name
Mcrypt Functions


Get the name of the specified cipher

mcrypt_get_block_size
mcrypt_get_iv_size
Mcrypt Functions
PHP Manual

mcrypt_get_cipher_name

(PHP 4, PHP 5)

mcrypt_get_cipher_name — Get the name of the specified cipher

Description

string mcrypt_get_cipher_name ( int $cipher )
string mcrypt_get_cipher_name ( string $cipher )

mcrypt_get_cipher_name() is used to get the name of the specified cipher.

mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher) and returns the name of the cipher or FALSE, if the cipher does not exist.

Parameters

cipher

One of the MCRYPT_ciphername constants or the name of the algorithm as string.

Return Values

This function returns the name of the cipher or FALSE, if the cipher does not exist.

Examples

Example #1 mcrypt_get_cipher_name() Example

<?php
   $cipher = MCRYPT_TripleDES;

   echo mcrypt_get_cipher_name($cipher);
?>

The above example will output:

3DES

mcrypt_get_block_size
mcrypt_get_iv_size
Mcrypt Functions


Returns the size of the IV belonging to a specific cipher/mode combination

mcrypt_get_cipher_name
mcrypt_get_key_size
Mcrypt Functions
PHP Manual

mcrypt_get_iv_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination

Description

int mcrypt_get_iv_size ( string $cipher , string $mode )

Gets the size of the IV belonging to a specific cipher /mode combination.

It is more useful to use the mcrypt_enc_get_iv_size() function as this uses the resource returned by mcrypt_module_open().

Parameters

cipher

One of the MCRYPT_ciphername constants of the name of the algorithm as string.

mode

mode is one of the MCRYPT_MODE_modename constants or one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream". The IV is ignored in ECB mode as this mode does not require it. You will need to have the same IV (think: starting point) both at encryption and decryption stages, otherwise your encryption will fail.

Return Values

Returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.

Examples

Example #1 mcrypt_get_iv_size() example

<?php
    echo mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB) . "\n";

    echo mcrypt_get_iv_size('des', 'ecb') . "\n";
?>

See Also

  • mcrypt_get_block_size() - Get the block size of the specified cipher
  • mcrypt_enc_get_iv_size() - Returns the size of the IV of the opened algorithm
  • mcrypt_create_iv() - Create an initialization vector (IV) from a random source

mcrypt_get_cipher_name
mcrypt_get_key_size
Mcrypt Functions


Get the key size of the specified cipher

mcrypt_get_iv_size
mcrypt_list_algorithms
Mcrypt Functions
PHP Manual

mcrypt_get_key_size

(PHP 4, PHP 5)

mcrypt_get_key_size — Get the key size of the specified cipher

Description

int mcrypt_get_key_size ( int $cipher )
int mcrypt_get_key_size ( string $cipher , string $module )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x. It is more useful to use the mcrypt_enc_get_key_size() function as this uses the resource returned by mcrypt_module_open().

Example #1 mcrypt_get_key_size() example

<?php
    echo mcrypt_get_key_size('tripledes', 'ecb');
?>

Prints:
24

See also: mcrypt_get_block_size(),
mcrypt_enc_get_key_size() and
mcrypt_encrypt().

mcrypt_get_iv_size
mcrypt_list_algorithms
Mcrypt Functions


Get an array of all supported ciphers

mcrypt_get_key_size
mcrypt_list_modes
Mcrypt Functions
PHP Manual

mcrypt_list_algorithms

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_list_algorithms — Get an array of all supported ciphers

Description

array mcrypt_list_algorithms ([ string $lib_dir = ini_get("mcrypt.algorithms_dir") ] )

Gets the list of all supported algorithms in the lib_dir parameter.

Parameters

lib_dir

Specifies the directory where all algorithms are located. If not specifies, the value of the mcrypt.algorithms_dir php.ini directive is used.

Return Values

Returns an array with all the supported algorithms.

Examples

Example #1 mcrypt_list_algorithms() Example

<?php
    $algorithms = mcrypt_list_algorithms("/usr/local/lib/libmcrypt");

    foreach ($algorithms as $cipher) {
        echo "$cipher<br />\n";
    }
?>

The above example will produce a list with all supported algorithms in the "/usr/local/lib/libmcrypt" directory.

mcrypt_get_key_size
mcrypt_list_modes
Mcrypt Functions


Get an array of all supported modes

mcrypt_list_algorithms
mcrypt_module_close
Mcrypt Functions
PHP Manual

mcrypt_list_modes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_list_modes — Get an array of all supported modes

Description

array mcrypt_list_modes ([ string $lib_dir = ini_get("mcrypt.modes_dir") ] )

Gets the list of all supported modes in the lib_dir parameter.

Parameters

lib_dir

Specifies the directory where all modes are located. If not specifies, the value of the mcrypt.modes_dir php.ini directive is used.

Return Values

Returns an array with all the supported modes.

Examples

Example #1 mcrypt_list_modes() Example

<?php
    $modes = mcrypt_list_modes();

    foreach ($modes as $mode) {
        echo "$mode <br />\n";
    }
?>

The above example will produce a list with all supported algorithms in the default mode directory. If it is not set with the ini directive mcrypt.modes_dir, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt).

mcrypt_list_algorithms
mcrypt_module_close
Mcrypt Functions


Close the mcrypt module

mcrypt_list_modes
mcrypt_module_get_algo_block_size
Mcrypt Functions
PHP Manual

mcrypt_module_close

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_close — Close the mcrypt module

Description

bool mcrypt_module_close ( resource $td )

Closes the specified encryption handle.

Parameters

td

The encryption descriptor.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

mcrypt_list_modes
mcrypt_module_get_algo_block_size
Mcrypt Functions


Returns the blocksize of the specified algorithm

mcrypt_module_close
mcrypt_module_get_algo_key_size
Mcrypt Functions
PHP Manual

mcrypt_module_get_algo_block_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm

Description

int mcrypt_module_get_algo_block_size ( string $algorithm [, string $lib_dir ] )

Gets the blocksize of the specified algorithm.

Parameters

algorithm

The algorithm name.

lib_dir

This optional parameter can contain the location where the mode module is on the system.

Return Values

Returns the block size of the algorithm specified in bytes.

mcrypt_module_close
mcrypt_module_get_algo_key_size
Mcrypt Functions


Returns the maximum supported keysize of the opened mode

mcrypt_module_get_algo_block_size
mcrypt_module_get_supported_key_sizes
Mcrypt Functions
PHP Manual

mcrypt_module_get_algo_key_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode

Description

int mcrypt_module_get_algo_key_size ( string $algorithm [, string $lib_dir ] )

Gets the maximum supported keysize of the opened mode.

Parameters

algorithm

The algorithm name.

lib_dir

This optional parameter can contain the location where the mode module is on the system.

Return Values

This function returns the maximum supported key size of the algorithm specified in bytes.

mcrypt_module_get_algo_block_size
mcrypt_module_get_supported_key_sizes
Mcrypt Functions


Returns an array with the supported keysizes of the opened algorithm

mcrypt_module_get_algo_key_size
mcrypt_module_is_block_algorithm_mode
Mcrypt Functions
PHP Manual

mcrypt_module_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_module_get_supported_key_sizes ( string $algorithm [, string $lib_dir ] )

Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm.

Parameters

algorithm

The algorithm to used.

lib_dir

The optional lib_dir parameter can contain the location of where the algorithm module is on the system.

Return Values

Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm.

See Also

  • mcrypt_enc_get_supported_key_sizes() - Returns an array with the supported keysizes of the opened algorithm

mcrypt_module_get_algo_key_size
mcrypt_module_is_block_algorithm_mode
Mcrypt Functions


This function checks whether the specified algorithm is a block algorithm

mcrypt_module_is_block_algorithm_mode
mcrypt_module_is_block_mode
Mcrypt Functions
PHP Manual

mcrypt_module_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm

Description

bool mcrypt_module_is_block_algorithm ( string $algorithm [, string $lib_dir ] )

This function returns TRUE if the specified algorithm is a block algorithm, or FALSE is it is a stream algorithm.

Parameters

algorithm

The algorithm to check.

lib_dir

The optional lib_dir parameter can contain the location of where the algorithm module is on the system.

Return Values

This function returns TRUE if the specified algorithm is a block algorithm, or FALSE is it is a stream algorithm.

mcrypt_module_is_block_algorithm_mode
mcrypt_module_is_block_mode
Mcrypt Functions


Returns if the specified module is a block algorithm or not

mcrypt_module_get_supported_key_sizes
mcrypt_module_is_block_algorithm
Mcrypt Functions
PHP Manual

mcrypt_module_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not

Description

bool mcrypt_module_is_block_algorithm_mode ( string $mode [, string $lib_dir ] )

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb).

Parameters

mode

The mode to check.

lib_dir

The optional lib_dir parameter can contain the location of where the algorithm module is on the system.

Return Values

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb).

mcrypt_module_get_supported_key_sizes
mcrypt_module_is_block_algorithm
Mcrypt Functions


Returns if the specified mode outputs blocks or not

mcrypt_module_is_block_algorithm
mcrypt_module_open
Mcrypt Functions
PHP Manual

mcrypt_module_is_block_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not

Description

bool mcrypt_module_is_block_mode ( string $mode [, string $lib_dir ] )

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).

Parameters

mode

The mode to check.

lib_dir

The optional lib_dir parameter can contain the location of where the algorithm module is on the system.

Return Values

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).

mcrypt_module_is_block_algorithm
mcrypt_module_open
Mcrypt Functions


Opens the module of the algorithm and the mode to be used

mcrypt_module_is_block_mode
mcrypt_module_self_test
Mcrypt Functions
PHP Manual

mcrypt_module_open

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_open — Opens the module of the algorithm and the mode to be used

Description

resource mcrypt_module_open ( string $algorithm , string $algorithm_directory , string $mode , string $mode_directory )

This function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, e.g. "twofish" or is one of the MCRYPT_ciphername constants. The module is closed by calling mcrypt_module_close().

Parameters

algorithm

The algorithm to be used.

algorithm_directory

The algorithm_directory and mode_directory are used to locate the encryption modules. When you supply a directory name, it is used. When you set one of these to the empty string (""), the value set by the mcrypt.algorithms_dir or mcrypt.modes_dir ini-directive is used. When these are not set, the default directories that are used are the ones that were compiled in into libmcrypt (usually /usr/local/lib/libmcrypt).

mode

The mode to be used.

mode_directory

Return Values

Normally it returns an encryption descriptor, or FALSE on error.

Examples

Example #1 mcrypt_module_open() examples

<?php
    $td = mcrypt_module_open(MCRYPT_DES, '',
        MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');

    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
?>

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

Example #2 Using mcrypt_module_open() in encryption

<?php
    /* Open the cipher */
    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');

    /* Create the IV and determine the keysize length, use MCRYPT_RAND
     * on Windows instead */
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
    $ks = mcrypt_enc_get_key_size($td);

    /* Create key */
    $key = substr(md5('very secret key'), 0, $ks);

    /* Intialize encryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Encrypt data */
    $encrypted = mcrypt_generic($td, 'This is very important data');

    /* Terminate encryption handler */
    mcrypt_generic_deinit($td);

    /* Initialize encryption module for decryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic($td, $encrypted);

    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    /* Show string */
    echo trim($decrypted) . "\n";
?>

See Also

  • mcrypt_module_close() - Close the mcrypt module
  • mcrypt_generic() - This function encrypts data
  • mdecrypt_generic() - Decrypt data
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption
  • mcrypt_generic_deinit() - This function deinitializes an encryption module

mcrypt_module_is_block_mode
mcrypt_module_self_test
Mcrypt Functions


This function runs a self test on the specified module

mcrypt_module_open
mcrypt_ofb
Mcrypt Functions
PHP Manual

mcrypt_module_self_test

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_self_test — This function runs a self test on the specified module

Description

bool mcrypt_module_self_test ( string $algorithm [, string $lib_dir ] )

This function runs the self test on the algorithm specified.

Parameters

algorithm

The algorithm to test.

lib_dir

The optional lib_dir parameter can contain the location of where the algorithm module is on the system.

Return Values

The function returns TRUE if the self test succeeds, or FALSE when if fails.

Examples

Example #1 mcrypt_module_self_test() example

<?php
var_dump(mcrypt_module_self_test(MCRYPT_RIJNDAEL_128)) . "\n";
var_dump(mcrypt_module_self_test(MCRYPT_BOGUS_CYPHER));
?>

The above example will output:

bool(true)
bool(false)

mcrypt_module_open
mcrypt_ofb
Mcrypt Functions


Encrypt/decrypt data in OFB mode

mcrypt_module_self_test
mdecrypt_generic
Mcrypt Functions
PHP Manual

mcrypt_ofb

(PHP 4, PHP 5)

mcrypt_ofb — Encrypt/decrypt data in OFB mode

Description

string mcrypt_ofb ( int $cipher , string $key , string $data , int $mode , string $iv )
string mcrypt_ofb ( string $cipher , string $key , string $data , int $mode [, string $iv ] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_module_self_test
mdecrypt_generic
Mcrypt Functions


Decrypt data

mcrypt_ofb
Mhash
Mcrypt Functions
PHP Manual

mdecrypt_generic

(PHP 4 >= 4.0.2, PHP 5)

mdecrypt_generic — Decrypt data

Description

string mdecrypt_generic ( resource $td , string $data )

This function decrypts data. Note that the length of the returned string can in fact be longer then the unencrypted string, due to the padding of the data.

Parameters

td

An encryption descriptor returned by mcrypt_module_open()

data

Encrypted data.

Examples

Example #1 mdecrypt_generic() example

<?php
    /* Data */
    $key = 'this is a very long key, even too long for the cipher';
    $plain_text = 'very important data';

    /* Open module, and create IV */
    $td = mcrypt_module_open('des', '', 'ecb', '');
    $key = substr($key, 0, mcrypt_enc_get_key_size($td));
    $iv_size = mcrypt_enc_get_iv_size($td);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    /* Initialize encryption handle */
    if (mcrypt_generic_init($td, $key, $iv) != -1) {

        /* Encrypt data */
        $c_t = mcrypt_generic($td, $plain_text);
        mcrypt_generic_deinit($td);

        /* Reinitialize buffers for decryption */
        mcrypt_generic_init($td, $key, $iv);
        $p_t = mdecrypt_generic($td, $c_t);

        /* Clean up */
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
    }

    if (strncmp($p_t, $plain_text, strlen($plain_text)) == 0) {
        echo "ok\n";
    } else {
        echo "error\n";
    }
?>

The above example shows how to check if the data before the encryption is the same as the data after the decryption. It is very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.

The decryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

See Also

  • mcrypt_generic() - This function encrypts data
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption
  • mcrypt_generic_deinit() - This function deinitializes an encryption module

mcrypt_ofb
Mhash
Mcrypt Functions


Returns the peak of memory allocated by PHP

main
memory_get_usage
PHP Options/Info Functions
PHP Manual

memory_get_peak_usage

(PHP 5 >= 5.2.0)

memory_get_peak_usage — Returns the peak of memory allocated by PHP

Description

int memory_get_peak_usage ([ bool $real_usage = false ] )

Returns the peak of memory, in bytes, that's been allocated to your PHP script.

Parameters

real_usage

Set this to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is reported.

Return Values

Returns the memory peak in bytes.

Changelog

Version | Description
5.2.1 | Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 | real_usage was added.

See Also

  • memory_get_usage() - Returns the amount of memory allocated to PHP
  • memory_limit

main
memory_get_usage
PHP Options/Info Functions


Returns the amount of memory allocated to PHP

memory_get_peak_usage
php_ini_loaded_file
PHP Options/Info Functions
PHP Manual

memory_get_usage

(PHP 4 >= 4.3.2, PHP 5)

memory_get_usage — Returns the amount of memory allocated to PHP

Description

int memory_get_usage ([ bool $real_usage = false ] )

Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

Parameters

real_usage

Set this to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is reported.

Return Values

Returns the memory amount in bytes.

Changelog

Version | Description
5.2.1 | Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 | real_usage was added.

Examples

Example #1 A memory_get_usage() example

<?php
// This is only an example, the numbers below will
// differ depending on your system

echo memory_get_usage() . "\n"; // 36640

$a = str_repeat("Hello", 4242);

echo memory_get_usage() . "\n"; // 57960

unset($a);

echo memory_get_usage() . "\n"; // 36744

?>

See Also

  • memory_get_peak_usage() - Returns the peak of memory allocated by PHP
  • memory_limit

memory_get_peak_usage
php_ini_loaded_file
PHP Options/Info Functions


Compute hash

mhash_keygen_s2k
OpenSSL
Mhash Functions
PHP Manual

mhash

(PHP 4, PHP 5)

mhash — Compute hash

Description

string mhash ( int $hash , string $data [, string $key ] )

mhash() applies a hash function specified by hash to the data .

Parameters

hash

The hash id. One of the MHASH_XXX constants.

data

The user input, as a string.

key

If specified, the function will return the resulting HMAC instead. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode.

Return Values

Returns the resulting hash (also called digest) or HMAC as a string, or FALSE on errors.

mhash_keygen_s2k
OpenSSL
Mhash Functions


Get the highest available hash id

Mhash Functions
mhash_get_block_size
Mhash Functions
PHP Manual

mhash_count

(PHP 4, PHP 5)

mhash_count — Get the highest available hash id

Description

int mhash_count ( void )

Gets the highest available hash id.

Return Values

Returns the highest available hash id. Hashes are numbered from 0 to this hash id.

Examples

Example #1 Traversing all hashes

<?php

$nr = mhash_count();

for ($i = 0; $i <= $nr; $i++) {
    echo sprintf("The blocksize of %s is %d\n",
        mhash_get_hash_name($i),
        mhash_get_block_size($i));
}
?>

Mhash Functions
mhash_get_block_size
Mhash Functions


Get the block size of the specified hash

mhash_count
mhash_get_hash_name
Mhash Functions
PHP Manual

mhash_get_block_size

(PHP 4, PHP 5)

mhash_get_block_size — Get the block size of the specified hash

Description

int mhash_get_block_size ( int $hash )

Gets the size of a block of the specified hash .

Parameters

hash

The hash id. One of the MHASH_XXX constants.

Return Values

Returns the size in bytes or FALSE, if the hash does not exist.

Examples

Example #1 mhash_get_block_size() Example

<?php

echo mhash_get_block_size(MHASH_MD5); // 16

?>

mhash_count
mhash_get_hash_name
Mhash Functions


Get the name of the specified hash

mhash_get_block_size
mhash_keygen_s2k
Mhash Functions
PHP Manual

mhash_get_hash_name

(PHP 4, PHP 5)

mhash_get_hash_name — Get the name of the specified hash

Description

string mhash_get_hash_name ( int $hash )

Gets the name of the specified hash .

Parameters

hash

The hash id. One of the MHASH_XXX constants.

Return Values

Returns the name of the hash or FALSE, if the hash does not exist.

Examples

Example #1 mhash_get_hash_name() example

<?php

echo mhash_get_hash_name(MHASH_MD5); // MD5

?>

mhash_get_block_size
mhash_keygen_s2k
Mhash Functions


Generates a key

mhash_get_hash_name
mhash
Mhash Functions
PHP Manual

mhash_keygen_s2k

(PHP 4 >= 4.0.4, PHP 5)

mhash_keygen_s2k — Generates a key

Description

string mhash_keygen_s2k ( int $hash , string $password , string $salt , int $bytes )

Generates a key according to the hash given a user provided password .

This is the Salted S2K algorithm as specified in the OpenPGP document (» RFC 2440).

Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly recommended to use some kind of transformation (like this function) to the user supplied key.

Parameters

hash

The hash id used to create the key. One of the MHASH_XXX constants.

password

User supplied password.

salt

Must be different and random enough for every key you generate in order to create different keys. That salt must be known when you check the keys, thus it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be padded with zeros if you supply less bytes.

bytes

The key length, in bytes.

Return Values

Returns the generated key as a string, or FALSE on error.

mhash_get_hash_name
mhash
Mhash Functions


Return current Unix timestamp with microseconds

localtime
mktime
Date/Time Functions
PHP Manual

microtime

(PHP 4, PHP 5)

microtime — Return current Unix timestamp with microseconds

Description

mixed microtime ([ bool $get_as_float ] )

microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

Parameters

get_as_float

When called without the optional argument, this function returns the string "msec sec" where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and msec is the microseconds part. Both portions of the string are returned in units of seconds.

If the optional get_as_float is set to TRUE then a float (in seconds) is returned.

Changelog

Version | Description
5.0.0 | The get_as_float parameter was added.

Examples

Example #1 Timing script execution with microtime()

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

// Sleep for a while
usleep(100);

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

Example #2 Timing script execution in PHP 5

<?php
$time_start = microtime(true);

// Sleep for a while
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

See Also

  • time() - Return current Unix timestamp

localtime
mktime
Date/Time Functions


Detect MIME Content-type for a file (deprecated)

finfo_set_flags
Filesystem
Fileinfo Functions
PHP Manual

mime_content_type

(PHP 4 >= 4.3.0, PHP 5)

mime_content_type — Detect MIME Content-type for a file (deprecated)

Description

string mime_content_type ( string $filename )

Returns the MIME content type for a file as determined by using information from the magic.mime file.

Parameters

filename

Path to the tested file.

Return Values

Returns the content type in MIME format, like text/plain or application/octet-stream.

Notes

Warning

This function has been deprecated as the PECL extension Fileinfo provides the same functionality (and more) in a much cleaner way.

Examples

Example #1 mime_content_type() Example

<?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?>

The above example will output:

image/gif
text/plain

See Also

  • Fileinfo for a replacement

finfo_set_flags
Filesystem
Fileinfo Functions


Find lowest value

max
mt_getrandmax
Math Functions
PHP Manual

min

(PHP 4, PHP 5)

min — Find lowest value

Description

mixed min ( array $values )
mixed min ( mixed $value1 , mixed $value2 [, mixed $value3... ] )

If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.

Note: PHP will evaluate a non-numeric string as 0 if compared to integer, but still return the string if it's seen as the numerically lowest value. If multiple arguments evaluate to 0, min() will return the lowest alphanumerical string value if any strings are given, else a numeric 0 is returned.

Parameters

values

An array containing the values.

Return Values

min() returns the numerically lowest of the parameter values.

Examples

Example #1 Example uses of min()

<?php
echo min(2, 3, 1, 6, 7);  // 1
echo min(array(2, 4, 5)); // 2

echo min(0, 'hello');     // 0
echo min('hello', 0);     // hello
echo min('hello', -1);    // -1

// With multiple arrays, min compares from left to right
// so in our example: 2 == 2, but 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)

// If both an array and non-array are given, the array
// is never returned as it's considered the largest
$val = min('string', array(2, 5, 7), 42);   // string
?>

See Also

  • max() - Find highest value
  • count() - Count all elements in an array, or properties in an object

max
mt_getrandmax
Math Functions


Returns the action flag for keyPress(char)

Ming Functions
ming_setcubicthreshold
Ming Functions
PHP Manual

ming_keypress

(PHP 5 <= 5.3.0, PECL ming SVN)

ming_keypress — Returns the action flag for keyPress(char)

Description

int ming_keypress ( string $char )
Warning

This function is currently not documented; only its argument list is available.

Ming Functions
ming_setcubicthreshold
Ming Functions


Set cubic threshold

ming_keypress
ming_setscale
Ming Functions
PHP Manual

ming_setcubicthreshold

(PHP 4 >= 4.0.5, PHP 5, PECL ming SVN)

ming_setcubicthreshold — Set cubic threshold

Description

void ming_setcubicthreshold ( int $threshold )

Sets the threshold error for drawing cubic beziers.

Parameters

threshold

The Threshold. Lower is more accurate, hence larger file size.

Return Values

No value is returned.

ming_keypress
ming_setscale
Ming Functions


Set the global scaling factor.

ming_setcubicthreshold
ming_setswfcompression
Ming Functions
PHP Manual

ming_setscale

(PHP 4 >= 4.0.5, PHP 5, PECL ming SVN)

ming_setscale — Set the global scaling factor.

Description

void ming_setscale ( float $scale )

Sets the scale of the output SWF. Inside the SWF file, coordinates are measured in TWIPS, rather than PIXELS. There are 20 TWIPS in 1 pixel.

Parameters

scale

The scale to be set.

Return Values

No value is returned.

ming_setcubicthreshold
ming_setswfcompression
Ming Functions


Sets the SWF output compression

ming_setscale
ming_useconstants
Ming Functions
PHP Manual

ming_setswfcompression

(PHP 5.2.1-5.3.0, PECL ming SVN)

ming_setswfcompression — Sets the SWF output compression

Description

void ming_setswfcompression ( int $level )

Sets the SWF output compression level.

Parameters

level

The new compression level. Should be a value between 1 and 9 inclusive.

Return Values

No value is returned.

ming_setscale
ming_useconstants
Ming Functions


Use constant pool

ming_setswfcompression
ming_useswfversion
Ming Functions
PHP Manual

ming_useconstants

(PHP 5 <= 5.3.0, PECL ming SVN)

ming_useconstants — Use constant pool

Description

void ming_useconstants ( int $use )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

ming_setswfcompression
ming_useswfversion
Ming Functions


Sets the SWF version

ming_useconstants
SWFAction
Ming Functions
PHP Manual

ming_useswfversion

(PHP 4 >= 4.2.0, PHP 5 <= 5.3.0, PECL ming SVN)

ming_useswfversion — Sets the SWF version

Description

void ming_useswfversion ( int $version )

Sets the SWF version to be used in the movie. This affect the bahaviour of Action Script.

Parameters

version

SWF version to use.

Return Values

No value is returned.

Examples

Example #1 ming_useswfversion() example

<?php

$movie = new SWFMovie();
ming_useswfversion(4); // Flash 4

?>

ming_useconstants
SWFAction
Ming Functions


Makes directory

lstat
move_uploaded_file
Filesystem Functions
PHP Manual

mkdir

(PHP 4, PHP 5)

mkdir — Makes directory

Description

bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

Attempts to create the directory specified by pathname.

Parameters

pathname

The directory path.

mode

The mode is 0777 by default, which means the widest possible access. For more information on modes, read the details on the chmod() page.

Note: mode is ignored on Windows.

Note that you probably want to specify the mode as an octal number, which means it should have a leading zero. The mode is also modified by the current umask, which you can change using umask().

recursive

Default to FALSE.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Stream Functions.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | The recursive parameter was added
5.0.0 | As of PHP 5.0.0 mkdir() can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support mkdir()
4.2.0 | The mode parameter became optional.

Examples

Example #1 mkdir() example

<?php
mkdir("/path/to/my/dir", 0700);
?>

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • rmdir() - Removes directory

lstat
move_uploaded_file
Filesystem Functions


Get Unix timestamp for a date

microtime
strftime
Date/Time Functions
PHP Manual

mktime

(PHP 4, PHP 5)

mktime — Get Unix timestamp for a date

Description

 int mktime
  ([ int $hour = date("H")
 [, int $minute = date("i")
 [, int $second = date("s")
 [, int $month = date("n")
 [, int $day = date("j")
 [, int $year = date("Y")
 [, int $is_dst = -1
]]]]]]] )

Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.

Notes

Note: As of PHP 5.1, when called with no arguments, mktime() throws an E_STRICT notice: use the time() function instead.

Parameters

hour

The number of the hour.

minute

The number of the minute.

second

The number of seconds past the minute.

month

The number of the month.

day

The number of the day.

year

The number of the year, may be a two or four digit value, with values between 0-69 mapping to 2000-2069 and 70-100 to 1970-2000. On systems where time_t is a 32bit signed integer, as most common today, the valid range for year is somewhere between 1901 and 2038. However, before PHP 5.1.0 this range was limited from 1970 to 2038 on some systems (e.g. Windows).

is_dst

This parameter can be set to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) if it is unknown whether the time is within daylight savings time or not. If it's unknown, PHP tries to figure it out itself. This can cause unexpected (but not incorrect) results. Some times are invalid if DST is enabled on the system PHP is running on or is_dst is set to 1. If DST is enabled in e.g. 2:00, all times between 2:00 and 3:00 are invalid and mktime() returns an undefined (usually negative) value. Some systems (e.g. Solaris 8) enable DST at midnight so time 0:30 of the day when DST is enabled is evaluated as 23:30 of the previous day.

Note: As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone handling features should be used instead.

Return Values

mktime() returns the Unix timestamp of the arguments given. If the arguments are invalid, the function returns FALSE (before PHP 5.1 it returned -1).

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.3.0 | mktime() now throws E_DEPRECATED notice if the is_dst parameter is used.
5.1.0 | The is_dst parameter became deprecated. Made the function return FALSE on error, instead of -1. Fixed the function to accept the year, month and day to be all passed as zero.
5.1.0 | When called with no arguments, mktime() throws E_STRICT notice. Use the time() function instead.
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 mktime() basic example

<?php
// Set the default timezone to use. Available as of PHP 5.1
date_default_timezone_set('UTC');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

// Prints something like: 2006-04-05T01:02:03+00:00
echo date('c', mktime(1, 2, 3, 4, 5, 2006));
?>

Example #2 mktime() example

mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input. For example, each of the following lines produces the string "Jan-01-1998".

<?php
echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 98));
?>

Example #3 Last day of next month

The last day of any given month can be expressed as the "0" day of the next month, not the -1 day. Both of the following examples will produce the string "The last day in Feb 2000 is: 29".

<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
?>

Notes

Caution

Before PHP 5.1.0, negative timestamps were not supported under any known version of Windows and some other systems as well. Therefore the range of valid years was limited to 1970 through 2038.

See Also

  • gmmktime() - Get Unix timestamp for a GMT date
  • date() - Format a local time/date
  • time() - Return current Unix timestamp

microtime
strftime
Date/Time Functions


Moves an uploaded file to a new location

mkdir
parse_ini_file
Filesystem Functions
PHP Manual

move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5)

move_uploaded_file — Moves an uploaded file to a new location

Description

bool move_uploaded_file ( string $filename , string $destination )

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination .

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

Parameters

filename

The filename of the uploaded file.

destination

The destination of the moved file.

Return Values

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

Examples

Example #1 Uploading multiple files

<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>

Notes

Note: move_uploaded_file() is both safe mode and open_basedir aware. However, restrictions are placed only on the destination path as to allow the moving of uploaded files in which filename may conflict with such restrictions. move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved.

Warning

If the destination file already exists, it will be overwritten.

See Also

  • is_uploaded_file() - Tells whether the file was uploaded via HTTP POST
  • See Handling file uploads for a simple usage example

mkdir
parse_ini_file
Filesystem Functions


Create or attach to a message queue

ftok
msg_queue_exists
Semaphore Functions
PHP Manual

msg_get_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_get_queue — Create or attach to a message queue

Description

resource msg_get_queue ( int $key [, int $perms ] )

msg_get_queue() returns an id that can be used to access the System V message queue with the given key . The first call creates the message queue with the optional perms . A second call to msg_get_queue() for the same key will return a different message queue identifier, but both identifiers access the same underlying message queue.

Parameters

key

Message queue numeric ID

perms

Queue permissions. Default to 0666. If the message queue already exists, the perms will be ignored.

Return Values

Returns a resource handle that can be used to access the System V message queue.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_send() - Send a message to a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

ftok
msg_queue_exists
Semaphore Functions


Check whether a message queue exists

msg_get_queue
msg_receive
Semaphore Functions
PHP Manual

msg_queue_exists

(PHP 5 >= 5.3.0)

msg_queue_exists — Check whether a message queue exists

Description

bool msg_queue_exists ( int $key )

Checks whether the message queue key exists.

Parameters

key

Queue key.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure

msg_get_queue
msg_receive
Semaphore Functions


Receive a message from a message queue

msg_queue_exists
msg_remove_queue
Semaphore Functions
PHP Manual

msg_receive

(PHP 4 >= 4.3.0, PHP 5)

msg_receive — Receive a message from a message queue

Description

bool msg_receive ( resource $queue , int $desiredmsgtype , int &$msgtype , int $maxsize , mixed &$message [, bool $unserialize = true [, int $flags [, int &$errorcode ]]] )

msg_receive() will receive the first message from the specified queue of the type specified by desiredmsgtype .

Parameters

queue

desiredmsgtype

If desiredmsgtype is 0, the message from the front of the queue is returned. If desiredmsgtype is greater than 0, then the first message of that type is returned. If desiredmsgtype is less than 0, the first message on the queue with the lowest type less than or equal to the absolute value of desiredmsgtype will be read. If no messages match the criteria, your script will wait until a suitable message arrives on the queue. You can prevent the script from blocking by specifying MSG_IPC_NOWAIT in the flags parameter.

msgtype

The type of the message that was received will be stored in this parameter.

maxsize

The maximum size of message to be accepted is specified by the maxsize ; if the message in the queue is larger than this size the function will fail (unless you set flags as described below).

message

The received message will be stored in message , unless there were errors receiving the message.

unserialize

If set to TRUE, the message is treated as though it was serialized using the same mechanism as the session module. The message will be unserialized and then returned to your script. This allows you to easily receive arrays or complex object structures from other PHP scripts, or if you are using the WDDX serializer, from any WDDX compatible source.

If unserialize is FALSE, the message will be returned as a binary-safe string.

flags

The optional flags allows you to pass flags to the low-level msgrcv system call. It defaults to 0, but you may specify one or more of the following values (by adding or ORing them together).

Flag values for msg_receive
MSG_IPC_NOWAIT | If there are no messages of the desiredmsgtype , return immediately and do not wait. The function will fail and return an integer value corresponding to MSG_ENOMSG.
MSG_EXCEPT | Using this flag in combination with a desiredmsgtype greater than 0 will cause the function to receive the first message that is not equal to desiredmsgtype .
MSG_NOERROR | If the message is longer than maxsize , setting this flag will truncate the message to maxsize and will not signal an error.

errorcode

If the function fails, the optional errorcode will be set to the value of the system errno variable.

Return Values

Returns TRUE on success or FALSE on failure.

Upon successful completion the message queue data structure is updated as follows: msg_lrpid is set to the process-ID of the calling process, msg_qnum is decremented by 1 and msg_rtime is set to the current time.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_send() - Send a message to a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

msg_queue_exists
msg_remove_queue
Semaphore Functions


Destroy a message queue

msg_receive
msg_send
Semaphore Functions
PHP Manual

msg_remove_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_remove_queue — Destroy a message queue

Description

bool msg_remove_queue ( resource $queue )

msg_remove_queue() destroys the message queue specified by the queue . Only use this function when all processes have finished working with the message queue and you need to release the system resources held by it.

Parameters

queue

Message queue resource handle

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msg_get_queue() - Create or attach to a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

msg_receive
msg_send
Semaphore Functions


Send a message to a message queue

msg_remove_queue
msg_set_queue
Semaphore Functions
PHP Manual

msg_send

(PHP 4 >= 4.3.0, PHP 5)

msg_send — Send a message to a message queue

Description

bool msg_send ( resource $queue , int $msgtype , mixed $message [, bool $serialize [, bool $blocking [, int &$errorcode ]]] )

msg_send() sends a message of type msgtype (which MUST be greater than 0) to the message queue specified by queue .

Parameters

queue

msgtype

message

serialize

The optional serialize controls how the message is sent. serialize defaults to TRUE which means that the message is serialized using the same mechanism as the session module before being sent to the queue. This allows complex arrays and objects to be sent to other PHP scripts, or if you are using the WDDX serializer, to any WDDX compatible client.

blocking

If the message is too large to fit in the queue, your script will wait until another process reads messages from the queue and frees enough space for your message to be sent. This is called blocking; you can prevent blocking by setting the optional blocking parameter to FALSE, in which case msg_send() will immediately return FALSE if the message is too big for the queue, and set the optional errorcode to MSG_EAGAIN, indicating that you should try to send your message again a little later on.

errorcode

Return Values

Returns TRUE on success or FALSE on failure.

Upon successful completion the message queue data structure is updated as follows: msg_lspid is set to the process-ID of the calling process, msg_qnum is incremented by 1 and msg_stime is set to the current time.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

msg_remove_queue
msg_set_queue
Semaphore Functions


Set information in the message queue data structure

msg_send
msg_stat_queue
Semaphore Functions
PHP Manual

msg_set_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_set_queue — Set information in the message queue data structure

Description

bool msg_set_queue ( resource $queue , array $data )

msg_set_queue() allows you to change the values of the msg_perm.uid, msg_perm.gid, msg_perm.mode and msg_qbytes fields of the underlying message queue data structure.

Changing the data structure will require that PHP be running as the same user that created the queue, owns the queue (as determined by the existing msg_perm.xxx fields), or be running with root privileges. root privileges are required to raise the msg_qbytes values above the system defined limit.

Parameters

queue

Message queue resource handle

data

You specify the values you require by setting the value of the keys that you require in the data array.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_get_queue() - Create or attach to a message queue

msg_send
msg_stat_queue
Semaphore Functions


Returns information from the message queue data structure

msg_set_queue
sem_acquire
Semaphore Functions
PHP Manual

msg_stat_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_stat_queue — Returns information from the message queue data structure

Description

array msg_stat_queue ( resource $queue )

msg_stat_queue() returns the message queue meta data for the message queue specified by the queue . This is useful, for example, to determine which process sent the message that was just received.

Parameters

queue

Message queue resource handle

Return Values

The return value is an array whose keys and values have the following meanings:

Array structure for msg_stat_queue
msg_perm.uid | The uid of the owner of the queue.
msg_perm.gid | The gid of the owner of the queue.
msg_perm.mode | The file access mode of the queue.
msg_stime | The time that the last message was sent to the queue.
msg_rtime | The time that the last message was received from the queue.
msg_ctime | The time that the queue was last changed.
msg_qnum | The number of messages waiting to be read from the queue.
msg_qbytes | The maximum number of bytes allowed in one message queue. On Linux, this value may be read and modified via /proc/sys/kernel/msgmnb.
msg_lspid | The pid of the process that sent the last message to the queue.
msg_lrpid | The pid of the process that received the last message from the queue.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_get_queue() - Create or attach to a message queue
  • msg_set_queue() - Set information in the message queue data structure

msg_set_queue
sem_acquire
Semaphore Functions


Alias of msql_db_query

msql_tablename
Mssql
mSQL Functions
PHP Manual

msql

(PHP 4, PHP 5)

msql — Alias of msql_db_query()

Description

This function is an alias of msql_db_query().

msql_tablename
Mssql
mSQL Functions


Returns number of affected rows

mSQL Functions
msql_close
mSQL Functions
PHP Manual

msql_affected_rows

(PHP 4, PHP 5)

msql_affected_rows — Returns number of affected rows

Description

int msql_affected_rows ( resource $result )

Returns number of affected rows by the last SELECT, UPDATE or DELETE query associated with result .

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns the number of affected rows on success, or FALSE on error.

See Also

  • msql_query() - Send mSQL query

mSQL Functions
msql_close
mSQL Functions


Close mSQL connection

msql_affected_rows
msql_connect
mSQL Functions
PHP Manual

msql_close

(PHP 4, PHP 5)

msql_close — Close mSQL connection

Description

bool msql_close ([ resource $link_identifier ] )

msql_close() closes the non-persistent connection to the mSQL server that's associated with the specified link identifier.

Using msql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

Parameters

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_connect() - Open mSQL connection
  • msql_pconnect() - Open persistent mSQL connection

msql_affected_rows
msql_connect
mSQL Functions


Open mSQL connection

msql_close
msql_create_db
mSQL Functions
PHP Manual

msql_connect

(PHP 4, PHP 5)

msql_connect — Open mSQL connection

Description

resource msql_connect ([ string $hostname ] )

msql_connect() establishes a connection to a mSQL server.

In case a second call is made to msql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling msql_close().

Parameters

hostname

The hostname can also include a port number. e.g. hostname,port.

If not specified, the connection is established by the means of a Unix domain socket, being then more efficient then a localhost TCP socket connection.

Note: While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.

Return Values

Returns a positive mSQL link identifier on success, or FALSE on error.

See Also

  • msql_pconnect() - Open persistent mSQL connection
  • msql_close() - Close mSQL connection

msql_close
msql_create_db
mSQL Functions


Create mSQL database

msql_connect
msql_createdb
mSQL Functions
PHP Manual

msql_create_db

(PHP 4, PHP 5)

msql_create_db — Create mSQL database

Description

bool msql_create_db ( string $database_name [, resource $link_identifier ] )

msql_create_db() attempts to create a new database on the mSQL server.

Parameters

database_name

The name of the mSQL database.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_drop_db() - Drop (delete) mSQL database

msql_connect
msql_createdb
mSQL Functions


Alias of msql_create_db

msql_create_db
msql_data_seek
mSQL Functions
PHP Manual

msql_createdb

(PHP 4, PHP 5)

msql_createdb — Alias of msql_create_db()

Description

This function is an alias of: msql_create_db().

msql_create_db
msql_data_seek
mSQL Functions


Move internal row pointer

msql_createdb
msql_db_query
mSQL Functions
PHP Manual

msql_data_seek

(PHP 4, PHP 5)

msql_data_seek — Move internal row pointer

Description

bool msql_data_seek ( resource $result , int $row_number )

msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified query identifier to point to the specified row number. The next call to msql_fetch_row() would return that row.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

row_number

The seeked row number.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_fetch_array() - Fetch row as array
  • msql_fetch_object() - Fetch row as object
  • msql_fetch_row() - Get row as enumerated array
  • msql_result() - Get result data

msql_createdb
msql_db_query
mSQL Functions


Send mSQL query

msql_data_seek
msql_dbname
mSQL Functions
PHP Manual

msql_db_query

(PHP 4, PHP 5)

msql_db_query — Send mSQL query

Description

resource msql_db_query ( string $database , string $query [, resource $link_identifier ] )

msql_db_query() selects a database and executes a query on it.

Parameters

database

The name of the mSQL database.

query

The SQL query.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a positive mSQL query identifier to the query result, or FALSE on error.

See Also

  • msql_query() - Send mSQL query

msql_data_seek
msql_dbname
mSQL Functions


Alias of msql_result

msql_db_query
msql_drop_db
mSQL Functions
PHP Manual

msql_dbname

(PHP 4, PHP 5)

msql_dbname — Alias of msql_result()

Description

This function is an alias of: msql_result().

msql_db_query
msql_drop_db
mSQL Functions


Drop (delete) mSQL database

msql_dbname
msql_error
mSQL Functions
PHP Manual

msql_drop_db

(PHP 4, PHP 5)

msql_drop_db — Drop (delete) mSQL database

Description

bool msql_drop_db ( string $database_name [, resource $link_identifier ] )

msql_drop_db() attempts to drop (remove) a database from the mSQL server.

Parameters

database_name

The name of the database.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_create_db() - Create mSQL database

msql_dbname
msql_error
mSQL Functions


Returns error message of last msql call

msql_drop_db
msql_fetch_array
mSQL Functions
PHP Manual

msql_error

(PHP 4, PHP 5)

msql_error — Returns error message of last msql call

Description

string msql_error ( void )

msql_error() returns the last issued error by the mSQL server. Note that only the last error message is accessible with msql_error().

Return Values

The last error message or an empty string if no error was issued.

msql_drop_db
msql_fetch_array
mSQL Functions


Fetch row as array

msql_error
msql_fetch_field
mSQL Functions
PHP Manual

msql_fetch_array

(PHP 4, PHP 5)

msql_fetch_array — Fetch row as array

Description

array msql_fetch_array ( resource $result [, int $result_type ] )

msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

result_type

A constant that can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH with MSQL_BOTH being the default.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 msql_fetch_array() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo $row['id'] . ': ' . $row['name'] . "\n";
}

msql_free_result($result);
?>

Changelog

Version | Description
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

  • msql_fetch_row() - Get row as enumerated array
  • msql_fetch_object() - Fetch row as object
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data

msql_error
msql_fetch_field
mSQL Functions


Get field information

msql_fetch_array
msql_fetch_object
mSQL Functions
PHP Manual

msql_fetch_field

(PHP 4, PHP 5)

msql_fetch_field — Get field information

Description

object msql_fetch_field ( resource $result [, int $field_offset ] )

msql_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The field offset. If not specified, the next field that wasn't yet retrieved by msql_fetch_field() is retrieved.

Return Values

Returns an object containing field information. The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • not_null - 1 if the column cannot be NULL

  • unique - 1 if the column is a unique key

  • type - the type of the column

See Also

  • msql_field_seek() - Set field offset

msql_fetch_array
msql_fetch_object
mSQL Functions


Fetch row as object

msql_fetch_field
msql_fetch_row
mSQL Functions
PHP Manual

msql_fetch_object

(PHP 4, PHP 5)

msql_fetch_object — Fetch row as object

Description

object msql_fetch_object ( resource $result )

msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 msql_fetch_object() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_object($result, MSQL_ASSOC)) {
    echo $row->id . ': ' . $row->name . "\n";
}

msql_free_result($result);
?>

Changelog

Version | Description
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

  • msql_fetch_array() - Fetch row as array
  • msql_fetch_row() - Get row as enumerated array
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data

msql_fetch_field
msql_fetch_row
mSQL Functions


Get row as enumerated array

msql_fetch_object
msql_field_flags
mSQL Functions
PHP Manual

msql_fetch_row

(PHP 4, PHP 5)

msql_fetch_row — Get row as enumerated array

Description

array msql_fetch_row ( resource $result )

msql_fetch_row() fetches one row of data from the result associated with the specified query identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to msql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 msql_fetch_row() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_row($result)) {
    echo $row[0] . ': ' . $row[1] . "\n";
}

msql_free_result($result);
?>

Changelog

Version | Description
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

  • msql_fetch_array() - Fetch row as array
  • msql_fetch_object() - Fetch row as object
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data

msql_fetch_object
msql_field_flags
mSQL Functions


Get field flags

msql_fetch_row
msql_field_len
mSQL Functions
PHP Manual

msql_field_flags

(PHP 4, PHP 5)

msql_field_flags — Get field flags

Description

string msql_field_flags ( resource $result , int $field_offset )

msql_field_flags() returns the field flags of the specified field.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

Returns a string containing the field flags of the specified key. This can be: primary key not null, not null, primary key, unique not null or unique.

msql_fetch_row
msql_field_len
mSQL Functions


Get field length

msql_field_flags
msql_field_name
mSQL Functions
PHP Manual

msql_field_len

(PHP 4, PHP 5)

msql_field_len — Get field length

Description

int msql_field_len ( resource $result , int $field_offset )

msql_field_len() returns the length of the specified field.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

Returns the length of the specified field or FALSE on error.

msql_field_flags
msql_field_name
mSQL Functions


Get the name of the specified field in a result

msql_field_len
msql_field_seek
mSQL Functions
PHP Manual

msql_field_name

(PHP 4, PHP 5)

msql_field_name — Get the name of the specified field in a result

Description

string msql_field_name ( resource $result , int $field_offset )

msql_field_name() gets the name of the specified field index.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

The name of the field or FALSE on failure.

See Also

  • msql_field_len() - Get field length

msql_field_len
msql_field_seek
mSQL Functions


Set field offset

msql_field_name
msql_field_table
mSQL Functions
PHP Manual

msql_field_seek

(PHP 4, PHP 5)

msql_field_seek — Set field offset

Description

bool msql_field_seek ( resource $result , int $field_offset )

Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_fetch_field() - Get field information

msql_field_name
msql_field_table
mSQL Functions


Get table name for field

msql_field_seek
msql_field_type
mSQL Functions
PHP Manual

msql_field_table

(PHP 4, PHP 5)

msql_field_table — Get table name for field

Description

int msql_field_table ( resource $result , int $field_offset )

Returns the name of the table that the specified field is in.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

The name of the table on success or FALSE on failure.

msql_field_seek
msql_field_type
mSQL Functions


Get field type

msql_field_table
msql_fieldflags
mSQL Functions
PHP Manual

msql_field_type

(PHP 4, PHP 5)

msql_field_type — Get field type

Description

string msql_field_type ( resource $result , int $field_offset )

msql_field_type() gets the type of the specified field index.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

The type of the field. One of int, char, real, ident, null or unknown. This functions will return FALSE on failure.

msql_field_table
msql_fieldflags
mSQL Functions


Alias of msql_field_flags

msql_field_type
msql_fieldlen
mSQL Functions
PHP Manual

msql_fieldflags

(PHP 4, PHP 5)

msql_fieldflags — Alias of msql_field_flags()

Description

This function is an alias of msql_field_flags().

msql_field_type
msql_fieldlen
mSQL Functions


Alias of msql_field_len

msql_fieldflags
msql_fieldname
mSQL Functions
PHP Manual

msql_fieldlen

(PHP 4, PHP 5)

msql_fieldlen — Alias of msql_field_len()

Description

This function is an alias of msql_field_len().

msql_fieldflags
msql_fieldname
mSQL Functions


Alias of msql_field_name

msql_fieldlen
msql_fieldtable
mSQL Functions
PHP Manual

msql_fieldname

(PHP 4, PHP 5)

msql_fieldname — Alias of msql_field_name()

Description

This function is an alias of msql_field_name().

msql_fieldlen
msql_fieldtable
mSQL Functions


Alias of msql_field_table

msql_fieldname
msql_fieldtype
mSQL Functions
PHP Manual

msql_fieldtable

(PHP 4, PHP 5)

msql_fieldtable — Alias of msql_field_table()

Description

This function is an alias of msql_field_table().

msql_fieldname
msql_fieldtype
mSQL Functions


Alias of msql_field_type

msql_fieldtable
msql_free_result
mSQL Functions
PHP Manual

msql_fieldtype

(PHP 4, PHP 5)

msql_fieldtype — Alias of msql_field_type()

Description

This function is an alias of msql_field_type().

msql_fieldtable
msql_free_result
mSQL Functions


Free result memory

msql_fieldtype
msql_list_dbs
mSQL Functions
PHP Manual

msql_free_result

(PHP 4, PHP 5)

msql_free_result — Free result memory

Description

bool msql_free_result ( resource $result )

msql_free_result() frees the memory associated with query_identifier . When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns TRUE on success or FALSE on failure.

msql_fieldtype
msql_list_dbs
mSQL Functions


List mSQL databases on server

msql_free_result
msql_list_fields
mSQL Functions
PHP Manual

msql_list_dbs

(PHP 4, PHP 5)

msql_list_dbs — List mSQL databases on server

Description

resource msql_list_dbs ([ resource $link_identifier ] )

msql_list_tables() lists the databases available on the specified link_identifier .

Parameters

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

See Also

  • msql_list_tables() - List tables in an mSQL database
  • msql_list_fields() - List result fields

msql_free_result
msql_list_fields
mSQL Functions


List result fields

msql_list_dbs
msql_list_tables
mSQL Functions
PHP Manual

msql_list_fields

(PHP 4, PHP 5)

msql_list_fields — List result fields

Description

resource msql_list_fields ( string $database , string $tablename [, resource $link_identifier ] )

msql_list_fields() returns information about the given table.

Parameters

database

The name of the database.

tablename

The name of the table.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

See Also

  • msql_list_tables() - List tables in an mSQL database
  • msql_list_dbs() - List mSQL databases on server

msql_list_dbs
msql_list_tables
mSQL Functions


List tables in an mSQL database

msql_list_fields
msql_num_fields
mSQL Functions
PHP Manual

msql_list_tables

(PHP 4, PHP 5)

msql_list_tables — List tables in an mSQL database

Description

resource msql_list_tables ( string $database [, resource $link_identifier ] )

msql_list_tables() lists the tables on the specified database .

Parameters

database

The name of the database.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

See Also

  • msql_list_fields() - List result fields
  • msql_list_dbs() - List mSQL databases on server

msql_list_fields
msql_num_fields
mSQL Functions


Get number of fields in result

msql_list_tables
msql_num_rows
mSQL Functions
PHP Manual

msql_num_fields

(PHP 4, PHP 5)

msql_num_fields — Get number of fields in result

Description

int msql_num_fields ( resource $result )

msql_num_fields() returns the number of fields in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns the number of fields in the result set.

See Also

  • msql_query() - Send mSQL query
  • msql_fetch_field() - Get field information
  • msql_num_rows() - Get number of rows in result

msql_list_tables
msql_num_rows
mSQL Functions


Get number of rows in result

msql_num_fields
msql_numfields
mSQL Functions
PHP Manual

msql_num_rows

(PHP 4, PHP 5)

msql_num_rows — Get number of rows in result

Description

int msql_num_rows ( resource $query_identifier )

msql_num_rows() returns the number of rows in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns the number of rows in the result set.

See Also

  • msql_num_fields() - Get number of fields in result

msql_num_fields
msql_numfields
mSQL Functions


Alias of msql_num_fields

msql_num_rows
msql_numrows
mSQL Functions
PHP Manual

msql_numfields

(PHP 4, PHP 5)

msql_numfields — Alias of msql_num_fields()

Description

This function is an alias of msql_num_fields().

msql_num_rows
msql_numrows
mSQL Functions


Alias of msql_num_rows

msql_numfields
msql_pconnect
mSQL Functions
PHP Manual

msql_numrows

(PHP 4, PHP 5)

msql_numrows — Alias of msql_num_rows()

Description

This function is an alias of msql_num_rows().

msql_numfields
msql_pconnect
mSQL Functions


Open persistent mSQL connection

msql_numrows
msql_query
mSQL Functions
PHP Manual

msql_pconnect

(PHP 4, PHP 5)

msql_pconnect — Open persistent mSQL connection

Description

resource msql_pconnect ([ string $hostname ] )

msql_pconnect() acts very much like msql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (msql_close() will not close links established by this function).

Parameters

hostname

The hostname can also include a port number. e.g. hostname,port.

If not specified, the connection is established by the means of a Unix domain socket, being more efficient than a localhost TCP socket connection.

Note: While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.

Return Values

Returns a positive mSQL link identifier on success, or FALSE on error.

See Also

  • msql_connect() - Open mSQL connection
  • msql_close() - Close mSQL connection

msql_numrows
msql_query
mSQL Functions


Send mSQL query

msql_pconnect
msql_regcase
mSQL Functions
PHP Manual

msql_query

(PHP 4, PHP 5)

msql_query — Send mSQL query

Description

resource msql_query ( string $query [, resource $link_identifier ] )

msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

The SQL query.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a positive mSQL query identifier on success, or FALSE on error.

Examples

Example #1 msql_query() example

<?php
$link = msql_connect("dbserver")
   or die("unable to connect to msql server: " . msql_error());
msql_select_db("db", $link)
   or die("unable to select database 'db': " . msql_error());

$result = msql_query("SELECT * FROM table WHERE id=1", $link);
if (!$result) {
   die("query failed: " . msql_error());
}

while ($row = msql_fetch_array($result)) {
    echo $row["id"];
}
?>

See Also

  • msql_db_query() - Send mSQL query
  • msql_select_db() - Select mSQL database
  • msql_connect() - Open mSQL connection

msql_pconnect
msql_regcase
mSQL Functions


Alias of sql_regcase

msql_query
msql_result
mSQL Functions
PHP Manual

msql_regcase

(PHP 4, PHP 5)

msql_regcase — Alias of sql_regcase()

Description

This function is an alias of sql_regcase().

msql_query
msql_result
mSQL Functions


Get result data

msql_regcase
msql_select_db
mSQL Functions
PHP Manual

msql_result

(PHP 4, PHP 5)

msql_result — Get result data

Description

string msql_result ( resource $result , int $row [, mixed $field ] )

msql_result() returns the contents of one cell from a mSQL result set.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they are often much quicker than msql_result().

Recommended high-performance alternatives:
msql_fetch_row(),
msql_fetch_array(), and
msql_fetch_object().

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

row

The row offset.

field

Can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname.). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.

Note: Specifying a numeric field offset is much quicker than specifying a fieldname or tablename.fieldname.

Return Values

Returns the contents of the cell at the row and offset in the specified mSQL result set.

msql_regcase
msql_select_db
mSQL Functions


Select mSQL database

msql_result
msql_tablename
mSQL Functions
PHP Manual

msql_select_db

(PHP 4, PHP 5)

msql_select_db — Select mSQL database

Description

bool msql_select_db ( string $database_name [, resource $link_identifier ] )

msql_select_db() sets the current active database on the server that's associated with the specified link_identifier .

Subsequent calls to msql_query() will be made on the active database.

Parameters

database_name

The database name.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_connect() - Open mSQL connection
  • msql_pconnect() - Open persistent mSQL connection
  • msql_query() - Send mSQL query

msql_result
msql_tablename
mSQL Functions


Alias of msql_result

msql_select_db
msql
mSQL Functions
PHP Manual

msql_tablename

(PHP 4, PHP 5)

msql_tablename — Alias of msql_result()

Description

This function is an alias of msql_result().

msql_select_db
msql
mSQL Functions


Adds a parameter to a stored procedure or a remote stored procedure

Mssql Functions
mssql_close
Mssql Functions
PHP Manual

mssql_bind

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure

Description

bool mssql_bind ( resource $stmt , string $param_name , mixed &$var , int $type [, bool $is_output = false [, bool $is_null = false [, int $maxlen = -1 ]]] )

Binds a parameter to a stored procedure or a remote stored procedure.

Parameters

stmt

Statement resource, obtained with mssql_init().

param_name

The parameter name, as a string.

Note: You have to include the @ character, like in the T-SQL syntax. See the explanation included in mssql_execute().

var

The PHP variable you'll bind the MSSQL parameter to. It is passed by reference, to retrieve OUTPUT and RETVAL values after the procedure execution.

type

One of: SQLTEXT, SQLVARCHAR, SQLCHAR, SQLINT1, SQLINT2, SQLINT4, SQLBIT, SQLFLT4, SQLFLT8, SQLFLTN.

is_output

Whether the value is an OUTPUT parameter or not. If it's an OUTPUT parameter and you don't mention it, it will be treated as a normal input parameter and no error will be thrown.

is_null

Whether the parameter is NULL or not. Passing the NULL value as var will not do the job.

maxlen

Used with char/varchar values. You have to indicate the length of the data so if the parameter is a varchar(50), the type must be SQLVARCHAR and this value 50.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_bind() example

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Create a new stored prodecure
$stmt = mssql_init('NewUserRecord');

// Bind the field names
mssql_bind($stmt, '@username',  'Kalle',  SQLVARCHAR,  false,  false,  60);
mssql_bind($stmt, '@name',      'Kalle',  SQLVARCHAR,  false,  false,  60);
mssql_bind($stmt, '@age',       19,       SQLINT1,     false,  false,   3);

// Execute
mssql_execute($stmt);

// Free statement
mssql_free_statement($stmt);
?>

See Also

  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_free_statement() - Free statement memory
  • mssql_init() - Initializes a stored procedure or a remote stored procedure

Mssql Functions
mssql_close
Mssql Functions


Close MS SQL Server connection

mssql_bind
mssql_connect
Mssql Functions
PHP Manual

mssql_close

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_close — Close MS SQL Server connection

Description

bool mssql_close ([ resource $link_identifier ] )

Closes the link to a MS SQL Server database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Parameters

link_identifier

A MS SQL link identifier, returned by mssql_connect().

This function will not close persistent links generated by mssql_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_close() example

<?php
// Connect to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Do any related operations here

// Close the link to MSSQL
mssql_close($link);
?>

See Also

  • mssql_connect() - Open MS SQL server connection
  • mssql_pconnect() - Open persistent MS SQL connection

mssql_bind
mssql_connect
Mssql Functions


Open MS SQL server connection

mssql_close
mssql_data_seek
Mssql Functions
PHP Manual

mssql_connect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_connect — Open MS SQL server connection

Description

resource mssql_connect ([ string $servername [, string $username [, string $password [, bool $new_link ]]]] )

mssql_connect() establishes a connection to a MS SQL server.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mssql_close().

Parameters

servername

The MS SQL server. It can also include a port number. e.g. hostname,port.

username

The username.

password

The password.

new_link

If a second call is made to mssql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. This parameter modifies this behavior and makes mssql_connect() always open a new link, even if mssql_connect() was called before with the same parameters.

Return Values

Returns a MS SQL link identifier on success, or FALSE on error.

Changelog

Version | Description
4.4.1 and 5.1.0 | The new_link parameter was added

Examples

Example #1 mssql_connect() example

<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = 'KALLESPC\SQLEXPRESS';

// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'phpfi');

if (!$link) {
    die('Something went wrong while connecting to MSSQL');
}
?>

See Also

  • mssql_close() - Close MS SQL Server connection
  • mssql_pconnect() - Open persistent MS SQL connection

mssql_close
mssql_data_seek
Mssql Functions


Moves internal row pointer

mssql_connect
mssql_execute
Mssql Functions
PHP Manual

mssql_data_seek

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_data_seek — Moves internal row pointer

Description

bool mssql_data_seek ( resource $result_identifier , int $row_number )

mssql_data_seek() moves the internal row pointer of the MS SQL result associated with the specified result identifier to point to the specified row number, first row being number 0. The next call to mssql_fetch_row() would return that row.

Parameters

result_identifier

The result resource that is being evaluated.

row_number

The desired row number of the new result pointer.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_data_seek() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Select all people
$result = mssql_query('SELECT [name], [age] FROM [persons] WHERE [age] >= 13');

if (!$result) {
    die('Query failed.');
}

// Select every 4th student in the results
for ($i = mssql_num_rows($result) - 1; $i % 4; $i++) {
    if (!mssql_data_seek($result, $i)) {
        continue;
    }

    // Fetch the row ...
}

// Free the query result
mssql_free_result($result);
?>

mssql_connect
mssql_execute
Mssql Functions


Executes a stored procedure on a MS SQL server database

mssql_data_seek
mssql_fetch_array
Mssql Functions
PHP Manual

mssql_execute

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_execute — Executes a stored procedure on a MS SQL server database

Description

mixed mssql_execute ( resource $stmt [, bool $skip_results = false ] )

Executes a stored procedure on a MS SQL server database

Parameters

stmt

Statement handle obtained with mssql_init().

skip_results

Whenever to skip the results or not.

Examples

Example #1 mssql_execute() example

<?php
// Create a new statement
$stmt = mssql_init('NewBlogEntry');

// Some data strings
$title = 'Test of blogging system';
$content = 'If you can read this, then the new system is compatible with MSSQL';

// Bind values
mssql_bind($stmt, '@author',    'Felipe Pena',  SQLVARCHAR,     false,  false,   60);
mssql_bind($stmt, '@date',      '08/10/2008',   SQLVARCHAR,     false,  false,   20);
mssql_bind($stmt, '@title',     $title,         SQLVARCHAR,     false,  false,   60);
mssql_bind($stmt, '@content',   $content,       SQLTEXT);

// Execute the statement
mssql_execute($stmt);

// And we can free it like so:
mssql_free_statement($stmt);
?>

Notes

Note: If the stored procedure returns parameters or a return value these will be available after the call to mssql_execute() unless the stored procedure returns more than one result set. In that case use mssql_next_result() to shift through the results. When the last result has been processed the output parameters and return values will be available.

See Also

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_free_statement() - Free statement memory
  • mssql_init() - Initializes a stored procedure or a remote stored procedure

mssql_data_seek
mssql_fetch_array
Mssql Functions


Fetch a result row as an associative array, a numeric array, or both

mssql_execute
mssql_fetch_assoc
Mssql Functions
PHP Manual

mssql_fetch_array

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Description

array mssql_fetch_array ( resource $result [, int $result_type = MSSQL_BOTH ] )

mssql_fetch_array() is an extended version of mssql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using mssql_fetch_array() is NOT significantly slower than using mssql_fetch_row(), while it provides a significant added value.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

result_type

The type of array that is to be fetched. It's a constant and can take the following values: MSSQL_ASSOC, MSSQL_NUM, and MSSQL_BOTH.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 mssql_fetch_array() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    // The following is equal to the code below:
    //
    // while ($row = mssql_fetch_row($query)) {

    while ($row = mssql_fetch_array($query, MSSQL_NUM)) {
        // ...
    }
}

// Free the query result
mssql_free_result($query);
?>

Notes

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mssql_fetch_row() - Get row as enumerated array

mssql_execute
mssql_fetch_assoc
Mssql Functions


Returns an associative array of the current row in the result

mssql_fetch_array
mssql_fetch_batch
Mssql Functions
PHP Manual

mssql_fetch_assoc

(PHP 4 >= 4.2.0, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_assoc — Returns an associative array of the current row in the result

Description

array mssql_fetch_assoc ( resource $result_id )

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mssql_fetch_assoc() is equivalent to calling mssql_fetch_array() with MSSQL_ASSOC for the optional second parameter.

Parameters

result_id

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 mssql_fetch_assoc() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
}
else
{
    // Print a nice list of users in the format of:
    // * name (username)

    echo '<ul>';

    while ($row = mssql_fetch_assoc($query)) {
        echo '<li>' . $row['name'] . ' (' . $row['username'] . ')</li>';
    }

    echo '</ul>';
}

// Free the query result
mssql_free_result($query);
?>

mssql_fetch_array
mssql_fetch_batch
Mssql Functions


Returns the next batch of records

mssql_fetch_assoc
mssql_fetch_field
Mssql Functions
PHP Manual

mssql_fetch_batch

(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_batch — Returns the next batch of records

Description

int mssql_fetch_batch ( resource $result )

Returns the next batch of records

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns the batch number as an integer.

Examples

Example #1 mssql_fetch_batch() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Send a query
$result = mssql_query('SELECT * FROM [php].[dbo].[people]', $link, 100);
$records = 10;

while ($records >= 0) {
    while ($row = mssql_fetch_assoc($result)) {
        // Do stuff ...
    }

    --$records;
}

if ($batchsize = mssql_fetch_batch($result)) {
    // $batchsize is the number of records left
    // in the result, but not shown above
}
?>

mssql_fetch_assoc
mssql_fetch_field
Mssql Functions


Get field information

mssql_fetch_batch
mssql_fetch_object
Mssql Functions
PHP Manual

mssql_fetch_field

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_field — Get field information

Description

object mssql_fetch_field ( resource $result [, int $field_offset = -1 ] )

mssql_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

field_offset

The numerical field offset. If the field offset is not specified, the next field that was not yet retrieved by this function is retrieved. The field_offset starts at 0.

Return Values

Returns an object containing field information.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
  • column_source - the table from which the column was taken
  • max_length - maximum length of the column
  • numeric - 1 if the column is numeric
  • type - the column type.

Examples

Example #1 mssql_fetch_field() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

// Construct table
echo '<h3>Table structure for \'persons\'</h3>';
echo '<table border="1">';

// Table header
echo '<thead>';
echo '<tr>';
echo '<td>Field name</td>';
echo '<td>Data type</td>';
echo '<td>Max length</td>';
echo '</tr>';
echo '</thead>';

// Dump all fields
echo '<tbody>';

for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    // Fetch the field information
    $field = mssql_fetch_field($query, $i);

    // Print the row
    echo '<tr>';
    echo '<td>' . $field->name . '</td>';
    echo '<td>' . strtoupper($field->type) . '</td>';
    echo '<td>' . $field->max_length . '</td>';
    echo '</tr>';
}

echo '</tbody>';
echo '</table>';

// Free the query result
mssql_free_result($query);
?>

See Also

  • mssql_field_seek() - Seeks to the specified field offset

mssql_fetch_batch
mssql_fetch_object
Mssql Functions


Fetch row as object

mssql_fetch_field
mssql_fetch_row
Mssql Functions
PHP Manual

mssql_fetch_object

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_object — Fetch row as object

Description

object mssql_fetch_object ( resource $result )

mssql_fetch_object() is similar to mssql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to mssql_fetch_array(), and almost as quick as mssql_fetch_row() (the difference is insignificant).

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 mssql_fetch_object() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    // Print a nice list of users in the format of:
    // * name (username)

    echo '<ul>';

    while ($row = mssql_fetch_object($query)) {
        echo '<li>' . $row->name . ' (' . $row->username . ')</li>';
    }

    echo '</ul>';
}

// Free the query result
mssql_free_result($query);
?>

Notes

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_row() - Get row as enumerated array

mssql_fetch_field
mssql_fetch_row
Mssql Functions


Get row as enumerated array

mssql_fetch_object
mssql_field_length
Mssql Functions
PHP Manual

mssql_fetch_row

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_row — Get row as enumerated array

Description

array mssql_fetch_row ( resource $result )

mssql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to mssql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 mssql_fetch_row() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Query to execute
$query = mssql_query('SELECT [id], [quote] FROM [quotes] WHERE [id] = \'42\'', $link);

// Did the query fail?
if (!$query) {
    die('MSSQL error: ' . mssql_get_last_message());
}

// Fetch the row
$row = mssql_fetch_row($query);

// Print the 'quote'
echo 'Quote #' . $row[0] . ': "' . $row[1] . '"';
?>

The above example will output something similar to:

Quote #42: "The answer to everything..."

Notes

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_object() - Fetch row as object
  • mssql_data_seek() - Moves internal row pointer
  • mssql_result() - Get result data

mssql_fetch_object
mssql_field_length
Mssql Functions


Get the length of a field

mssql_fetch_row
mssql_field_name
Mssql Functions
PHP Manual

mssql_field_length

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_length — Get the length of a field

Description

int mssql_field_length ( resource $result [, int $offset = -1 ] )

Returns the length of field no. offset in result .

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Return Values

The length of the specified field index on success or FALSE on failure.

Examples

Example #1 mssql_field_length() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT [name], [age] FROM [php].[dbo].[persons]');

// Print the field length
echo 'The field \'age\' has a data length of ' . mssql_field_length($query, 1);

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

The field 'age' has a data length of 4

Notes

Note: Note to Windows Users
Due to a limitation in the underlying API used by PHP (MS DBLib C API), the length of VARCHAR fields is limited to 255. If you need to store more data, use a TEXT field instead.

See Also

  • mssql_field_name() - Get the name of a field
  • mssql_field_type() - Gets the type of a field

mssql_fetch_row
mssql_field_name
Mssql Functions


Get the name of a field

mssql_field_length
mssql_field_seek
Mssql Functions
PHP Manual

mssql_field_name

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_name — Get the name of a field

Description

string mssql_field_name ( resource $result [, int $offset = -1 ] )

Returns the name of field no. offset in result .

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Return Values

The name of the specified field index on success or FALSE on failure.

Examples

Example #1 mssql_field_name() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name], [email] FROM [php].[dbo].[userlist]');

echo 'Result set contains the following field(s):', PHP_EOL;

// Dump all field names in result
for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    echo ' - ' . mssql_field_name($query, $i), PHP_EOL;
}

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

Result set contains the following field(s):
 - username
 - name
 - email

See Also

  • mssql_field_length() - Get the length of a field
  • mssql_field_type() - Gets the type of a field

mssql_field_length
mssql_field_seek
Mssql Functions


Seeks to the specified field offset

mssql_field_name
mssql_field_type
Mssql Functions
PHP Manual

mssql_field_seek

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_seek — Seeks to the specified field offset

Description

bool mssql_field_seek ( resource $result , int $field_offset )

Seeks to the specified field offset. If the next call to mssql_fetch_field() won't include a field offset, this field would be returned.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

field_offset

The field offset, starts at 0.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using mssql_field_seek() on the example for mssql_fetch_field()

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

// Construct table
echo '<h3>Table structure for \'persons\'</h3>';
echo '<table border="1">';

// Table header
echo '<thead>';
echo '<tr>';
echo '<td>Field name</td>';
echo '<td>Data type</td>';
echo '<td>Max length</td>';
echo '</tr>';
echo '</thead>';

// Dump all fields
echo '<tbody>';

for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    // Fetch the field information, notice the
    // field_offset parameter is not set. See
    // the mssql_field_seek call below
    $field = mssql_fetch_field($query);

    // Print the row
    echo '<tr>';
    echo '<td>' . $field->name . '</td>';
    echo '<td>' . strtoupper($field->type) . '</td>';
    echo '<td>' . $field->max_length . '</td>';
    echo '</tr>';

    // Move the internal seek pointer to the next
    // row in the result set
    mssql_field_seek($query, $i + 1);
}

echo '</tbody>';
echo '</table>';

// Free the query result
mssql_free_result($query);
?>

See Also

  • mssql_fetch_field() - Get field information

mssql_field_name
mssql_field_type
Mssql Functions


Gets the type of a field

mssql_field_seek
mssql_free_result
Mssql Functions
PHP Manual

mssql_field_type

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_type — Gets the type of a field

Description

string mssql_field_type ( resource $result [, int $offset = -1 ] )

Returns the type of field no. offset in result .

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Return Values

The type of the specified field index on success or FALSE on failure.

Examples

Example #1 mssql_field_type() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT [name] FROM [php].[dbo].[persons]');

// Print the field type and length
echo '\'' . mssql_field_name($query, 0) . '\' is a type of ' .
     strtoupper(mssql_field_type($query, 0)) .
     '(' . mssql_field_length($query, 0) . ')';

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

'name' is a type of CHAR(50)

See Also

  • mssql_field_length() - Get the length of a field
  • mssql_field_name() - Get the name of a field

mssql_field_seek
mssql_free_result
Mssql Functions


Free result memory

mssql_field_type
mssql_free_statement
Mssql Functions
PHP Manual

mssql_free_result

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_free_result — Free result memory

Description

bool mssql_free_result ( resource $result )

mssql_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call mssql_free_result() with the result identifier as an argument and the associated result memory will be freed.

Parameters

result

The result resource that is being freed. This result comes from a call to mssql_query().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_free_result() example

<?php
// Select some data from a table
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]', $link);

// Handle query result here

// When we're done we free the result by calling
// mssql_free_result like so:
mssql_free_result($query);
?>

See Also

  • mssql_free_statement() - Free statement memory

mssql_field_type
mssql_free_statement
Mssql Functions


Free statement memory

mssql_free_result
mssql_get_last_message
Mssql Functions
PHP Manual

mssql_free_statement

(PHP 4 >= 4.3.2, PHP 5, PECL odbtp >= 1.1.1)

mssql_free_statement — Free statement memory

Description

bool mssql_free_statement ( resource $stmt )

mssql_free_statement() only needs to be called if you are worried about using too much memory while your script is running. All statement memory will automatically be freed when the script ends. You may call mssql_free_statement() with the statement identifier as an argument and the associated statement memory will be freed.

Parameters

stmt

Statement resource, obtained with mssql_init().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_free_statement() example

<?php
// Create a new statement
$stmt = mssql_init('test');

// Bind values here and execute the statement

// once we're done, we clear it from the memory
// using mssql_free_statement like so:
mssql_free_statement($stmt);
?>

See Also

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_init() - Initializes a stored procedure or a remote stored procedure
  • mssql_free_result() - Free result memory

mssql_free_result
mssql_get_last_message
Mssql Functions


Returns the last message from the server

mssql_free_statement
mssql_guid_string
Mssql Functions
PHP Manual

mssql_get_last_message

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_get_last_message — Returns the last message from the server

Description

string mssql_get_last_message ( void )

Gets the last message from the MS-SQL server

Parameters

This function has no parameters.

Return Values

Returns last error message from server, or an empty string if no error messages are returned from MSSQL.

Examples

Example #1 mssql_get_last_message() example

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Make a query that will fail
$query = @mssql_query('SELECT * FROM [php].[dbo].[not-found]');

if (!$query) {
    // The query has failed, print a nice error message
    // using mssql_get_last_message()
    die('MSSQL error: ' . mssql_get_last_message());
}
?>

The above example will output something similar to:

MSSQL error: Invalid object name 'php.dbo.not-found'.

See Also

  • mssql_min_error_severity() - Sets the minimum error severity
  • mssql_min_message_severity() - Sets the minimum message severity

mssql_free_statement
mssql_guid_string
Mssql Functions


Converts a 16 byte binary GUID to a string

mssql_get_last_message
mssql_init
Mssql Functions
PHP Manual

mssql_guid_string

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_guid_string — Converts a 16 byte binary GUID to a string

Description

string mssql_guid_string ( string $binary [, bool $short_format = false ] )

Converts a 16 byte binary GUID to a string.

Parameters

binary

A 16 byte binary GUID.

short_format

Whenever to use short format.

Return Values

Returns the converted string on success.

Examples

Example #1 mssql_guid_string() example

<?php
$binary = '19555081977808608437941339997619274330352755554827939936';

var_dump(mssql_guid_string($binary));
var_dump(mssql_guid_string($binary, true));
?>

The above example will output:

string(36) "35353931-3035-3138-3937-373830383630"
string(32) "31393535353038313937373830383630"

mssql_get_last_message
mssql_init
Mssql Functions


Initializes a stored procedure or a remote stored procedure

mssql_guid_string
mssql_min_error_severity
Mssql Functions
PHP Manual

mssql_init

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_init — Initializes a stored procedure or a remote stored procedure

Description

resource mssql_init ( string $sp_name [, resource $link_identifier ] )

Initializes a stored procedure or a remote stored procedure.

Parameters

sp_name

Stored procedure name, like ownew.sp_name or otherdb.owner.sp_name.

link_identifier

A MS SQL link identifier, returned by mssql_connect().

Return Values

Returns a resource identifier "statement", used in subsequent calls to mssql_bind() and mssql_execute(), or FALSE on errors.

Examples

Example #1 mssql_init() example

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Create a new statement
$stmt = mssql_init('StatementTest', $link);

// Bind values here

// Once values are binded we execute our statement
// using mssql_execute:
mssql_execute($stmt);

// And we can free it like so:
mssql_free_statement($stmt);
?>

See Also

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_free_statement() - Free statement memory

mssql_guid_string
mssql_min_error_severity
Mssql Functions


Sets the minimum error severity

mssql_init
mssql_min_message_severity
Mssql Functions
PHP Manual

mssql_min_error_severity

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_min_error_severity — Sets the minimum error severity

Description

void mssql_min_error_severity ( int $severity )

Sets the minimum error severity.

Parameters

severity

The new error severity.

Return Values

No value is returned.

Examples

Example #1 mssql_min_error_severity() example

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Set the minimum error severity to not include SQL
// syntax errors by setting it to something greater than
// or equal to 1.
mssql_min_error_severity(1);

// Send a query we know that will cause an syntax error, in
// this case we use the MySQL quote signs instead of wrapping
// square brackets around the field and table names.
$query = mssql_query('SELECT `syntax`, `error` FROM `MSSQL`');

if (!$query) {
    // Custom error handler ...
}
?>

mssql_init
mssql_min_message_severity
Mssql Functions


Sets the minimum message severity

mssql_min_error_severity
mssql_next_result
Mssql Functions
PHP Manual

mssql_min_message_severity

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_min_message_severity — Sets the minimum message severity

Description

void mssql_min_message_severity ( int $severity )

Sets the minimum message severity.

Parameters

severity

The new message severity.

Return Values

No value is returned.

Examples

Example #1 mssql_min_message_severity() example

<?php
// Connect to MSSQL
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Set the minimum message severity to 17, this
// will not show any messages issued by the underlaying
// API when we select a non-existent database below
mssql_min_message_severity(17);

// Select a non-existent database
mssql_select_db('THIS_DATABASE_DOES_NOT_EXISTS');
?>

The above example will output:

mssql_select_db(): Unable to select database:  THIS_DATABASE_DOES_NOT_EXISTS

mssql_min_error_severity
mssql_next_result
Mssql Functions


Move the internal result pointer to the next result

mssql_min_message_severity
mssql_num_fields
Mssql Functions
PHP Manual

mssql_next_result

(PHP 4 >= 4.0.5, PHP 5, PECL odbtp >= 1.1.1)

mssql_next_result — Move the internal result pointer to the next result

Description

bool mssql_next_result ( resource $result_id )

When sending more than one SQL statement to the server or executing a stored procedure with multiple results, it will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the rows from the new result set.

Parameters

result_id

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns TRUE if an additional result set was available or FALSE otherwise.

Examples

Example #1 mssql_next_result() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Send a query to MSSQL
$sql = 'SELECT [name], [age] FROM [php].[dbo].[persons]';
$query = mssql_query($sql, $link);

// Iterate through returned records
do {
    while ($row = mssql_fetch_row($query)) {
        // Handle record ...
    }
} while (mssql_next_result($query));

// Clean up
mssql_free_result($query);
mssql_close($link);
?>

mssql_min_message_severity
mssql_num_fields
Mssql Functions


Gets the number of fields in result

mssql_next_result
mssql_num_rows
Mssql Functions
PHP Manual

mssql_num_fields

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_num_fields — Gets the number of fields in result

Description

int mssql_num_fields ( resource $result )

mssql_num_fields() returns the number of fields in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns the number of fields, as an integer.

Examples

Example #1 mssql_num_fields() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Select some data from our database
$data = mssql_query('SELECT [name], [age] FROM [php].[dbo].[persons]');

// Construct a table
echo '<table border="1">';

$header = false;

// Iterate through returned results
while ($row = mssql_fetch_array($data)) {
    // Build the table header
    if (!$header) {
        echo '<thead>';
        echo '<tr>';

        for ($i = 1; ($i + 1) <= mssql_num_fields($data); ++$i) {
            echo '<td>' . ucfirst($row[$i]) . '</td>';
        }

        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';

        $header = true;
    }

    // Build the row
    echo '<tr>';

    foreach($row as $value) {
        echo '<td>' . $value . '</td>';
    }

    echo '</tr>';
}

// Close table
echo '</tbody>';
echo '</table>';

// Clean up
mssql_free_result($data);
mssql_close($link);
?>

See Also

  • mssql_query() - Send MS SQL query
  • mssql_fetch_field() - Get field information
  • mssql_num_rows() - Gets the number of rows in result

mssql_next_result
mssql_num_rows
Mssql Functions


Gets the number of rows in result

mssql_num_fields
mssql_pconnect
Mssql Functions
PHP Manual

mssql_num_rows

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_num_rows — Gets the number of rows in result

Description

int mssql_num_rows ( resource $result )

mssql_num_rows() returns the number of rows in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns the number of rows, as an integer.

Examples

Example #1 mssql_num_rows() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Select all our records from a table
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

echo 'Total records in database: ' . mssql_num_rows($query);

// Clean up
mssql_free_result($query);
?>

See Also

  • mssql_query() - Send MS SQL query
  • mssql_fetch_row() - Get row as enumerated array

mssql_num_fields
mssql_pconnect
Mssql Functions


Open persistent MS SQL connection

mssql_num_rows
mssql_query
Mssql Functions
PHP Manual

mssql_pconnect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_pconnect — Open persistent MS SQL connection

Description

resource mssql_pconnect ([ string $servername [, string $username [, string $password [, bool $new_link ]]]] )

mssql_pconnect() acts very much like mssql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mssql_close() will not close links established by mssql_pconnect()).

This type of links is therefore called 'persistent'.

Parameters

servername

The MS SQL server. It can also include a port number. e.g. hostname:port.

username

The username.

password

The password.

new_link

If a second call is made to mssql_pconnect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. This parameter modifies this behavior and makes mssql_pconnect() always open a new link, even if mssql_pconnect() was called before with the same parameters.

Return Values

Returns a positive MS SQL persistent link identifier on success, or FALSE on error.

Examples

Example #1 mssql_pconnect() using the new_link parameter

<?php
// Connect to MSSQL and select the database
$link1 = mssql_pconnect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link1);

// Create a new link
$link2 = mssql_pconnect('MANGO\SQLEXPRESS', 'sa', 'phpfi', true);
mssql_select_db('random', $link2);
?>

mssql_num_rows
mssql_query
Mssql Functions


Send MS SQL query

mssql_pconnect
mssql_result
Mssql Functions
PHP Manual

mssql_query

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_query — Send MS SQL query

Description

mixed mssql_query ( string $query [, resource $link_identifier [, int $batch_size = 0 ]] )

mssql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

A SQL query.

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mssql_connect() was called, and use it.

batch_size

The number of records to batch in the buffer.

Return Values

Returns a MS SQL result resource on success, TRUE if no rows were returned, or FALSE on error.

Examples

Example #1 mssql_query() example

<?php
// Connect to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

if (!$link || !mssql_select_db('php', $link)) {
    die('Unable to connect or select database!');
}

// Do a simple query, select the version of
// MSSQL and print it.
$version = mssql_query('SELECT @@VERSION');
$row = mssql_fetch_array($version);

echo $row[0];

// Clean up
mssql_free_result($version);
?>

Notes

Note: If the query returns multiple results then it is necessary to fetch all results by mssql_next_result() or free the results by mssql_free_result() before executing next query.

See Also

  • mssql_select_db() - Select MS SQL database
  • mssql_connect() - Open MS SQL server connection

mssql_pconnect
mssql_result
Mssql Functions


Get result data

mssql_query
mssql_rows_affected
Mssql Functions
PHP Manual

mssql_result

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_result — Get result data

Description

string mssql_result ( resource $result , int $row , mixed $field )

mssql_result() returns the contents of one cell from a MS SQL result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

row

The row number.

field

Can be the field's offset, the field's name or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), it uses the alias instead of the column name.

Note: Specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Return Values

Returns the contents of the specified cell.

Examples

Example #1 mssql_result() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    for ($i = 0; $i < mssql_num_rows($query); ++$i) {
        echo mssql_result($query, $i, 'username'), PHP_EOL;
    }
}

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

Kalle
Felipe
Emil
Ross

Example #2 Faster alternative to above example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    while ($row = mssql_fetch_array($query)) {
        echo $row['username'], PHP_EOL;
    }
}

// Free the query result
mssql_free_result($query);
?>

Notes

Note: When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mssql_result().

See Also

Recommended high-performance alternatives:

  • mssql_fetch_row() - Get row as enumerated array
  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_assoc() - Returns an associative array of the current row in the result
  • mssql_fetch_object() - Fetch row as object

mssql_query
mssql_rows_affected
Mssql Functions


Returns the number of records affected by the query

mssql_result
mssql_select_db
Mssql Functions
PHP Manual

mssql_rows_affected

(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)

mssql_rows_affected — Returns the number of records affected by the query

Description

int mssql_rows_affected ( resource $link_identifier )

Returns the number of records affected by the last write query.

Parameters

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

Return Values

Returns the number of records affected by last operation.

Examples

Example #1 mssql_rows_affected() example

<?php
// Delete all rows in a table
mssql_query('TRUNCATE TABLE [php].[dbo].[persons]');

echo 'Deleted ' . mssql_rows_affected($link) . ' row(s)';
?>

mssql_result
mssql_select_db
Mssql Functions


Select MS SQL database

mssql_rows_affected
MySQL
Mssql Functions
PHP Manual

mssql_select_db

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_select_db — Select MS SQL database

Description

bool mssql_select_db ( string $database_name [, resource $link_identifier ] )

mssql_select_db() sets the current active database on the server that's associated with the specified link identifier.

Every subsequent call to mssql_query() will be made on the active database.

Parameters

database_name

The database name.

To escape the name of a database that contains spaces, hyphens ("-"), or any other exceptional characters, the database name must be enclosed in brackets, as is shown in the example, below. This technique must also be applied when selecting a database name that is also a reserved word (such as primary).

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mssql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_select_db() example

<?php
// Create a link to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Select the database 'php'
mssql_select_db('php', $link);
?>

See Also

  • mssql_connect() - Open MS SQL server connection
  • mssql_pconnect() - Open persistent MS SQL connection
  • mssql_query() - Send MS SQL query

mssql_rows_affected
MySQL
Mssql Functions


Show largest possible random value

min
mt_rand
Math Functions
PHP Manual

mt_getrandmax

(PHP 4, PHP 5)

mt_getrandmax — Show largest possible random value

Description

int mt_getrandmax ( void )

Returns the maximum value that can be returned by a call to mt_rand().

Return Values

Returns the maximum random value returned by mt_rand()

See Also

  • mt_rand() - Generate a better random value
  • mt_srand() - Seed the better random number generator
  • getrandmax() - Show largest possible random value

min
mt_rand
Math Functions


Generate a better random value

mt_getrandmax
mt_srand
Math Functions
PHP Manual

mt_rand

(PHP 4, PHP 5)

mt_rand — Generate a better random value

Description

int mt_rand ( void )
int mt_rand ( int $min , int $max )

Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses the libc random number generator with the rand() function. The mt_rand() function is a drop-in replacement for this. It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

If called without the optional min , max arguments mt_rand() returns a pseudo-random value between 0 and mt_getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use mt_rand(5, 15).

Parameters

min

Optional lowest value to be returned (default: 0)

max

Optional highest value to be returned (default: mt_getrandmax())

Return Values

A random integer value between min (or 0) and max (or mt_getrandmax(), inclusive)

Changelog

Version | Description
4.2.0 | The random number generator is seeded automatically.

Examples

Example #1 mt_rand() example

<?php
echo mt_rand() . "\n";
echo mt_rand() . "\n";

echo mt_rand(5, 15);
?>

The above example will output something similar to:

1604716014
1478613278
6

See Also

  • mt_srand() - Seed the better random number generator
  • mt_getrandmax() - Show largest possible random value
  • rand() - Generate a random integer

mt_getrandmax
mt_srand
Math Functions


Seed the better random number generator

mt_rand
octdec
Math Functions
PHP Manual

mt_srand

(PHP 4, PHP 5)

mt_srand — Seed the better random number generator

Description

void mt_srand ([ int $seed ] )

Seeds the random number generator with seed or with a random value if no seed is given.

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

Parameters

seed

An optional seed value

Return Values

No value is returned.

Changelog

Version | Description
Since 4.2.0 | The seed becomes optional and defaults to a random value if omitted.
Since 5.2.1 | The Mersenne Twister implementation in PHP now uses a new seeding algorithm by Richard Wagner. Identical seeds no longer produce the same sequence of values they did in previous versions. This behavior is not expected to change again, but it is considered unsafe to rely upon it nonetheless.

Examples

Example #1 mt_srand() example

<?php
// seed with microseconds
function make_seed()
{
  list($usec, $sec) = explode(' ', microtime());
  return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$randval = mt_rand();
?>

See Also

  • mt_rand() - Generate a better random value
  • mt_getrandmax() - Show largest possible random value
  • srand() - Seed the random number generator

mt_rand
octdec
Math Functions


Get number of affected rows in previous MySQL operation

MySQL Functions
mysql_client_encoding
MySQL Functions
PHP Manual

mysql_affected_rows

(PHP 4, PHP 5)

mysql_affected_rows — Get number of affected rows in previous MySQL operation

Description

int mysql_affected_rows ([ resource $link_identifier ] )

Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier .

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the number of affected rows on success, and -1 if the last query failed.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.1.2.

When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records plus the number of inserted records.

Examples

Example #1 mysql_affected_rows() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

/* this should return the correct numbers of deleted records */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());

/* with a where clause that is never true, it should return 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
?>

The above example will output something similar to:

Records deleted: 10
Records deleted: 0

Example #2 mysql_affected_rows() example using transactions

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

/* Update records */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>

The above example will output something similar to:

Updated Records: 10

Notes

Note: Transactions
If you are using transactions, you need to call mysql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the COMMIT.

Note: SELECT Statements
To retrieve the number of rows returned by a SELECT, it is possible to use mysql_num_rows().

See Also

  • mysql_num_rows() - Get number of rows in result
  • mysql_info() - Get information about the most recent query

MySQL Functions
mysql_client_encoding
MySQL Functions


Returns the name of the character set

mysql_affected_rows
mysql_close
MySQL Functions
PHP Manual

mysql_client_encoding

(PHP 4 >= 4.3.0, PHP 5)

mysql_client_encoding — Returns the name of the character set

Description

string mysql_client_encoding ([ resource $link_identifier ] )

Retrieves the character_set variable from MySQL.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the default character set name for the current connection.

Examples

Example #1 mysql_client_encoding() example

<?php
$link    = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);

echo "The current character set is: $charset\n";
?>

The above example will output something similar to:

The current character set is: latin1

See Also

  • mysql_set_charset() - Sets the client character set
  • mysql_real_escape_string() - Escapes special characters in a string for use in a SQL statement

mysql_affected_rows
mysql_close
MySQL Functions


Close MySQL connection

mysql_client_encoding
mysql_connect
MySQL Functions
PHP Manual

mysql_close

(PHP 4, PHP 5)

mysql_close — Close MySQL connection

Description

bool mysql_close ([ resource $link_identifier ] )

mysql_close() closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysql_close() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

The above example will output:

Connected successfully

Notes

Note: mysql_close() will not close persistent links created by mysql_pconnect().

See Also

  • mysql_connect() - Open a connection to a MySQL Server
  • mysql_free_result() - Free result memory

mysql_client_encoding
mysql_connect
MySQL Functions


Open a connection to a MySQL Server

mysql_close
mysql_create_db
MySQL Functions
PHP Manual

mysql_connect

(PHP 4, PHP 5)

mysql_connect — Open a connection to a MySQL Server

Description

resource mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool $new_link = false [, int $client_flags = 0 ]]]]] )

Opens or reuses a connection to a MySQL server.

Parameters

server

The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost.

If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used.

username

The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used.

password

The password. Default value is defined by mysql.default_password. In SQL safe mode, this parameter is ignored and empty password is used.

new_link

If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.

client_flags

The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE. Read the section about Predefined Constants for further information. In SQL safe mode, this parameter is ignored.

Return Values

Returns a MySQL link identifier on success or FALSE on failure.

Changelog

Version | Description
4.3.0 | Added the client_flags parameter.
4.2.0 | Added the new_link parameter.

Examples

Example #1 mysql_connect() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Example #2 mysql_connect() example using hostname:port syntax

<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Example #3 mysql_connect() example using ":/path/to/socket" syntax

<?php
// we connect to localhost and socket e.g. /tmp/mysql.sock

//variant 1: ommit localhost
$link = mysql_connect(':/tmp/mysql', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

// variant 2: with localhost
$link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Notes

Note: Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, you should set the correct path as Runtime Configuration in your PHP configuration and leave the server field blank.

Note: The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close().

Note: You can suppress the error message on failure by prepending a @ to the function name.

Note: Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

See Also

  • mysql_pconnect() - Open a persistent connection to a MySQL server
  • mysql_close() - Close MySQL connection

mysql_close
mysql_create_db
MySQL Functions


Create a MySQL database

mysql_connect
mysql_data_seek
MySQL Functions
PHP Manual

mysql_create_db

(PHP 4, PHP 5)

mysql_create_db — Create a MySQL database

Description

bool mysql_create_db ( string $database_name [, resource $link_identifier ] )

mysql_create_db() attempts to create a new database on the server associated with the specified link identifier.

Parameters

database_name

The name of the database being created.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysql_create_db() alternative example

The function mysql_create_db() is deprecated. It is preferable to use mysql_query() to issue a sql CREATE DATABASE statement instead.

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
    echo "Database my_db created successfully\n";
} else {
    echo 'Error creating database: ' . mysql_error() . "\n";
}
?>

The above example will output something similar to:

Database my_db created successfully

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_createdb()

Note: This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

See Also

  • mysql_query() - Send a MySQL query
  • mysql_select_db() - Select a MySQL database

mysql_connect
mysql_data_seek
MySQL Functions


Move internal result pointer

mysql_create_db
mysql_db_name
MySQL Functions
PHP Manual

mysql_data_seek

(PHP 4, PHP 5)

mysql_data_seek — Move internal result pointer

Description

bool mysql_data_seek ( resource $result , int $row_number )

mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc(), would return that row.

row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows() - 1. However if the result set is empty (mysql_num_rows() == 0), a seek to 0 will fail with a E_WARNING and mysql_data_seek() will return FALSE.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

row_number

The desired row number of the new result pointer.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysql_data_seek() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sample_db');
if (!$db_selected) {
    die('Could not select database: ' . mysql_error());
}
$query = 'SELECT last_name, first_name FROM friends';
$result = mysql_query($query);
if (!$result) {
    die('Query failed: ' . mysql_error());
}
/* fetch rows in reverse order */
for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
    if (!mysql_data_seek($result, $i)) {
        echo "Cannot seek to row $i: " . mysql_error() . "\n";
        continue;
    }

    if (!($row = mysql_fetch_assoc($result))) {
        continue;
    }

    echo $row['last_name'] . ' ' . $row['first_name'] . "<br />\n";
}

mysql_free_result($result);
?>

Notes

Note: The function mysql_data_seek() can be used in conjunction only with mysql_query(), not with mysql_unbuffered_query().

See Also

  • mysql_query() - Send a MySQL query
  • mysql_num_rows() - Get number of rows in result
  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_object() - Fetch a result row as an object

mysql_create_db
mysql_db_name
MySQL Functions


Get result data

mysql_data_seek
mysql_db_query
MySQL Functions
PHP Manual

mysql_db_name

(PHP 4, PHP 5)

mysql_db_name — Get result data

Description

string mysql_db_name ( resource $result , int $row [, mixed $field ] )

Retrieve the database name from a call to mysql_list_dbs().

Parameters

result

The result pointer from a call to mysql_list_dbs().

row

The index into the result set.

field

The field name.

Return Values

Returns the database name on success, and FALSE on failure. If FALSE is returned, use mysql_error() to determine the nature of the error.

Examples

Example #1 mysql_db_name() example

<?php
error_reporting(E_ALL);

$link = mysql_connect('dbhost', 'username', 'password');
$db_list = mysql_list_dbs($link);

$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
    echo mysql_db_name($db_list, $i) . "\n";
    $i++;
}
?>

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_dbname()

See Also

  • mysql_list_dbs() - List databases available on a MySQL server
  • mysql_tablename() - Get table name of field

mysql_data_seek
mysql_db_query
MySQL Functions


Send a MySQL query

mysql_db_name
mysql_drop_db
MySQL Functions
PHP Manual

mysql_db_query

(PHP 4, PHP 5)

mysql_db_query — Send a MySQL query

Description

resource mysql_db_query ( string $database , string $query [, resource $link_identifier ] )

mysql_db_query() selects a database, and executes a query on it.

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

Parameters

database

The name of the database that will be selected.

query

The MySQL query.

Data inside the query should be properly escaped.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns a positive MySQL result resource to the query result, or FALSE on error. The function also returns TRUE/FALSE for INSERT/UPDATE/DELETE queries to indicate success/failure.

Changelog

Version | Description
5.3.0 | This function now throws an E_DEPRECATED notice.
4.0.6 | This function is deprecated, do not use this function. Use mysql_select_db() and mysql_query() instead.

Examples

Example #1 mysql_db_query() alternative example

<?php

if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
    echo 'Could not connect to mysql';
    exit;
}

if (!mysql_select_db('mysql_dbname', $link)) {
    echo 'Could not select database';
    exit;
}

$sql    = 'SELECT foo FROM bar WHERE id = 42';
$result = mysql_query($sql, $link);

if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_assoc($result)) {
    echo $row['foo'];
}

mysql_free_result($result);

?>

Notes

Note: Be aware that this function does NOT switch back to the database you were connected before. In other words, you can't use this function to temporarily run a sql query on another database, you would have to manually switch back. Users are strongly encouraged to use the database.table syntax in their sql queries or mysql_select_db() instead of this function.

See Also

  • mysql_query() - Send a MySQL query
  • mysql_select_db() - Select a MySQL database

mysql_db_name
mysql_drop_db
MySQL Functions


Drop (delete) a MySQL database

mysql_db_query
mysql_errno
MySQL Functions
PHP Manual

mysql_drop_db

(PHP 4, PHP 5)

mysql_drop_db — Drop (delete) a MySQL database

Description

bool mysql_drop_db ( string $database_name [, resource $link_identifier ] )

mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier. This function is deprecated, it is preferable to use mysql_query() to issue a sql DROP DATABASE statement instead.

Parameters

database_name

The name of the database that will be deleted.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysql_drop_db() alternative example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$sql = 'DROP DATABASE my_db';
if (mysql_query($sql, $link)) {
    echo "Database my_db was successfully dropped\n";
} else {
    echo 'Error dropping database: ' . mysql_error() . "\n";
}
?>

Notes

Warning

This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

Note: For backward compatibility, the following deprecated alias may be used: mysql_dropdb()

See Also

  • mysql_query() - Send a MySQL query

mysql_db_query
mysql_errno
MySQL Functions


Returns the numerical value of the error message from previous MySQL operation

mysql_drop_db
mysql_error
MySQL Functions
PHP Manual

mysql_errno

(PHP 4, PHP 5)

mysql_errno — Returns the numerical value of the error message from previous MySQL operation

Description

int mysql_errno ([ resource $link_identifier ] )

Returns the error number from the last MySQL function.

Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the error number from the last MySQL function, or 0 (zero) if no error occurred.

Examples

Example #1 mysql_errno() example

<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!mysql_select_db("nonexistentdb", $link)) {
    echo mysql_errno($link) . ": " . mysql_error($link). "\n";
}

mysql_select_db("kossu", $link);
if (!mysql_query("SELECT * FROM nonexistenttable", $link)) {
    echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
}
?>

The above example will output something similar to:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

See Also

  • mysql_error() - Returns the text of the error message from previous MySQL operation
  • » MySQL error codes

mysql_drop_db
mysql_error
MySQL Functions


Returns the text of the error message from previous MySQL operation

mysql_errno
mysql_escape_string
MySQL Functions
PHP Manual

mysql_error

(PHP 4, PHP 5)

mysql_error — Returns the text of the error message from previous MySQL operation

Description

string mysql_error ([ resource $link_identifier ] )

Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the error text from the last MySQL function, or '' (empty string) if no error occurred.

Examples

Example #1 mysql_error() example

<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";

mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
?>

The above example will output something similar to:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

See Also

  • mysql_errno() - Returns the numerical value of the error message from previous MySQL operation
  • » MySQL error codes

mysql_errno
mysql_escape_string
MySQL Functions


Escapes a string for use in a mysql_query

mysql_error
mysql_fetch_array
MySQL Functions
PHP Manual

mysql_escape_string

(PHP 4 >= 4.0.3, PHP 5)

mysql_escape_string — Escapes a string for use in a mysql_query

Description

string mysql_escape_string ( string $unescaped_string )

This function will escape the unescaped_string , so that it is safe to place it in a mysql_query(). This function is deprecated.

This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set. mysql_escape_string() does not take a connection argument and does not respect the current charset setting.

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

Parameters

unescaped_string

The string that is to be escaped.

Return Values

Returns the escaped string.

Changelog

Version | Description
5.3.0 | This function now throws an E_DEPRECATED notice.
4.3.0 | This function became deprecated, do not use this function. Instead, use mysql_real_escape_string().

Examples

Example #1 mysql_escape_string() example

<?php
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
printf("Escaped string: %s\n", $escaped_item);
?>

The above example will output:

Escaped string: Zak\'s Laptop

Notes

Note: mysql_escape_string() does not escape % and _.

See Also

  • mysql_real_escape_string() - Escapes special characters in a string for use in a SQL statement
  • addslashes() - Quote string with slashes
  • The magic_quotes_gpc directive.

mysql_error
mysql_fetch_array
MySQL Functions


Fetch a result row as an associative array, a numeric array, or both

mysql_escape_string
mysql_fetch_assoc
MySQL Functions
PHP Manual

mysql_fetch_array

(PHP 4, PHP 5)

mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Description

array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )

Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

result_type

The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.

Return Values

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name.

Examples

Example #1 Query with aliased duplicate field names

SELECT table1.field AS foo, table2.field AS bar FROM table1, table2

Example #2 mysql_fetch_array() with MYSQL_NUM

<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
    die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    printf("ID: %s  Name: %s", $row[0], $row[1]);
}

mysql_free_result($result);
?>

Example #3 mysql_fetch_array() with MYSQL_ASSOC

<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
    die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    printf("ID: %s  Name: %s", $row["id"], $row["name"]);
}

mysql_free_result($result);
?>

Example #4 mysql_fetch_array() with MYSQL_BOTH

<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
    die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    printf ("ID: %s  Name: %s", $row[0], $row["name"]);
}

mysql_free_result($result);
?>

Notes

Note: Performance
An important thing to note is that using mysql_fetch_array() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_data_seek() - Move internal result pointer
  • mysql_query() - Send a MySQL query

mysql_escape_string
mysql_fetch_assoc
MySQL Functions


Fetch a result row as an associative array

mysql_fetch_array
mysql_fetch_field
MySQL Functions
PHP Manual

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc — Fetch a result row as an associative array

Description

array mysql_fetch_assoc ( resource $result )

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases.

Examples

Example #1 An expanded mysql_fetch_assoc() example

<?php

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}

if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}

$sql = "SELECT id as userid, fullname, userstatus
        FROM   sometable
        WHERE  userstatus = 1";

$result = mysql_query($sql);

if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//       then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

mysql_free_result($result);

?>

Notes

Note: Performance
An important thing to note is that using mysql_fetch_assoc() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_data_seek() - Move internal result pointer
  • mysql_query() - Send a MySQL query
  • mysql_error() - Returns the text of the error message from previous MySQL operation

mysql_fetch_array
mysql_fetch_field
MySQL Functions


Get column information from a result and return as an object

mysql_fetch_assoc
mysql_fetch_lengths
MySQL Functions
PHP Manual

mysql_fetch_field

(PHP 4, PHP 5)

mysql_fetch_field — Get column information from a result and return as an object

Description

object mysql_fetch_field ( resource $result [, int $field_offset = 0 ] )

Returns an object containing field information. This function can be used to obtain information about fields in the provided query result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. If the field offset is not specified, the next field that was not yet retrieved by this function is retrieved. The field_offset starts at 0.

Return Values

Returns an object containing field information. The properties of the object are:

  • name - column name
  • table - name of the table the column belongs to
  • def - default value of the column
  • max_length - maximum length of the column
  • not_null - 1 if the column cannot be NULL
  • primary_key - 1 if the column is a primary key
  • unique_key - 1 if the column is a unique key
  • multiple_key - 1 if the column is a non-unique key
  • numeric - 1 if the column is numeric
  • blob - 1 if the column is a BLOB
  • type - the type of the column
  • unsigned - 1 if the column is unsigned
  • zerofill - 1 if the column is zero-filled

Examples

Example #1 mysql_fetch_field() example

<?php
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$conn) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('database');
$result = mysql_query('select * from table');
if (!$result) {
    die('Query failed: ' . mysql_error());
}
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
    echo "Information for column $i:<br />\n";
    $meta = mysql_fetch_field($result, $i);
    if (!$meta) {
        echo "No information available<br />\n";
    }
    echo "<pre>
blob:         $meta->blob
max_length:   $meta->max_length
multiple_key: $meta->multiple_key
name:         $meta->name
not_null:     $meta->not_null
numeric:      $meta->numeric
primary_key:  $meta->primary_key
table:        $meta->table
type:         $meta->type
default:      $meta->def
unique_key:   $meta->unique_key
unsigned:     $meta->unsigned
zerofill:     $meta->zerofill
</pre>";
    $i++;
}
mysql_free_result($result);
?>

Notes

Note: Field names returned by this function are case-sensitive.

See Also

  • mysql_field_seek() - Set result pointer to a specified field offset

mysql_fetch_assoc
mysql_fetch_lengths
MySQL Functions


Get the length of each output in a result

mysql_fetch_field
mysql_fetch_object
MySQL Functions
PHP Manual

mysql_fetch_lengths

(PHP 4, PHP 5)

mysql_fetch_lengths — Get the length of each output in a result

Description

array mysql_fetch_lengths ( resource $result )

Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL.

mysql_fetch_lengths() stores the lengths of
each result column in the last row returned by
mysql_fetch_row(),
mysql_fetch_assoc(),
mysql_fetch_array(), and
mysql_fetch_object() in an array, starting at
offset 0.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

An array of lengths on success or FALSE on failure.

Examples

Example #1 A mysql_fetch_lengths() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row     = mysql_fetch_assoc($result);
$lengths = mysql_fetch_lengths($result);

print_r($row);
print_r($lengths);
?>

The above example will output something similar to:

Array
(
    [id] => 42
    [email] => user@example.com
)
Array
(
    [0] => 2
    [1] => 16
)

See Also

  • mysql_field_len() - Returns the length of the specified field
  • mysql_fetch_row() - Get a result row as an enumerated array
  • strlen() - Get string length

mysql_fetch_field
mysql_fetch_object
MySQL Functions


Fetch a result row as an object

mysql_fetch_lengths
mysql_fetch_row
MySQL Functions
PHP Manual

mysql_fetch_object

(PHP 4, PHP 5)

mysql_fetch_object — Fetch a result row as an object

Description

object mysql_fetch_object ( resource $result [, string $class_name [, array $params ]] )

Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

class_name

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

Return Values

Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows.

Changelog

Version | Description
5.0.0 | Added the ability to return as a different object.

Examples

Example #1 mysql_fetch_object() example

<?php
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
mysql_free_result($result);
?>

Example #2 mysql_fetch_object() example

<?php
class foo {
    public $name;
}

mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");

$result = mysql_query("select name from mytable limit 1");
$obj = mysql_fetch_object($result, 'foo');
var_dump($obj);
?>

Notes

Note: Performance
Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant).

Note: mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_data_seek() - Move internal result pointer
  • mysql_query() - Send a MySQL query

mysql_fetch_lengths
mysql_fetch_row
MySQL Functions


Get a result row as an enumerated array

mysql_fetch_object
mysql_field_flags
MySQL Functions
PHP Manual

mysql_fetch_row

(PHP 4, PHP 5)

mysql_fetch_row — Get a result row as an enumerated array

Description

array mysql_fetch_row ( resource $result )

Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Examples

Example #1 Fetching one row with mysql_fetch_row()

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>

Notes

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_fetch_object() - Fetch a result row as an object
  • mysql_data_seek() - Move internal result pointer
  • mysql_fetch_lengths() - Get the length of each output in a result
  • mysql_result() - Get result data

mysql_fetch_object
mysql_field_flags
MySQL Functions


Get the flags associated with the specified field in a result

mysql_fetch_row
mysql_field_len
MySQL Functions
PHP Manual

mysql_field_flags

(PHP 4, PHP 5)

mysql_field_flags — Get the flags associated with the specified field in a result

Description

string mysql_field_flags ( resource $result , int $field_offset )

mysql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode().

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

Returns a string of flags associated with the result or FALSE on failure.

The following flags are reported, if your version of MySQL is current enough to support them: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment" and "timestamp".

Examples

Example #1 A mysql_field_flags() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$flags = mysql_field_flags($result, 0);

echo $flags;
print_r(explode(' ', $flags));
?>

The above example will output something similar to:

not_null primary_key auto_increment
Array
(
    [0] => not_null
    [1] => primary_key
    [2] => auto_increment
)

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldflags()

See Also

  • mysql_field_type() - Get the type of the specified field in a result
  • mysql_field_len() - Returns the length of the specified field

mysql_fetch_row
mysql_field_len
MySQL Functions


Returns the length of the specified field

mysql_field_flags
mysql_field_name
MySQL Functions
PHP Manual

mysql_field_len

(PHP 4, PHP 5)

mysql_field_len — Returns the length of the specified field

Description

int mysql_field_len ( resource $result , int $field_offset )

mysql_field_len() returns the length of the specified field.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The length of the specified field index on success or FALSE on failure.

Examples

Example #1 mysql_field_len() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

// Will get the length of the id field as specified in the database
// schema.
$length = mysql_field_len($result, 0);
echo $length;
?>

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldlen()

See Also

  • mysql_fetch_lengths() - Get the length of each output in a result
  • strlen() - Get string length

mysql_field_flags
mysql_field_name
MySQL Functions


Get the name of the specified field in a result

mysql_field_len
mysql_field_seek
MySQL Functions
PHP Manual

mysql_field_name

(PHP 4, PHP 5)

mysql_field_name — Get the name of the specified field in a result

Description

string mysql_field_name ( resource $result , int $field_offset )

mysql_field_name() returns the name of the specified field index.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The name of the specified field index on success or FALSE on failure.

Examples

Example #1 mysql_field_name() example

<?php
/* The users table consists of three fields:
*   user_id
*   username
*   password.
*/
$link = @mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'mydb';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
    die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from users', $link);

echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 2);
?>

The above example will output:

user_id
password

Notes

Note: Field names returned by this function are case-sensitive.

Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldname()

See Also

  • mysql_field_type() - Get the type of the specified field in a result
  • mysql_field_len() - Returns the length of the specified field

mysql_field_len
mysql_field_seek
MySQL Functions


Set result pointer to a specified field offset

mysql_field_name
mysql_field_table
MySQL Functions
PHP Manual

mysql_field_seek

(PHP 4, PHP 5)

mysql_field_seek — Set result pointer to a specified field offset

Description

bool mysql_field_seek ( resource $result , int $field_offset )

Seeks to the specified field offset. If the next call to mysql_fetch_field() doesn't include a field offset, the field offset specified in mysql_field_seek() will be returned.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysql_fetch_field() - Get column information from a result and return as an object

mysql_field_name
mysql_field_table
MySQL Functions


Get name of the table the specified field is in

mysql_field_seek
mysql_field_type
MySQL Functions
PHP Manual

mysql_field_table

(PHP 4, PHP 5)

mysql_field_table — Get name of the table the specified field is in

Description

string mysql_field_table ( resource $result , int $field_offset )

Returns the name of the table that the specified field is in.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The name of the table on success.

Examples

Example #1 A mysql_field_table() example

<?php

$query = "SELECT account.*, country.* FROM account, country WHERE country.name = 'Portugal' AND account.country_id = country.id";

// get the result from the DB
$result = mysql_query($query);

// Lists the table name and then the field name
for ($i = 0; $i < mysql_num_fields($result); ++$i) {
    $table = mysql_field_table($result, $i);
    $field = mysql_field_name($result, $i);

    echo  "$table: $field\n";
}

?>

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldtable()

See Also

  • mysql_list_tables() - List tables in a MySQL database

mysql_field_seek
mysql_field_type
MySQL Functions


Get the type of the specified field in a result

mysql_field_table
mysql_free_result
MySQL Functions
PHP Manual

mysql_field_type

(PHP 4, PHP 5)

mysql_field_type — Get the type of the specified field in a result

Description

string mysql_field_type ( resource $result , int $field_offset )

mysql_field_type() is similar to the mysql_field_name() function. The arguments are identical, but the field type is returned instead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The returned field type will be one of "int", "real", "string", "blob", and others as detailed in the » MySQL documentation.

Examples

Example #1 mysql_field_type() example

<?php
mysql_connect("localhost", "mysql_username", "mysql_password");
mysql_select_db("mysql");
$result = mysql_query("SELECT * FROM func");
$fields = mysql_num_fields($result);
$rows   = mysql_num_rows($result);
$table  = mysql_field_table($result, 0);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)\n";
echo "The table has the following fields:\n";
for ($i=0; $i < $fields; $i++) {
    $type  = mysql_field_type($result, $i);
    $name  = mysql_field_name($result, $i);
    $len   = mysql_field_len($result, $i);
    $flags = mysql_field_flags($result, $i);
    echo $type . " " . $name . " " . $len . " " . $flags . "\n";
}
mysql_free_result($result);
mysql_close();
?>

The above example will output something similar to:

Your 'func' table has 4 fields and 1 record(s)
The table has the following fields:
string name 64 not_null primary_key binary
int ret 1 not_null
string dl 128 not_null
string type 9 not_null enum

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldtype()

See Also

  • mysql_field_name() - Get the name of the specified field in a result
  • mysql_field_len() - Returns the length of the specified field

mysql_field_table
mysql_free_result
MySQL Functions


Free result memory

mysql_field_type
mysql_get_client_info
MySQL Functions
PHP Manual

mysql_free_result

(PHP 4, PHP 5)

mysql_free_result — Free result memory

Description

bool mysql_free_result ( resource $result )

mysql_free_result() will free all memory associated with the result identifier result .

mysql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns TRUE on success or FALSE on failure.

If a non-resource is used for the result , an error of level E_WARNING will be emitted. It's worth noting that mysql_query() only returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries.

Examples

Example #1 A mysql_free_result() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
/* Use the result, assuming we're done with it afterwards */
$row = mysql_fetch_assoc($result);

/* Now we free up the result and continue on with our script */
mysql_free_result($result);

echo $row['id'];
echo $row['email'];
?>

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_freeresult()

See Also

  • mysql_query() - Send a MySQL query
  • is_resource() - Finds whether a variable is a resource

mysql_field_type
mysql_get_client_info
MySQL Functions


Get MySQL client info

mysql_free_result
mysql_get_host_info
MySQL Functions
PHP Manual

mysql_get_client_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_client_info — Get MySQL client info

Description

string mysql_get_client_info ( void )

mysql_get_client_info() returns a string that represents the client library version.

Return Values

The MySQL client version.

Examples

Example #1 mysql_get_client_info() example

<?php
printf("MySQL client info: %s\n", mysql_get_client_info());
?>

The above example will output something similar to:

MySQL client info: 3.23.39

See Also

  • mysql_get_host_info() - Get MySQL host info
  • mysql_get_proto_info() - Get MySQL protocol info
  • mysql_get_server_info() - Get MySQL server info

mysql_free_result
mysql_get_host_info
MySQL Functions


Get MySQL host info

mysql_get_client_info
mysql_get_proto_info
MySQL Functions
PHP Manual

mysql_get_host_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_host_info — Get MySQL host info

Description

string mysql_get_host_info ([ resource $link_identifier ] )

Describes the type of connection in use for the connection, including the server host name.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns a string describing the type of MySQL connection in use for the connection or FALSE on failure.

Examples

Example #1 mysql_get_host_info() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
printf("MySQL host info: %s\n", mysql_get_host_info());
?>

The above example will output something similar to:

MySQL host info: Localhost via UNIX socket

See Also

  • mysql_get_client_info() - Get MySQL client info
  • mysql_get_proto_info() - Get MySQL protocol info
  • mysql_get_server_info() - Get MySQL server info

mysql_get_client_info
mysql_get_proto_info
MySQL Functions


Get MySQL protocol info

mysql_get_host_info
mysql_get_server_info
MySQL Functions
PHP Manual

mysql_get_proto_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_proto_info — Get MySQL protocol info

Description

int mysql_get_proto_info ([ resource $link_identifier ] )

Retrieves the MySQL protocol.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the MySQL protocol on success or FALSE on failure.

Examples

Example #1 mysql_get_proto_info() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
printf("MySQL protocol version: %s\n", mysql_get_proto_info());
?>

The above example will output something similar to:

MySQL protocol version: 10

See Also

  • mysql_get_client_info() - Get MySQL client info
  • mysql_get_host_info() - Get MySQL host info
  • mysql_get_server_info() - Get MySQL server info

mysql_get_host_info
mysql_get_server_info
MySQL Functions


Get MySQL server info

mysql_get_proto_info
mysql_info
MySQL Functions
PHP Manual

mysql_get_server_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_server_info — Get MySQL server info

Description

string mysql_get_server_info ([ resource $link_identifier ] )

Retrieves the MySQL server version.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the MySQL server version on success or FALSE on failure.

Examples

Example #1 mysql_get_server_info() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
printf("MySQL server version: %s\n", mysql_get_server_info());
?>

The above example will output something similar to:

MySQL server version: 4.0.1-alpha

See Also

  • mysql_get_client_info() - Get MySQL client info
  • mysql_get_host_info() - Get MySQL host info
  • mysql_get_proto_info() - Get MySQL protocol info
  • phpversion() - Gets the current PHP version

mysql_get_proto_info
mysql_info
MySQL Functions


Get information about the most recent query

mysql_get_server_info
mysql_insert_id
MySQL Functions
PHP Manual

mysql_info

(PHP 4 >= 4.3.0, PHP 5)

mysql_info — Get information about the most recent query

Description

string mysql_info ([ resource $link_identifier ] )

Returns detailed information about the last query.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns information about the statement on success, or FALSE on failure. See the example below for which statements provide information, and what the returned value may look like. Statements that are not listed will return FALSE.

Examples

Example #1 Relevant MySQL Statements

Statements that return string values. The numbers are only for illustrating purpose; their values will correspond to the query.

INSERT INTO ... SELECT ...
String format: Records: 23 Duplicates: 0 Warnings: 0
INSERT INTO ... VALUES (...),(...),(...)...
String format: Records: 37 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...
String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE
String format: Records: 60 Duplicates: 0 Warnings: 0
UPDATE
String format: Rows matched: 65 Changed: 65 Warnings: 0

Notes

Note: mysql_info() returns a non-FALSE value for the INSERT ... VALUES statement only if multiple value lists are specified in the statement.

See Also

  • mysql_affected_rows() - Get number of affected rows in previous MySQL operation
  • mysql_insert_id() - Get the ID generated in the last query
  • mysql_stat() - Get current system status

mysql_get_server_info
mysql_insert_id
MySQL Functions


Get the ID generated in the last query

mysql_info
mysql_list_dbs
MySQL Functions
PHP Manual

mysql_insert_id

(PHP 4, PHP 5)

mysql_insert_id — Get the ID generated in the last query

Description

int mysql_insert_id ([ resource $link_identifier ] )

Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.

Examples

Example #1 mysql_insert_id() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>

Notes

Caution

mysql_insert_id() will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. For more information about PHP's maximum integer values, please see the integer documentation.

Note: Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.

Note: The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries.

See Also

  • mysql_query() - Send a MySQL query
  • mysql_info() - Get information about the most recent query

mysql_info
mysql_list_dbs
MySQL Functions


List databases available on a MySQL server

mysql_insert_id
mysql_list_fields
MySQL Functions
PHP Manual

mysql_list_dbs

(PHP 4, PHP 5)

mysql_list_dbs — List databases available on a MySQL server

Description

resource mysql_list_dbs ([ resource $link_identifier ] )

Returns a result pointer containing the databases available from the current mysql daemon.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns a result pointer resource on success, or FALSE on failure. Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

Examples

Example #1 mysql_list_dbs() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);

while ($row = mysql_fetch_object($db_list)) {
     echo $row->Database . "\n";
}
?>

The above example will output something similar to:

database1
database2
database3

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_listdbs()

See Also

  • mysql_db_name() - Get result data
  • mysql_select_db() - Select a MySQL database

mysql_insert_id
mysql_list_fields
MySQL Functions


List MySQL table fields

mysql_list_dbs
mysql_list_processes
MySQL Functions
PHP Manual

mysql_list_fields

(PHP 4, PHP 5)

mysql_list_fields — List MySQL table fields

Description

resource mysql_list_fields ( string $database_name , string $table_name [, resource $link_identifier ] )

Retrieves information about the given table name.

This function is deprecated. It is preferable to use mysql_query() to issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.

Parameters

database_name

The name of the database that's being queried.

table_name

The name of the table that's being queried.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

A result pointer resource on success, or FALSE on failure.

The returned result can be used with mysql_field_flags(),
mysql_field_len(),
mysql_field_name() and
mysql_field_type().

Examples

Example #1 Alternate to deprecated mysql_list_fields()

<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        print_r($row);
    }
}
?>

The above example will output something similar to:

Array
(
    [Field] => id
    [Type] => int(7)
    [Null] =>
    [Key] => PRI
    [Default] =>
    [Extra] => auto_increment
)
Array
(
    [Field] => email
    [Type] => varchar(100)
    [Null] =>
    [Key] =>
    [Default] =>
    [Extra] =>
)

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_listfields()

See Also

  • mysql_field_flags() - Get the flags associated with the specified field in a result
  • mysql_info() - Get information about the most recent query

mysql_list_dbs
mysql_list_processes
MySQL Functions


List MySQL processes

mysql_list_fields
mysql_list_tables
MySQL Functions
PHP Manual

mysql_list_processes

(PHP 4 >= 4.3.0, PHP 5)

mysql_list_processes — List MySQL processes

Description

resource mysql_list_processes ([ resource $link_identifier ] )

Retrieves the current MySQL server threads.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

A result pointer resource on success or FALSE on failure.

Examples

Example #1 mysql_list_processes() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$result = mysql_list_processes($link);
while ($row = mysql_fetch_assoc($result)){
    printf("%s %s %s %s %s\n", $row["Id"], $row["Host"], $row["db"],
        $row["Command"], $row["Time"]);
}
mysql_free_result($result);
?>

The above example will output something similar to:

1 localhost test Processlist 0
4 localhost mysql sleep 5

See Also

  • mysql_thread_id() - Return the current thread ID
  • mysql_stat() - Get current system status

mysql_list_fields
mysql_list_tables
MySQL Functions


List tables in a MySQL database

mysql_list_processes
mysql_num_fields
MySQL Functions
PHP Manual

mysql_list_tables

(PHP 4, PHP 5)

mysql_list_tables — List tables in a MySQL database

Description

resource mysql_list_tables ( string $database [, resource $link_identifier ] )

Retrieves a list of table names from a MySQL database.

This function is deprecated. It is preferable to use mysql_query() to issue a SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.

Parameters

database

The name of the database

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

A result pointer resource on success or FALSE on failure.

Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

Changelog

Version | Description
4.3.7 | This function became deprecated.

Examples

Example #1 mysql_list_tables() alternative example

<?php
$dbname = 'mysql_dbname';

if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
    echo 'Could not connect to mysql';
    exit;
}

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);

if (!$result) {
    echo "DB Error, could not list tables\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_row($result)) {
    echo "Table: {$row[0]}\n";
}

mysql_free_result($result);
?>

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_listtables()

See Also

  • mysql_list_dbs() - List databases available on a MySQL server
  • mysql_tablename() - Get table name of field

mysql_list_processes
mysql_num_fields
MySQL Functions


Get number of fields in result

mysql_list_tables
mysql_num_rows
MySQL Functions
PHP Manual

mysql_num_fields

(PHP 4, PHP 5)

mysql_num_fields — Get number of fields in result

Description

int mysql_num_fields ( resource $result )

Retrieves the number of fields from a query.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns the number of fields in the result set resource on success or FALSE on failure.

Examples

Example #1 A mysql_num_fields() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

/* returns 2 because id,email === two fields */
echo mysql_num_fields($result);
?>

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_numfields()

See Also

  • mysql_select_db() - Select a MySQL database
  • mysql_query() - Send a MySQL query
  • mysql_fetch_field() - Get column information from a result and return as an object
  • mysql_num_rows() - Get number of rows in result

mysql_list_tables
mysql_num_rows
MySQL Functions


Get number of rows in result

mysql_num_fields
mysql_pconnect
MySQL Functions
PHP Manual

mysql_num_rows

(PHP 4, PHP 5)

mysql_num_rows — Get number of rows in result

Description

int mysql_num_rows ( resource $result )

Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

The number of rows in a result set on success or FALSE on failure.

Examples

Example #1 mysql_num_rows() example

<?php

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

echo "$num_rows Rows\n";

?>

Notes

Note: If you use mysql_unbuffered_query(), mysql_num_rows() will not return the correct value until all the rows in the result set have been retrieved.

Note: For backward compatibility, the following deprecated alias may be used: mysql_numrows()

See Also

  • mysql_affected_rows() - Get number of affected rows in previous MySQL operation
  • mysql_connect() - Open a connection to a MySQL Server
  • mysql_data_seek() - Move internal result pointer
  • mysql_select_db() - Select a MySQL database
  • mysql_query() - Send a MySQL query

mysql_num_fields
mysql_pconnect
MySQL Functions


Open a persistent connection to a MySQL server

mysql_num_rows
mysql_ping
MySQL Functions
PHP Manual

mysql_pconnect

(PHP 4, PHP 5)

mysql_pconnect — Open a persistent connection to a MySQL server

Description

resource mysql_pconnect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, int $client_flags ]]]] )

Establishes a persistent connection to a MySQL server.

mysql_pconnect() acts very much like mysql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).

This type of link is therefore called 'persistent'.

Parameters

server

The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost.

If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'

username

The username. Default value is the name of the user that owns the server process.

password

The password. Default value is an empty password.

client_flags

The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE.

Return Values

Returns a MySQL persistent link identifier on success, or FALSE on failure.

Changelog

Version | Description
4.3.0 | Added the client_flags parameter.

Notes

Note: Note, that these kind of links only work if you are using a module version of PHP. See the Persistent Database Connections section for more information.

Warning

Using persistent connections can require a bit of tuning of your Apache and MySQL configurations to ensure that you do not exceed the number of connections allowed by MySQL.

Note: You can suppress the error message on failure by prepending a @ to the function name.

See Also

  • mysql_connect() - Open a connection to a MySQL Server
  • Persistent Database Connections

mysql_num_rows
mysql_ping
MySQL Functions


Ping a server connection or reconnect if there is no connection

mysql_pconnect
mysql_query
MySQL Functions
PHP Manual

mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

mysql_ping — Ping a server connection or reconnect if there is no connection

Description

bool mysql_ping ([ resource $link_identifier ] )

Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.

Note: Since MySQL 5.0.13, automatic reconnection feature is disabled.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns TRUE if the connection to the server MySQL server is working, otherwise FALSE.

Examples

Example #1 A mysql_ping() example

<?php
set_time_limit(0);

$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
$db   = mysql_select_db('mydb');

/* Assuming this query will take a long time */
$result = mysql_query($sql);
if (!$result) {
    echo 'Query #1 failed, exiting.';
    exit;
}

/* Make sure the connection is still alive, if not, try to reconnect */
if (!mysql_ping($conn)) {
    echo 'Lost connection, exiting after query #1';
    exit;
}
mysql_free_result($result);

/* So the connection is still alive, let's run another query */
$result2 = mysql_query($sql2);
?>

See Also

  • mysql_thread_id() - Return the current thread ID
  • mysql_list_processes() - List MySQL processes

mysql_pconnect
mysql_query
MySQL Functions


Send a MySQL query

mysql_ping
mysql_real_escape_string
MySQL Functions
PHP Manual

mysql_query

(PHP 4, PHP 5)

mysql_query — Send a MySQL query

Description

resource mysql_query ( string $query [, resource $link_identifier ] )

mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier .

Parameters

query

A SQL query

The query string should not end with a semicolon. Data inside the query should be properly escaped.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.

Examples

Example #1 Invalid Query

The following query is syntactically invalid, so mysql_query() fails and returns FALSE.

<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

?>

Example #2 Valid Query

The following query is valid, so mysql_query() returns a resource.

<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname  = 'fox';

// Formulate Query
// This is the best way to perform a SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
    mysql_real_escape_string($firstname),
    mysql_real_escape_string($lastname));

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
    echo $row['firstname'];
    echo $row['lastname'];
    echo $row['address'];
    echo $row['age'];
}

// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>

See Also

  • mysql_connect() - Open a connection to a MySQL Server
  • mysql_error() - Returns the text of the error message from previous MySQL operation
  • mysql_real_escape_string() - Escapes special characters in a string for use in a SQL statement
  • mysql_result() - Get result data
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_unbuffered_query() - Send an SQL query to MySQL without fetching and buffering the result rows.

mysql_ping
mysql_real_escape_string
MySQL Functions


Escapes special characters in a string for use in a SQL statement

mysql_query
mysql_result
MySQL Functions
PHP Manual

mysql_real_escape_string

(PHP 4 >= 4.3.0, PHP 5)

mysql_real_escape_string — Escapes special characters in a string for use in a SQL statement

Description

string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )

Escapes special characters in the unescaped_string , taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

Parameters

unescaped_string

The string that is to be escaped.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the escaped string, or FALSE on error.

Examples

Example #1 Simple mysql_real_escape_string() example

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));
?>

Example #2 An example SQL Injection Attack

<?php
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// This means the query sent to MySQL would be:
echo $query;
?>

The query sent to MySQL:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

This would allow anyone to log in without a valid password.

Notes

Note: A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.

Note: If magic_quotes_gpc is enabled, first apply stripslashes() to the data. Using this function on data which has already been escaped will escape the data twice.

Note: If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks.

Note: mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.

See Also

  • mysql_client_encoding() - Returns the name of the character set
  • addslashes() - Quote string with slashes
  • stripslashes() - Un-quotes a quoted string
  • The magic_quotes_gpc directive
  • The magic_quotes_runtime directive

mysql_query
mysql_result
MySQL Functions


Get result data

mysql_real_escape_string
mysql_select_db
MySQL Functions
PHP Manual

mysql_result

(PHP 4, PHP 5)

mysql_result — Get result data

Description

string mysql_result ( resource $result , int $row [, mixed $field = 0 ] )

Retrieves the contents of one cell from a MySQL result set.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mysql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

row

The row number from the result that's being retrieved. Row numbers start at 0.

field

The name or offset of the field being retrieved.

It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.

Return Values

The contents of one cell from a MySQL result set on success, or FALSE on failure.

Examples

Example #1 mysql_result() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('database_name')) {
    die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT name FROM work.employee');
if (!$result) {
    die('Could not query:' . mysql_error());
}
echo mysql_result($result, 2); // outputs third employee's name

mysql_close($link);
?>

Notes

Note: Calls to mysql_result() should not be mixed with calls to other functions that deal with the result set.

See Also

  • mysql_fetch_row() - Get a result row as an enumerated array
  • mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_assoc() - Fetch a result row as an associative array
  • mysql_fetch_object() - Fetch a result row as an object

mysql_real_escape_string
mysql_select_db
MySQL Functions


Select a MySQL database

mysql_result
mysql_set_charset
MySQL Functions
PHP Manual

mysql_select_db

(PHP 4, PHP 5)

mysql_select_db — Select a MySQL database

Description

bool mysql_select_db ( string $database_name [, resource $link_identifier ] )

Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.

Parameters

database_name

The name of the database that is to be selected.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysql_select_db() example

<?php

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}
?>

Notes

Note: For backward compatibility, the following deprecated alias may be used: mysql_selectdb()

See Also

  • mysql_connect() - Open a connection to a MySQL Server
  • mysql_pconnect() - Open a persistent connection to a MySQL server
  • mysql_query() - Send a MySQL query

mysql_result
mysql_set_charset
MySQL Functions


Sets the client character set

mysql_select_db
mysql_stat
MySQL Functions
PHP Manual

mysql_set_charset

(PHP 5 >= 5.2.3)

mysql_set_charset — Sets the client character set

Description

bool mysql_set_charset ( string $charset [, resource $link_identifier ] )

Sets the default character set for the current connection.

Parameters

charset

A valid character set name.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function requires MySQL 5.0.7 or later.

Note: This is the preferred way to change the charset. Using mysql_query() to execute SET NAMES .. is not recommended.

See Also

  • mysql_client_encoding() - Returns the name of the character set
  • » List of character sets that MySQL supports

mysql_select_db
mysql_stat
MySQL Functions


Get current system status

mysql_set_charset
mysql_tablename
MySQL Functions
PHP Manual

mysql_stat

(PHP 4 >= 4.3.0, PHP 5)

mysql_stat — Get current system status

Description

string mysql_stat ([ resource $link_identifier ] )

mysql_stat() returns the current server status.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns a string with the status for uptime, threads, queries, open tables, flush tables and queries per second. For a complete list of other status variables, you have to use the SHOW STATUS SQL command. If link_identifier is invalid, NULL is returned.

Examples

Example #1 mysql_stat() example

<?php
$link   = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$status = explode('  ', mysql_stat($link));
print_r($status);
?>

The above example will output something similar to:

Array
(
    [0] => Uptime: 5380
    [1] => Threads: 2
    [2] => Questions: 1321299
    [3] => Slow queries: 0
    [4] => Opens: 26
    [5] => Flush tables: 1
    [6] => Open tables: 17
    [7] => Queries per second avg: 245.595
)

Example #2 Alternative mysql_stat() example

<?php
$link   = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_query('SHOW STATUS', $link);
while ($row = mysql_fetch_assoc($result)) {
    echo $row['Variable_name'] . ' = ' . $row['Value'] . "\n";
}
?>

The above example will output something similar to:

back_log = 50
basedir = /usr/local/
bdb_cache_size = 8388600
bdb_log_buffer_size = 32768
bdb_home = /var/db/mysql/
bdb_max_lock = 10000
bdb_logdir =
bdb_shared_data = OFF
bdb_tmpdir = /var/tmp/
...

See Also

  • mysql_get_server_info() - Get MySQL server info
  • mysql_list_processes() - List MySQL processes

mysql_set_charset
mysql_tablename
MySQL Functions


Get table name of field

mysql_stat
mysql_thread_id
MySQL Functions
PHP Manual

mysql_tablename

(PHP 4, PHP 5)

mysql_tablename — Get table name of field

Description

string mysql_tablename ( resource $result , int $i )

Retrieves the table name from a result .

This function deprecated. It is preferable to use mysql_query() to issue a SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.

Parameters

result

A result pointer resource that's returned from mysql_list_tables().

i

The integer index (row/table number)

Return Values

The name of the table on success or FALSE on failure.

Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

Examples

Example #1 mysql_tablename() example

<?php
mysql_connect("localhost", "mysql_user", "mysql_password");
$result = mysql_list_tables("mydb");
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
    echo "Table: ", mysql_tablename($result, $i), "\n";
}

mysql_free_result($result);
?>

Notes

Note: The mysql_num_rows() function may be used to determine the number of tables in the result pointer.

See Also

  • mysql_list_tables() - List tables in a MySQL database
  • mysql_field_table() - Get name of the table the specified field is in
  • mysql_db_name() - Get result data

mysql_stat
mysql_thread_id
MySQL Functions


Return the current thread ID

mysql_tablename
mysql_unbuffered_query
MySQL Functions
PHP Manual

mysql_thread_id

(PHP 4 >= 4.3.0, PHP 5)

mysql_thread_id — Return the current thread ID

Description

int mysql_thread_id ([ resource $link_identifier ] )

Retrieves the current thread ID. If the connection is lost, and a reconnect with mysql_ping() is executed, the thread ID will change. This means only retrieve the thread ID when needed.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

The thread ID on success or FALSE on failure.

Examples

Example #1 mysql_thread_id() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){
    printf("current thread id is %d\n", $thread_id);
}
?>

The above example will output something similar to:

current thread id is 73

See Also

  • mysql_ping() - Ping a server connection or reconnect if there is no connection
  • mysql_list_processes() - List MySQL processes

mysql_tablename
mysql_unbuffered_query
MySQL Functions


Send an SQL query to MySQL without fetching and buffering the result rows.

mysql_thread_id
Mysqli
MySQL Functions
PHP Manual

mysql_unbuffered_query

(PHP 4 >= 4.0.6, PHP 5)

mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows.

Description

resource mysql_unbuffered_query ( string $query [, resource $link_identifier ] )

mysql_unbuffered_query() sends the SQL query query to MySQL without automatically fetching and buffering the result rows as mysql_query() does. This saves a considerable amount of memory with SQL queries that produce large result sets, and you can start working on the result set immediately after the first row has been retrieved as you don't have to wait until the complete SQL query has been performed. To use mysql_unbuffered_query() while multiple database connections are open, you must specify the optional parameter link_identifier to identify which connection you want to use.

Parameters

query

The SQL query to execute.

Data inside the query should be properly escaped.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_unbuffered_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_unbuffered_query() returns TRUE on success or FALSE on error.

Notes

Note: The benefits of mysql_unbuffered_query() come at a cost: you cannot use mysql_num_rows() and mysql_data_seek() on a result set returned from mysql_unbuffered_query(). You also have to fetch all result rows from an unbuffered SQL query before you can send a new SQL query to MySQL.

See Also

  • mysql_query() - Send a MySQL query

mysql_thread_id
Mysqli
MySQL Functions


Alias for mysqli_stmt_bind_param

Aliases and deprecated Mysqli Functions
mysqli_bind_result
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_bind_param

(PHP 5)

mysqli_bind_param — Alias for mysqli_stmt_bind_param()

Description

This function is an alias of mysqli_stmt_bind_param().

Notes

Note: mysqli_bind_param() is deprecated and will be removed.

See Also

  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

Aliases and deprecated Mysqli Functions
mysqli_bind_result
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_bind_result

mysqli_bind_param
mysqli_client_encoding
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_bind_result

(PHP 5)

mysqli_bind_result — Alias for mysqli_stmt_bind_result()

Description

This function is an alias of mysqli_stmt_bind_result().

Notes

Note: mysqli_bind_result() is deprecated and will be removed.

See Also

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage

mysqli_bind_param
mysqli_client_encoding
Aliases and deprecated Mysqli Functions


Alias of mysqli_character_set_name

mysqli_bind_result
mysqli_disable_reads_from_master
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_client_encoding

(PHP 5)

mysqli_client_encoding — Alias of mysqli_character_set_name()

Description

This function is an alias of mysqli_character_set_name().

See Also

  • mysqli_real_escape_string() - Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

mysqli_bind_result
mysqli_disable_reads_from_master
Aliases and deprecated Mysqli Functions


Disable reads from master

mysqli_client_encoding
mysqli_disable_rpl_parse
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_disable_reads_from_master

mysqli->disable_reads_from_master

(PHP 5)

mysqli_disable_reads_from_master -- mysqli->disable_reads_from_master — Disable reads from master

Description

Procedural style:

bool mysqli_disable_reads_from_master ( mysqli $link )

Object oriented style (method):

mysqli
void disable_reads_from_master ( void )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

mysqli_client_encoding
mysqli_disable_rpl_parse
Aliases and deprecated Mysqli Functions


Disable RPL parse

mysqli_disable_reads_from_master
mysqli_enable_reads_from_master
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_disable_rpl_parse

(PHP 5)

mysqli_disable_rpl_parse — Disable RPL parse

Description

bool mysqli_disable_rpl_parse ( mysqli $link )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

mysqli_disable_reads_from_master
mysqli_enable_reads_from_master
Aliases and deprecated Mysqli Functions


Enable reads from master

mysqli_disable_rpl_parse
mysqli_enable_rpl_parse
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_enable_reads_from_master

(PHP 5)

mysqli_enable_reads_from_master — Enable reads from master

Description

bool mysqli_enable_reads_from_master ( mysqli $link )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

mysqli_disable_rpl_parse
mysqli_enable_rpl_parse
Aliases and deprecated Mysqli Functions


Enable RPL parse

mysqli_enable_reads_from_master
mysqli_escape_string
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_enable_rpl_parse

(PHP 5)

mysqli_enable_rpl_parse — Enable RPL parse

Description

bool mysqli_enable_rpl_parse ( mysqli $link )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

mysqli_enable_reads_from_master
mysqli_escape_string
Aliases and deprecated Mysqli Functions


Alias of mysqli_real_escape_string

mysqli_enable_rpl_parse
mysqli_execute
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_escape_string

(PHP 5)

mysqli_escape_string — Alias of mysqli_real_escape_string()

Description

This function is an alias of mysqli_real_escape_string().

See Also

  • mysqli_real_escape_string() - Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

mysqli_enable_rpl_parse
mysqli_execute
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_execute

mysqli_escape_string
mysqli_fetch
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_execute

(PHP 5)

mysqli_execute — Alias for mysqli_stmt_execute()

Description

This function is an alias of mysqli_stmt_execute().

Notes

Note: mysqli_execute() is deprecated and will be removed.

See Also

  • mysqli_stmt_execute() - Executes a prepared Query

mysqli_escape_string
mysqli_fetch
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_fetch

mysqli_execute
mysqli_get_cache_stats
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_fetch

(PHP 5)

mysqli_fetch — Alias for mysqli_stmt_fetch()

Description

This function is an alias of mysqli_stmt_fetch().

Notes

Note: mysqli_fetch() is deprecated and will be removed.

See Also

  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables

mysqli_execute
mysqli_get_cache_stats
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_result_metadata

mysqli_get_client_stats
mysqli_master_query
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_get_metadata

(PHP 5)

mysqli_get_metadata — Alias for mysqli_stmt_result_metadata()

Description

This function is an alias of mysqli_stmt_result_metadata().

Notes

Note: mysqli_get_metadata() is deprecated and will be removed.

See Also

  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement

mysqli_get_client_stats
mysqli_master_query
Aliases and deprecated Mysqli Functions


Enforce execution of a query on the master in a master/slave setup

mysqli_get_metadata
mysqli_param_count
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_master_query

(PHP 5)

mysqli_master_query — Enforce execution of a query on the master in a master/slave setup

Description

bool mysqli_master_query ( mysqli $link , string $query )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

mysqli_get_metadata
mysqli_param_count
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_param_count

mysqli_master_query
mysqli_report
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_param_count

(PHP 5)

mysqli_param_count — Alias for mysqli_stmt_param_count()

Description

This function is an alias of mysqli_stmt_param_count().

Notes

Note: mysqli_param_count() is deprecated and will be removed.

See Also

  • mysqli_stmt_param_count() - Returns the number of parameter for the given statement

mysqli_master_query
mysqli_report
Aliases and deprecated Mysqli Functions


Enables or disables internal report functions

mysqli_param_count
mysqli_rpl_parse_enabled
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_report

(PHP 5)

mysqli_report — Enables or disables internal report functions

Description

bool mysqli_report ( int $flags )

mysqli_report() is a powerful function to improve your queries and code during development and testing phase. Depending on the flags it reports errors from mysqli function calls or queries which don't use an index (or use a bad index).

Parameters

flags

Supported flags
Name | Description
MYSQLI_REPORT_OFF | Turns reporting off
MYSQLI_REPORT_ERROR | Report errors from mysqli function calls
MYSQLI_REPORT_STRICT | Report warnings from mysqli function calls
MYSQLI_REPORT_INDEX | Report if no index or bad index was used in a query
MYSQLI_REPORT_ALL | Set all options (report all)

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* this query should report an error */
$result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

/* this query should report a warning */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
$result->close();

$mysqli->close();
?>

See Also

  • mysqli_debug() - Performs debugging operations
  • mysqli_dump_debug_info() - Dump debugging information into the log

mysqli_param_count
mysqli_rpl_parse_enabled
Aliases and deprecated Mysqli Functions


Check if RPL parse is enabled

mysqli_report
mysqli_rpl_probe
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_rpl_parse_enabled

(PHP 5)

mysqli_rpl_parse_enabled — Check if RPL parse is enabled

Description

int mysqli_rpl_parse_enabled ( mysqli $link )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

mysqli_report
mysqli_rpl_probe
Aliases and deprecated Mysqli Functions


RPL probe

mysqli_rpl_parse_enabled
mysqli_rpl_query_type
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_rpl_probe

(PHP 5)

mysqli_rpl_probe — RPL probe

Description

bool mysqli_rpl_probe ( mysqli $link )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

mysqli_rpl_parse_enabled
mysqli_rpl_query_type
Aliases and deprecated Mysqli Functions


Returns RPL query type

mysqli_rpl_probe
mysqli_send_long_data
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_rpl_query_type

mysqli->rpl_query_type

(PHP 5)

mysqli_rpl_query_type -- mysqli->rpl_query_type — Returns RPL query type

Description

Procedural style:

int mysqli_rpl_query_type ( mysqli $link , string $query )

Object oriented style (method)

mysqli
int rpl_query_type ( string $query )

Returns MYSQLI_RPL_MASTER, MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending on a query type. INSERT, UPDATE and similar are master queries, SELECT is slave, and FLUSH, REPAIR and similar are admin.

Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

mysqli_rpl_probe
mysqli_send_long_data
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_send_long_data

mysqli_rpl_query_type
mysqli_send_query
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_send_long_data

(PHP 5)

mysqli_send_long_data — Alias for mysqli_stmt_send_long_data()

Description

This function is an alias of mysqli_stmt_send_long_data().

Notes

Note: mysqli_send_long_data() is deprecated and will be removed.

See Also

  • mysqli_stmt_send_long_data() - Send data in blocks

mysqli_rpl_query_type
mysqli_send_query
Aliases and deprecated Mysqli Functions


Send the query and return

mysqli_send_long_data
mysqli_set_opt
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_send_query

mysqli->send_query

(PHP 5)

mysqli_send_query -- mysqli->send_query — Send the query and return

Description

Procedural style:

bool mysqli_send_query ( mysqli $link , string $query )

Object oriented style (method)

mysqli
bool send_query ( string $query )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

mysqli_send_long_data
mysqli_set_opt
Aliases and deprecated Mysqli Functions


Alias of mysqli_options

mysqli_send_query
mysqli_slave_query
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_set_opt

(PHP 5)

mysqli_set_opt — Alias of mysqli_options()

Description

This function is an alias of mysqli_options().

mysqli_send_query
mysqli_slave_query
Aliases and deprecated Mysqli Functions


Force execution of a query on a slave in a master/slave setup

mysqli_set_opt
Mysqlnd
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_slave_query

(PHP 5)

mysqli_slave_query — Force execution of a query on a slave in a master/slave setup

Description

bool mysqli_slave_query ( mysqli $link , string $query )
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.

mysqli_set_opt
Mysqlnd
Aliases and deprecated Mysqli Functions


Add character at current position and advance cursor

Ncurses Functions
ncurses_addchnstr
Ncurses Functions
PHP Manual

ncurses_addch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addch — Add character at current position and advance cursor

Description

int ncurses_addch ( int $ch )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

ch

Ncurses Functions
ncurses_addchnstr
Ncurses Functions


Add attributed string with specified length at current position

ncurses_addch
ncurses_addchstr
Ncurses Functions
PHP Manual

ncurses_addchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchnstr — Add attributed string with specified length at current position

Description

int ncurses_addchnstr ( string $s , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

s

n

ncurses_addch
ncurses_addchstr
Ncurses Functions


Add attributed string at current position

ncurses_addchnstr
ncurses_addnstr
Ncurses Functions
PHP Manual

ncurses_addchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchstr — Add attributed string at current position

Description

int ncurses_addchstr ( string $s )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

s

ncurses_addchnstr
ncurses_addnstr
Ncurses Functions


Add string with specified length at current position

ncurses_addchstr
ncurses_addstr
Ncurses Functions
PHP Manual

ncurses_addnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addnstr — Add string with specified length at current position

Description

int ncurses_addnstr ( string $s , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

s

n

ncurses_addchstr
ncurses_addstr
Ncurses Functions


Output text at current position

ncurses_addnstr
ncurses_assume_default_colors
Ncurses Functions
PHP Manual

ncurses_addstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addstr — Output text at current position

Description

int ncurses_addstr ( string $text )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

text

ncurses_addnstr
ncurses_assume_default_colors
Ncurses Functions


Define default colors for color 0

ncurses_addstr
ncurses_attroff
Ncurses Functions
PHP Manual

ncurses_assume_default_colors

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_assume_default_colors — Define default colors for color 0

Description

int ncurses_assume_default_colors ( int $fg , int $bg )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fg

bg

ncurses_addstr
ncurses_attroff
Ncurses Functions


Turn off the given attributes

ncurses_assume_default_colors
ncurses_attron
Ncurses Functions
PHP Manual

ncurses_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attroff — Turn off the given attributes

Description

int ncurses_attroff ( int $attributes )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attributes

ncurses_assume_default_colors
ncurses_attron
Ncurses Functions


Turn on the given attributes

ncurses_attroff
ncurses_attrset
Ncurses Functions
PHP Manual

ncurses_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attron — Turn on the given attributes

Description

int ncurses_attron ( int $attributes )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attributes

ncurses_attroff
ncurses_attrset
Ncurses Functions


Set given attributes

ncurses_attron
ncurses_baudrate
Ncurses Functions
PHP Manual

ncurses_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attrset — Set given attributes

Description

int ncurses_attrset ( int $attributes )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attributes

ncurses_attron
ncurses_baudrate
Ncurses Functions


Returns baudrate of terminal

ncurses_attrset
ncurses_beep
Ncurses Functions
PHP Manual

ncurses_baudrate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_baudrate — Returns baudrate of terminal

Description

int ncurses_baudrate ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_attrset
ncurses_beep
Ncurses Functions


Let the terminal beep

ncurses_baudrate
ncurses_bkgd
Ncurses Functions
PHP Manual

ncurses_beep

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_beep — Let the terminal beep

Description

int ncurses_beep ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen.

See Also

  • ncurses_flash() - Flash terminal screen (visual bell)

ncurses_baudrate
ncurses_bkgd
Ncurses Functions


Set background property for terminal screen

ncurses_beep
ncurses_bkgdset
Ncurses Functions
PHP Manual

ncurses_bkgd

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgd — Set background property for terminal screen

Description

int ncurses_bkgd ( int $attrchar )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attrchar

ncurses_beep
ncurses_bkgdset
Ncurses Functions


Control screen background

ncurses_bkgd
ncurses_border
Ncurses Functions
PHP Manual

ncurses_bkgdset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgdset — Control screen background

Description

void ncurses_bkgdset ( int $attrchar )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attrchar

ncurses_bkgd
ncurses_border
Ncurses Functions


Draw a border around the screen using attributed characters

ncurses_bkgdset
ncurses_bottom_panel
Ncurses Functions
PHP Manual

ncurses_border

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_border — Draw a border around the screen using attributed characters

Description

int ncurses_border ( int $left , int $right , int $top , int $bottom , int $tl_corner , int $tr_corner , int $bl_corner , int $br_corner )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Draws the specified lines and corners around the main window.

Use ncurses_wborder() for borders around subwindows!

Parameters

Every parameter expects 0 to draw a line or 1 to skip it.

left

right

top

bottom

tl_corner

Top left corner

tr_corner

Top right corner

bl_corner

Bottom left corner

br_corner

Bottom right corner

See Also

  • ncurses_wborder() - Draws a border around the window using attributed characters

ncurses_bkgdset
ncurses_bottom_panel
Ncurses Functions


Moves a visible panel to the bottom of the stack

ncurses_border
ncurses_can_change_color
Ncurses Functions
PHP Manual

ncurses_bottom_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bottom_panel — Moves a visible panel to the bottom of the stack

Description

int ncurses_bottom_panel ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

ncurses_border
ncurses_can_change_color
Ncurses Functions


Checks if terminal color definitions can be changed

ncurses_bottom_panel
ncurses_cbreak
Ncurses Functions
PHP Manual

ncurses_can_change_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_can_change_color — Checks if terminal color definitions can be changed

Description

bool ncurses_can_change_color ( void )

Checks whether the terminal has color capabilities and whether the programmer can change color definitions using ncurses_init_color(). ncurses must be initialized using ncurses_init() before calling this function.

Parameters

This function has no parameters.

Return Values

Return TRUE if the programmer can change color definitions, FALSE otherwise.

See Also

  • ncurses_has_colors() - Checks if terminal has color capabilities
  • ncurses_init_color() - Define a terminal color
  • ncurses_start_color() - Initializes color functionality

ncurses_bottom_panel
ncurses_cbreak
Ncurses Functions


Switch of input buffering

ncurses_can_change_color
ncurses_clear
Ncurses Functions
PHP Manual

ncurses_cbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_cbreak — Switch of input buffering

Description

bool ncurses_cbreak ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.

Return Values

Returns TRUE or NCURSES_ERR if any error occurred.

See Also

  • ncurses_nocbreak() - Switch terminal to cooked mode

ncurses_can_change_color
ncurses_clear
Ncurses Functions


Clear screen

ncurses_cbreak
ncurses_clrtobot
Ncurses Functions
PHP Manual

ncurses_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clear — Clear screen

Description

bool ncurses_clear ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Clears the screen completely without setting blanks.

Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ncurses_erase() - Erase terminal screen

ncurses_cbreak
ncurses_clrtobot
Ncurses Functions


Clear screen from current position to bottom

ncurses_clear
ncurses_clrtoeol
Ncurses Functions
PHP Manual

ncurses_clrtobot

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtobot — Clear screen from current position to bottom

Description

bool ncurses_clrtobot ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ncurses_clear() - Clear screen
  • ncurses_clrtoeol() - Clear screen from current position to end of line

ncurses_clear
ncurses_clrtoeol
Ncurses Functions


Clear screen from current position to end of line

ncurses_clrtobot
ncurses_color_content
Ncurses Functions
PHP Manual

ncurses_clrtoeol

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtoeol — Clear screen from current position to end of line

Description

bool ncurses_clrtoeol ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ncurses_clear() - Clear screen
  • ncurses_clrtobot() - Clear screen from current position to bottom

ncurses_clrtobot
ncurses_color_content
Ncurses Functions


Retrieves RGB components of a color

ncurses_clrtoeol
ncurses_color_set
Ncurses Functions
PHP Manual

ncurses_color_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_content — Retrieves RGB components of a color

Description

int ncurses_color_content ( int $color , int &$r , int &$g , int &$b )

Retrieves the red, green, and blue components for the given color definition. Terminal color capabilities must be initialized with ncurses_start_color() prior to calling this function.

Parameters

color

The number of the color to retrieve information for. May be one of the pre-defined color constants.

r

A reference to which to return the red component of the color. The value returned to the reference will be between 0 and 1000.

g

A reference to which to return the green component of the color. The value returned to the reference will be between 0 and 1000.

b

A reference to which to return the blue component of the color. The value returned to the reference will be between 0 and 1000.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized.

See Also

  • ncurses_init_color() - Define a terminal color
  • ncurses_start_color() - Initializes color functionality

ncurses_clrtoeol
ncurses_color_set
Ncurses Functions


Set active foreground and background colors

ncurses_color_content
ncurses_curs_set
Ncurses Functions
PHP Manual

ncurses_color_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_set — Set active foreground and background colors

Description

int ncurses_color_set ( int $pair )

Sets the active foreground and background colors. Any characters written after this function is invoked will have these colors. This function requires terminal colors to be supported and initialized using ncurses_start_color() beforehand.

ncurses uses color pairs to specify both foreground and background colors. Use ncurses_init_pair() to define a color pair.

Parameters

pair

The color pair from which to get the foreground and background colors to set as the active colors.

Return Values

Returns -1 on success, and 0 on failure.

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_init_pair() - Define a color pair
  • ncurses_start_color() - Initializes color functionality

ncurses_color_content
ncurses_curs_set
Ncurses Functions


Set cursor state

ncurses_color_set
ncurses_def_prog_mode
Ncurses Functions
PHP Manual

ncurses_curs_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_curs_set — Set cursor state

Description

int ncurses_curs_set ( int $visibility )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

visibility

ncurses_color_set
ncurses_def_prog_mode
Ncurses Functions


Saves terminals (program) mode

ncurses_curs_set
ncurses_def_shell_mode
Ncurses Functions
PHP Manual

ncurses_def_prog_mode

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_def_prog_mode — Saves terminals (program) mode

Description

bool ncurses_def_prog_mode ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode().

Return Values

Returns FALSE on success, otherwise TRUE.

See Also

  • ncurses_reset_prog_mode() - Resets the prog mode saved by def_prog_mode

ncurses_curs_set
ncurses_def_shell_mode
Ncurses Functions


Saves terminals (shell) mode

ncurses_def_prog_mode
ncurses_define_key
Ncurses Functions
PHP Manual

ncurses_def_shell_mode

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_def_shell_mode — Saves terminals (shell) mode

Description

bool ncurses_def_shell_mode ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode().

Return Values

Returns FALSE on success, TRUE otherwise.

See Also

  • ncurses_reset_shell_mode() - Resets the shell mode saved by def_shell_mode

ncurses_def_prog_mode
ncurses_define_key
Ncurses Functions


Define a keycode

ncurses_def_shell_mode
ncurses_del_panel
Ncurses Functions
PHP Manual

ncurses_define_key

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_define_key — Define a keycode

Description

int ncurses_define_key ( string $definition , int $keycode )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

definition

keycode

ncurses_def_shell_mode
ncurses_del_panel
Ncurses Functions


Remove panel from the stack and delete it (but not the associated window)

ncurses_define_key
ncurses_delay_output
Ncurses Functions
PHP Manual

ncurses_del_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_del_panel — Remove panel from the stack and delete it (but not the associated window)

Description

bool ncurses_del_panel ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

ncurses_define_key
ncurses_delay_output
Ncurses Functions


Delay output on terminal using padding characters

ncurses_del_panel
ncurses_delch
Ncurses Functions
PHP Manual

ncurses_delay_output

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delay_output — Delay output on terminal using padding characters

Description

int ncurses_delay_output ( int $milliseconds )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

milliseconds

ncurses_del_panel
ncurses_delch
Ncurses Functions


Delete character at current position, move rest of line left

ncurses_delay_output
ncurses_deleteln
Ncurses Functions
PHP Manual

ncurses_delch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delch — Delete character at current position, move rest of line left

Description

bool ncurses_delch ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change.

Return Values

Returns FALSE on success, TRUE otherwise.

See Also

  • ncurses_deleteln() - Delete line at current position, move rest of screen up

ncurses_delay_output
ncurses_deleteln
Ncurses Functions


Delete line at current position, move rest of screen up

ncurses_delch
ncurses_delwin
Ncurses Functions
PHP Manual

ncurses_deleteln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_deleteln — Delete line at current position, move rest of screen up

Description

bool ncurses_deleteln ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Deletes the current line under cursorposition. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change.

Return Values

Returns FALSE on success, otherwise TRUE.

See Also

  • ncurses_delch() - Delete character at current position, move rest of line left

ncurses_delch
ncurses_delwin
Ncurses Functions


Delete a ncurses window

ncurses_deleteln
ncurses_doupdate
Ncurses Functions
PHP Manual

ncurses_delwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delwin — Delete a ncurses window

Description

bool ncurses_delwin ( resource $window )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ncurses_deleteln
ncurses_doupdate
Ncurses Functions


Write all prepared refreshes to terminal

ncurses_delwin
ncurses_echo
Ncurses Functions
PHP Manual

ncurses_doupdate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_doupdate — Write all prepared refreshes to terminal

Description

bool ncurses_doupdate ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls.

Return Values

Returns TRUE on success or FALSE on failure.

ncurses_delwin
ncurses_echo
Ncurses Functions


Activate keyboard input echo

ncurses_doupdate
ncurses_echochar
Ncurses Functions
PHP Manual

ncurses_echo

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echo — Activate keyboard input echo

Description

bool ncurses_echo ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Enables echo mode. All characters typed by user are echoed by ncurses_getch().

Return Values

Returns FALSE on success, TRUE if any error occurred.

See Also

  • ncurses_noecho() - Switch off keyboard input echo to disable echo mode

ncurses_doupdate
ncurses_echochar
Ncurses Functions


Single character output including refresh

ncurses_echo
ncurses_end
Ncurses Functions
PHP Manual

ncurses_echochar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echochar — Single character output including refresh

Description

int ncurses_echochar ( int $character )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

character

ncurses_echo
ncurses_end
Ncurses Functions


Stop using ncurses, clean up the screen

ncurses_echochar
ncurses_erase
Ncurses Functions
PHP Manual

ncurses_end

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_end — Stop using ncurses, clean up the screen

Description

int ncurses_end ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_echochar
ncurses_erase
Ncurses Functions


Erase terminal screen

ncurses_end
ncurses_erasechar
Ncurses Functions
PHP Manual

ncurses_erase

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erase — Erase terminal screen

Description

bool ncurses_erase ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Fills the terminal screen with blanks.

Created blanks have the current background rendition, set by ncurses_bkgd().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ncurses_bkgd() - Set background property for terminal screen
  • ncurses_clear() - Clear screen

ncurses_end
ncurses_erasechar
Ncurses Functions


Returns current erase character

ncurses_erase
ncurses_filter
Ncurses Functions
PHP Manual

ncurses_erasechar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erasechar — Returns current erase character

Description

string ncurses_erasechar ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the current erase character.

Return Values

The current erase char, as a string.

See Also

  • ncurses_killchar() - Returns current line kill character

ncurses_erase
ncurses_filter
Ncurses Functions


Set LINES for iniscr() and newterm() to 1

ncurses_erasechar
ncurses_flash
Ncurses Functions
PHP Manual

ncurses_filter

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_filter — Set LINES for iniscr() and newterm() to 1

Description

void ncurses_filter ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_erasechar
ncurses_flash
Ncurses Functions


Flash terminal screen (visual bell)

ncurses_filter
ncurses_flushinp
Ncurses Functions
PHP Manual

ncurses_flash

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flash — Flash terminal screen (visual bell)

Description

bool ncurses_flash ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Flashes the screen, and if its not possible, sends an audible alert (bell).

Return Values

Returns FALSE on success, otherwise TRUE.

See Also

  • ncurses_beep() - Let the terminal beep

ncurses_filter
ncurses_flushinp
Ncurses Functions


Flush keyboard input buffer

ncurses_flash
ncurses_getch
Ncurses Functions
PHP Manual

ncurses_flushinp

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flushinp — Flush keyboard input buffer

Description

bool ncurses_flushinp ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Throws away any typeahead that has been typed and has not yet been read by your program.

Return Values

Returns FALSE on success, otherwise TRUE.

ncurses_flash
ncurses_getch
Ncurses Functions


Read a character from keyboard

ncurses_flushinp
ncurses_getmaxyx
Ncurses Functions
PHP Manual

ncurses_getch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getch — Read a character from keyboard

Description

int ncurses_getch ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_flushinp
ncurses_getmaxyx
Ncurses Functions


Returns the size of a window

ncurses_getch
ncurses_getmouse
Ncurses Functions
PHP Manual

ncurses_getmaxyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmaxyx — Returns the size of a window

Description

void ncurses_getmaxyx ( resource $window , int &$y , int &$x )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Gets the horizontal and vertical size of the given window into the given variables.

Variables must be passed as reference, so they are updated when the user changes the terminal size.

Parameters

window

The measured window

x

This will be set to the window width

y

This will be set to the window height

Return Values

No value is returned.

ncurses_getch
ncurses_getmouse
Ncurses Functions


Reads mouse event

ncurses_getmaxyx
ncurses_getyx
Ncurses Functions
PHP Manual

ncurses_getmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmouse — Reads mouse event

Description

bool ncurses_getmouse ( array &$mevent )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

ncurses_getmouse() reads mouse event out of queue.

Parameters

mevent

Event options will be delivered in this parameter which has to be an array, passed by reference (see example below).

On success an associative array with following keys will be delivered:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

Return Values

Returns FALSE if a mouse event is actually visible in the given window, otherwise returns TRUE.

Examples

Example #1 ncurses_getmouse() example

<?php
switch (ncurses_getch()){
  case NCURSES_KEY_MOUSE:
    if (!ncurses_getmouse($mevent)){
      if ($mevent["mmask"] & NCURSES_MOUSE_BUTTON1_PRESSED){
        $mouse_x = $mevent["x"]; // Save mouse position
        $mouse_y = $mevent["y"];
      }
    }
  break;

  default:
    /* .... */
}
?>

See Also

  • ncurses_ungetmouse() - Pushes mouse event to queue

ncurses_getmaxyx
ncurses_getyx
Ncurses Functions


Returns the current cursor position for a window

ncurses_getmouse
ncurses_halfdelay
Ncurses Functions
PHP Manual

ncurses_getyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getyx — Returns the current cursor position for a window

Description

void ncurses_getyx ( resource $window , int &$y , int &$x )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

y

x

ncurses_getmouse
ncurses_halfdelay
Ncurses Functions


Put terminal into halfdelay mode

ncurses_getyx
ncurses_has_colors
Ncurses Functions
PHP Manual

ncurses_halfdelay

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_halfdelay — Put terminal into halfdelay mode

Description

int ncurses_halfdelay ( int $tenth )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

tenth

ncurses_getyx
ncurses_has_colors
Ncurses Functions


Checks if terminal has color capabilities

ncurses_halfdelay
ncurses_has_ic
Ncurses Functions
PHP Manual

ncurses_has_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_colors — Checks if terminal has color capabilities

Description

bool ncurses_has_colors ( void )

Checks whether the terminal has color capabilities. This function can be used to write terminal-independent programs. ncurses must be initialized using ncurses_init() before calling this function.

Parameters

This function has no parameters.

Return Values

Return TRUE if the terminal has color capabilities, FALSE otherwise.

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_can_change_color() - Checks if terminal color definitions can be changed
  • ncurses_start_color() - Initializes color functionality

ncurses_halfdelay
ncurses_has_ic
Ncurses Functions


Check for insert- and delete-capabilities

ncurses_has_colors
ncurses_has_il
Ncurses Functions
PHP Manual

ncurses_has_ic

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_ic — Check for insert- and delete-capabilities

Description

bool ncurses_has_ic ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Checks whether the terminal has insert and delete capabilities.

Return Values

Returns TRUE if the terminal has insert/delete-capabilities, FALSE otherwise.

See Also

  • ncurses_has_il() - Check for line insert- and delete-capabilities

ncurses_has_colors
ncurses_has_il
Ncurses Functions


Check for line insert- and delete-capabilities

ncurses_has_ic
ncurses_has_key
Ncurses Functions
PHP Manual

ncurses_has_il

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_il — Check for line insert- and delete-capabilities

Description

bool ncurses_has_il ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Checks whether the terminal has insert- and delete-line-capabilities.

Return Values

Returns TRUE if the terminal has insert/delete-line capabilities, FALSE otherwise.

See Also

  • ncurses_has_ic() - Check for insert- and delete-capabilities

ncurses_has_ic
ncurses_has_key
Ncurses Functions


Check for presence of a function key on terminal keyboard

ncurses_has_il
ncurses_hide_panel
Ncurses Functions
PHP Manual

ncurses_has_key

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_key — Check for presence of a function key on terminal keyboard

Description

int ncurses_has_key ( int $keycode )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

keycode

ncurses_has_il
ncurses_hide_panel
Ncurses Functions


Remove panel from the stack, making it invisible

ncurses_has_key
ncurses_hline
Ncurses Functions
PHP Manual

ncurses_hide_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hide_panel — Remove panel from the stack, making it invisible

Description

int ncurses_hide_panel ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

ncurses_has_key
ncurses_hline
Ncurses Functions


Draw a horizontal line at current position using an attributed character and max. n characters long

ncurses_hide_panel
ncurses_inch
Ncurses Functions
PHP Manual

ncurses_hline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long

Description

int ncurses_hline ( int $charattr , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

charattr

n

ncurses_hide_panel
ncurses_inch
Ncurses Functions


Get character and attribute at current position

ncurses_hline
ncurses_init_color
Ncurses Functions
PHP Manual

ncurses_inch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_inch — Get character and attribute at current position

Description

string ncurses_inch ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the character from the current position.

Return Values

Returns the character, as a string.

ncurses_hline
ncurses_init_color
Ncurses Functions


Initialize ncurses

ncurses_init_pair
ncurses_insch
Ncurses Functions
PHP Manual

ncurses_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init — Initialize ncurses

Description

void ncurses_init ( void )

Initializes the ncurses interface. This function must be used before any other ncurses function call.

Note that ncurses_end() must be called before exiting from the program, or the terminal will not be restored to its proper non-visual mode.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • ncurses_end() - Stop using ncurses, clean up the screen

ncurses_init_pair
ncurses_insch
Ncurses Functions


Define a terminal color

ncurses_inch
ncurses_init_pair
Ncurses Functions
PHP Manual

ncurses_init_color

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_color — Define a terminal color

Description

int ncurses_init_color ( int $color , int $r , int $g , int $b )

Defines or redefines the given color. When this function is called, all occurrences of the given color on the screen, if any, immediately change to the new definition.

Color capabilities must be supported by the terminal and initialized using ncurses_start_color() prior to calling this function. In addition, the terminal must have color changing capabilities; use ncurses_can_change_color() to check for this.

Parameters

color

The identification number of the color to redefine. It may be one of the default color constants.

r

A color value, between 0 and 1000, for the red component.

g

A color value, between 0 and 1000, for the green component.

b

A color value, between 0 and 1000, for the blue component.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized or the terminal does not have color changing capabilities.

See Also

  • ncurses_color_content() - Retrieves RGB components of a color
  • ncurses_start_color() - Initializes color functionality

ncurses_inch
ncurses_init_pair
Ncurses Functions


Define a color pair

ncurses_init_color
ncurses_init
Ncurses Functions
PHP Manual

ncurses_init_pair

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_pair — Define a color pair

Description

int ncurses_init_pair ( int $pair , int $fg , int $bg )

Defines or redefines the given color pair to have the given foreground and background colors. If the color pair was previously initialized, the screen is refreshed and all occurrences of it are changed to reflect the new definition.

Color capabilities must be initialized using ncurses_start_color() before calling this function. The first color pair (color pair 0) is assumed to be white on black by default, but can be changed using ncurses_assume_default_colors().

Parameters

pair

The number of the color pair to define.

fg

The foreground color for the color pair. May be one of the pre-defined colors or one defined by ncurses_init_color() if the terminal has color changing capabilities.

bg

The background color for the color pair. May be one of the pre-defined colors or one defined by ncurses_init_color() if the terminal has color changing capabilities.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or color support were not initialized.

Notes

Note that color changing capabilities are not required for defining color pairs of pre-existing colors, but only for changing definitions (red, green, and blue components) of colors themselves per ncurses_init_color().

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_pair_content() - Retrieves foreground and background colors of a color pair
  • ncurses_start_color() - Initializes color functionality

ncurses_init_color
ncurses_init
Ncurses Functions


Insert character moving rest of line including character at current position

ncurses_init
ncurses_insdelln
Ncurses Functions
PHP Manual

ncurses_insch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insch — Insert character moving rest of line including character at current position

Description

int ncurses_insch ( int $character )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

character

ncurses_init
ncurses_insdelln
Ncurses Functions


Insert lines before current line scrolling down (negative numbers delete and scroll up)

ncurses_insch
ncurses_insertln
Ncurses Functions
PHP Manual

ncurses_insdelln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insdelln — Insert lines before current line scrolling down (negative numbers delete and scroll up)

Description

int ncurses_insdelln ( int $count )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

count

ncurses_insch
ncurses_insertln
Ncurses Functions


Insert a line, move rest of screen down

ncurses_insdelln
ncurses_insstr
Ncurses Functions
PHP Manual

ncurses_insertln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insertln — Insert a line, move rest of screen down

Description

int ncurses_insertln ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Inserts a new line above the current line. The bottom line will be lost.

ncurses_insdelln
ncurses_insstr
Ncurses Functions


Insert string at current position, moving rest of line right

ncurses_insertln
ncurses_instr
Ncurses Functions
PHP Manual

ncurses_insstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insstr — Insert string at current position, moving rest of line right

Description

int ncurses_insstr ( string $text )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

text

ncurses_insertln
ncurses_instr
Ncurses Functions


Reads string from terminal screen

ncurses_insstr
ncurses_isendwin
Ncurses Functions
PHP Manual

ncurses_instr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_instr — Reads string from terminal screen

Description

int ncurses_instr ( string &$buffer )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Reads a string from the terminal screen and returns the number of characters read from the current character position until end of line.

Parameters

buffer

The characters. Attributes will be stripped.

Return Values

Returns the number of characters.

ncurses_insstr
ncurses_isendwin
Ncurses Functions


Ncurses is in endwin mode, normal screen output may be performed

ncurses_instr
ncurses_keyok
Ncurses Functions
PHP Manual

ncurses_isendwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_isendwin — Ncurses is in endwin mode, normal screen output may be performed

Description

bool ncurses_isendwin ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Checks if ncurses is in endwin mode.

Return Values

Returns TRUE, if ncurses_end() has been called without any subsequent calls to ncurses_wrefresh(), FALSE otherwise.

See Also

  • ncurses_end() - Stop using ncurses, clean up the screen
  • ncurses_wrefresh() - Refresh window on terminal screen

ncurses_instr
ncurses_keyok
Ncurses Functions


Enable or disable a keycode

ncurses_isendwin
ncurses_keypad
Ncurses Functions
PHP Manual

ncurses_keyok

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keyok — Enable or disable a keycode

Description

int ncurses_keyok ( int $keycode , bool $enable )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

keycode

enable

ncurses_isendwin
ncurses_keypad
Ncurses Functions


Turns keypad on or off

ncurses_keyok
ncurses_killchar
Ncurses Functions
PHP Manual

ncurses_keypad

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keypad — Turns keypad on or off

Description

int ncurses_keypad ( resource $window , bool $bf )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

bf

ncurses_keyok
ncurses_killchar
Ncurses Functions


Returns current line kill character

ncurses_keypad
ncurses_longname
Ncurses Functions
PHP Manual

ncurses_killchar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_killchar — Returns current line kill character

Description

string ncurses_killchar ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the current line kill character.

Return Values

Returns the kill character, as a string.

See Also

  • ncurses_erasechar() - Returns current erase character

ncurses_keypad
ncurses_longname
Ncurses Functions


Returns terminals description

ncurses_killchar
ncurses_meta
Ncurses Functions
PHP Manual

ncurses_longname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_longname — Returns terminals description

Description

string ncurses_longname ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns a verbose description of the terminal.

Return Values

Returns the description, as a string truncated to 128 characters. On errors, returns NULL.

See Also

  • ncurses_termname() - Returns terminals (short)-name

ncurses_killchar
ncurses_meta
Ncurses Functions


Enables/Disable 8-bit meta key information

ncurses_longname
ncurses_mouse_trafo
Ncurses Functions
PHP Manual

ncurses_meta

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_meta — Enables/Disable 8-bit meta key information

Description

int ncurses_meta ( resource $window , bool $8bit )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

8bit

ncurses_longname
ncurses_mouse_trafo
Ncurses Functions


Transforms coordinates

ncurses_meta
ncurses_mouseinterval
Ncurses Functions
PHP Manual

ncurses_mouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouse_trafo — Transforms coordinates

Description

bool ncurses_mouse_trafo ( int &$y , int &$x , bool $toscreen )
Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

toscreen

ncurses_meta
ncurses_mouseinterval
Ncurses Functions


Set timeout for mouse button clicks

ncurses_mouse_trafo
ncurses_mousemask
Ncurses Functions
PHP Manual

ncurses_mouseinterval

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouseinterval — Set timeout for mouse button clicks

Description

int ncurses_mouseinterval ( int $milliseconds )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

milliseconds

ncurses_mouse_trafo
ncurses_mousemask
Ncurses Functions


Sets mouse options

ncurses_mouseinterval
ncurses_move_panel
Ncurses Functions
PHP Manual

ncurses_mousemask

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mousemask — Sets mouse options

Description

int ncurses_mousemask ( int $newmask , int &$oldmask )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets mouse events to be reported. By default no mouse events will be reported.

Mouse events are represented by NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event of queue, call ncurses_getmouse().

Parameters

newmask

Mouse mask options can be set with the following predefined constants:

  • NCURSES_BUTTON1_PRESSED

  • NCURSES_BUTTON1_RELEASED

  • NCURSES_BUTTON1_CLICKED

  • NCURSES_BUTTON1_DOUBLE_CLICKED

  • NCURSES_BUTTON1_TRIPLE_CLICKED

  • NCURSES_BUTTON2_PRESSED

  • NCURSES_BUTTON2_RELEASED

  • NCURSES_BUTTON2_CLICKED

  • NCURSES_BUTTON2_DOUBLE_CLICKED

  • NCURSES_BUTTON2_TRIPLE_CLICKED

  • NCURSES_BUTTON3_PRESSED

  • NCURSES_BUTTON3_RELEASED

  • NCURSES_BUTTON3_CLICKED

  • NCURSES_BUTTON3_DOUBLE_CLICKED

  • NCURSES_BUTTON3_TRIPLE_CLICKED

  • NCURSES_BUTTON4_PRESSED

  • NCURSES_BUTTON4_RELEASED

  • NCURSES_BUTTON4_CLICKED

  • NCURSES_BUTTON4_DOUBLE_CLICKED

  • NCURSES_BUTTON4_TRIPLE_CLICKED

  • NCURSES_BUTTON_SHIFT>

  • NCURSES_BUTTON_CTRL

  • NCURSES_BUTTON_ALT

  • NCURSES_ALL_MOUSE_EVENTS

  • NCURSES_REPORT_MOUSE_POSITION

As a side effect, setting a zero mousemask in newmask turns off the mouse pointer. Setting a non zero value turns mouse pointer on.

oldmask

This will be set to the previous value of the mouse event mask.

Return Values

Returns a mask to indicated which of the in parameter newmask specified mouse events can be reported. On complete failure, it returns 0.

Examples

Example #1 ncurses_mousemask() example

<?php
$newmask = NCURSES_BUTTON1_CLICKED + NCURSES_BUTTON1_RELEASED;
$mask = ncurses_mousemask($newmask, $oldmask);
if ($mask & $newmask){
    printf("All specified mouse options will be supported\n");
}
?>

See Also

  • ncurses_getch() - Read a character from keyboard
  • ncurses_getmouse() - Reads mouse event
  • ncurses_ungetmouse() - Pushes mouse event to queue

ncurses_mouseinterval
ncurses_move_panel
Ncurses Functions


Move output position

ncurses_move_panel
ncurses_mvaddch
Ncurses Functions
PHP Manual

ncurses_move

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_move — Move output position

Description

int ncurses_move ( int $y , int $x )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

ncurses_move_panel
ncurses_mvaddch
Ncurses Functions


Moves a panel so that its upper-left corner is at [startx, starty]

ncurses_mousemask
ncurses_move
Ncurses Functions
PHP Manual

ncurses_move_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_move_panel — Moves a panel so that its upper-left corner is at [startx, starty]

Description

int ncurses_move_panel ( resource $panel , int $startx , int $starty )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

startx

starty

ncurses_mousemask
ncurses_move
Ncurses Functions


Move current position and add character

ncurses_move
ncurses_mvaddchnstr
Ncurses Functions
PHP Manual

ncurses_mvaddch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddch — Move current position and add character

Description

int ncurses_mvaddch ( int $y , int $x , int $c )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

c

ncurses_move
ncurses_mvaddchnstr
Ncurses Functions


Move position and add attributed string with specified length

ncurses_mvaddch
ncurses_mvaddchstr
Ncurses Functions
PHP Manual

ncurses_mvaddchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchnstr — Move position and add attributed string with specified length

Description

int ncurses_mvaddchnstr ( int $y , int $x , string $s , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s

n

ncurses_mvaddch
ncurses_mvaddchstr
Ncurses Functions


Move position and add attributed string

ncurses_mvaddchnstr
ncurses_mvaddnstr
Ncurses Functions
PHP Manual

ncurses_mvaddchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchstr — Move position and add attributed string

Description

int ncurses_mvaddchstr ( int $y , int $x , string $s )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s

ncurses_mvaddchnstr
ncurses_mvaddnstr
Ncurses Functions


Move position and add string with specified length

ncurses_mvaddchstr
ncurses_mvaddstr
Ncurses Functions
PHP Manual

ncurses_mvaddnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddnstr — Move position and add string with specified length

Description

int ncurses_mvaddnstr ( int $y , int $x , string $s , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s

n

ncurses_mvaddchstr
ncurses_mvaddstr
Ncurses Functions


Move position and add string

ncurses_mvaddnstr
ncurses_mvcur
Ncurses Functions
PHP Manual

ncurses_mvaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddstr — Move position and add string

Description

int ncurses_mvaddstr ( int $y , int $x , string $s )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s

ncurses_mvaddnstr
ncurses_mvcur
Ncurses Functions


Move cursor immediately

ncurses_mvaddstr
ncurses_mvdelch
Ncurses Functions
PHP Manual

ncurses_mvcur

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvcur — Move cursor immediately

Description

int ncurses_mvcur ( int $old_y , int $old_x , int $new_y , int $new_x )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

old_y

old_x

new_y

new_x

ncurses_mvaddstr
ncurses_mvdelch
Ncurses Functions


Move position and delete character, shift rest of line left

ncurses_mvcur
ncurses_mvgetch
Ncurses Functions
PHP Manual

ncurses_mvdelch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvdelch — Move position and delete character, shift rest of line left

Description

int ncurses_mvdelch ( int $y , int $x )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

ncurses_mvcur
ncurses_mvgetch
Ncurses Functions


Move position and get character at new position

ncurses_mvdelch
ncurses_mvhline
Ncurses Functions
PHP Manual

ncurses_mvgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvgetch — Move position and get character at new position

Description

int ncurses_mvgetch ( int $y , int $x )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

ncurses_mvdelch
ncurses_mvhline
Ncurses Functions


Set new position and draw a horizontal line using an attributed character and max. n characters long

ncurses_mvgetch
ncurses_mvinch
Ncurses Functions
PHP Manual

ncurses_mvhline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long

Description

int ncurses_mvhline ( int $y , int $x , int $attrchar , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

attrchar

n

ncurses_mvgetch
ncurses_mvinch
Ncurses Functions


Move position and get attributed character at new position

ncurses_mvhline
ncurses_mvvline
Ncurses Functions
PHP Manual

ncurses_mvinch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvinch — Move position and get attributed character at new position

Description

int ncurses_mvinch ( int $y , int $x )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

ncurses_mvhline
ncurses_mvvline
Ncurses Functions


Set new position and draw a vertical line using an attributed character and max. n characters long

ncurses_mvinch
ncurses_mvwaddstr
Ncurses Functions
PHP Manual

ncurses_mvvline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvvline — Set new position and draw a vertical line using an attributed character and max. n characters long

Description

int ncurses_mvvline ( int $y , int $x , int $attrchar , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

attrchar

n

ncurses_mvinch
ncurses_mvwaddstr
Ncurses Functions


Add string at new position in window

ncurses_mvvline
ncurses_napms
Ncurses Functions
PHP Manual

ncurses_mvwaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvwaddstr — Add string at new position in window

Description

int ncurses_mvwaddstr ( resource $window , int $y , int $x , string $text )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

window

y

x

text

ncurses_mvvline
ncurses_napms
Ncurses Functions


Sleep

ncurses_mvwaddstr
ncurses_new_panel
Ncurses Functions
PHP Manual

ncurses_napms

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_napms — Sleep

Description

int ncurses_napms ( int $milliseconds )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

milliseconds

ncurses_mvwaddstr
ncurses_new_panel
Ncurses Functions


Create a new panel and associate it with window

ncurses_napms
ncurses_newpad
Ncurses Functions
PHP Manual

ncurses_new_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_new_panel — Create a new panel and associate it with window

Description

resource ncurses_new_panel ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ncurses_napms
ncurses_newpad
Ncurses Functions


Creates a new pad (window)

ncurses_new_panel
ncurses_newwin
Ncurses Functions
PHP Manual

ncurses_newpad

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newpad — Creates a new pad (window)

Description

resource ncurses_newpad ( int $rows , int $cols )
Warning

This function is currently not documented; only its argument list is available.

Parameters

rows

cols

ncurses_new_panel
ncurses_newwin
Ncurses Functions


Create a new window

ncurses_newpad
ncurses_nl
Ncurses Functions
PHP Manual

ncurses_newwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newwin — Create a new window

Description

resource ncurses_newwin ( int $rows , int $cols , int $y , int $x )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Creates a new window to draw elements in.

When creating additional windows, remember to use ncurses_getmaxyx() to check for available space, as terminal size is individual and may vary.

Parameters

rows

Number of rows

cols

Number of columns

y

y-coordinate of the origin

x

x-coordinate of the origin

Return Values

Returns a resource ID for the new window.

ncurses_newpad
ncurses_nl
Ncurses Functions


Translate newline and carriage return / line feed

ncurses_newwin
ncurses_nocbreak
Ncurses Functions
PHP Manual

ncurses_nl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nl — Translate newline and carriage return / line feed

Description

bool ncurses_nl ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_newwin
ncurses_nocbreak
Ncurses Functions


Switch terminal to cooked mode

ncurses_nl
ncurses_noecho
Ncurses Functions
PHP Manual

ncurses_nocbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nocbreak — Switch terminal to cooked mode

Description

bool ncurses_nocbreak ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns terminal to normal (cooked) mode. Initially the terminal may or may not in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly.

Return Values

Returns TRUE if any error occurred, otherwise FALSE.

See Also

  • ncurses_cbreak() - Switch of input buffering

ncurses_nl
ncurses_noecho
Ncurses Functions


Switch off keyboard input echo

ncurses_nocbreak
ncurses_nonl
Ncurses Functions
PHP Manual

ncurses_noecho

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noecho — Switch off keyboard input echo

Description

bool ncurses_noecho ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Prevents echoing of user typed characters.

Return Values

Returns TRUE if any error occurred, FALSE otherwise.

See Also

  • ncurses_echo() - Activate keyboard input echo
  • ncurses_getch() - Read a character from keyboard

ncurses_nocbreak
ncurses_nonl
Ncurses Functions


Do not translate newline and carriage return / line feed

ncurses_noecho
ncurses_noqiflush
Ncurses Functions
PHP Manual

ncurses_nonl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nonl — Do not translate newline and carriage return / line feed

Description

bool ncurses_nonl ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_noecho
ncurses_noqiflush
Ncurses Functions


Do not flush on signal characters

ncurses_nonl
ncurses_noraw
Ncurses Functions
PHP Manual

ncurses_noqiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noqiflush — Do not flush on signal characters

Description

void ncurses_noqiflush ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_nonl
ncurses_noraw
Ncurses Functions


Switch terminal out of raw mode

ncurses_noqiflush
ncurses_pair_content
Ncurses Functions
PHP Manual

ncurses_noraw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noraw — Switch terminal out of raw mode

Description

bool ncurses_noraw ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal.

Return Values

Returns TRUE if any error occurred, otherwise FALSE.

See Also

  • ncurses_raw() - Switch terminal into raw mode
  • ncurses_cbreak() - Switch of input buffering
  • ncurses_nocbreak() - Switch terminal to cooked mode

ncurses_noqiflush
ncurses_pair_content
Ncurses Functions


Retrieves foreground and background colors of a color pair

ncurses_noraw
ncurses_panel_above
Ncurses Functions
PHP Manual

ncurses_pair_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pair_content — Retrieves foreground and background colors of a color pair

Description

int ncurses_pair_content ( int $pair , int &$f , int &$b )

Retrieves the foreground and background colors that constitute the given color pair. Terminal color capabilities must be initialized with ncurses_start_color() prior to calling this function.

Parameters

pair

The number of the color pair to retrieve information for.

f

A reference to which to return the foreground color of the color pair. The information returned will be a color number referring to one of the pre-defined colors or a color defined previously by ncurses_init_color() if the terminal supports color changing.

b

A reference to which to return the background color of the color pair. The information returned will be a color number referring to one of the pre-defined colors or a color defined previously by ncurses_init_color() if the terminal supports color changing.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized.

See Also

  • ncurses_init_pair() - Define a color pair
  • ncurses_start_color() - Initializes color functionality

ncurses_noraw
ncurses_panel_above
Ncurses Functions


Returns the panel above panel

ncurses_pair_content
ncurses_panel_below
Ncurses Functions
PHP Manual

ncurses_panel_above

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_above — Returns the panel above panel

Description

resource ncurses_panel_above ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

Return Values

If panel is null, returns the bottom panel in the stack.

ncurses_pair_content
ncurses_panel_below
Ncurses Functions


Returns the panel below panel

ncurses_panel_above
ncurses_panel_window
Ncurses Functions
PHP Manual

ncurses_panel_below

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_below — Returns the panel below panel

Description

resource ncurses_panel_below ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

Parameters

If panel is null, returns the top panel in the stack.

ncurses_panel_above
ncurses_panel_window
Ncurses Functions


Returns the window associated with panel

ncurses_panel_below
ncurses_pnoutrefresh
Ncurses Functions
PHP Manual

ncurses_panel_window

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_window — Returns the window associated with panel

Description

resource ncurses_panel_window ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

ncurses_panel_below
ncurses_pnoutrefresh
Ncurses Functions


Copies a region from a pad into the virtual screen

ncurses_panel_window
ncurses_prefresh
Ncurses Functions
PHP Manual

ncurses_pnoutrefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pnoutrefresh — Copies a region from a pad into the virtual screen

Description

int ncurses_pnoutrefresh ( resource $pad , int $pminrow , int $pmincol , int $sminrow , int $smincol , int $smaxrow , int $smaxcol )
Warning

This function is currently not documented; only its argument list is available.

Parameters

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol

ncurses_panel_window
ncurses_prefresh
Ncurses Functions


Copies a region from a pad into the virtual screen

ncurses_pnoutrefresh
ncurses_putp
Ncurses Functions
PHP Manual

ncurses_prefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_prefresh — Copies a region from a pad into the virtual screen

Description

int ncurses_prefresh ( resource $pad , int $pminrow , int $pmincol , int $sminrow , int $smincol , int $smaxrow , int $smaxcol )
Warning

This function is currently not documented; only its argument list is available.

Parameters

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol

ncurses_pnoutrefresh
ncurses_putp
Ncurses Functions


Apply padding information to the string and output it

ncurses_prefresh
ncurses_qiflush
Ncurses Functions
PHP Manual

ncurses_putp

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_putp — Apply padding information to the string and output it

Description

int ncurses_putp ( string $text )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

text

ncurses_prefresh
ncurses_qiflush
Ncurses Functions


Flush on signal characters

ncurses_putp
ncurses_raw
Ncurses Functions
PHP Manual

ncurses_qiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_qiflush — Flush on signal characters

Description

void ncurses_qiflush ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_putp
ncurses_raw
Ncurses Functions


Switch terminal into raw mode

ncurses_qiflush
ncurses_refresh
Ncurses Functions
PHP Manual

ncurses_raw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_raw — Switch terminal into raw mode

Description

bool ncurses_raw ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal.

Return Values

Returns TRUE if any error occurred, otherwise FALSE.

See Also

  • ncurses_noraw() - Switch terminal out of raw mode
  • ncurses_cbreak() - Switch of input buffering
  • ncurses_nocbreak() - Switch terminal to cooked mode

ncurses_qiflush
ncurses_refresh
Ncurses Functions


Refresh screen

ncurses_raw
ncurses_replace_panel
Ncurses Functions
PHP Manual

ncurses_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_refresh — Refresh screen

Description

int ncurses_refresh ( int $ch )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

ch

ncurses_raw
ncurses_replace_panel
Ncurses Functions


Replaces the window associated with panel

ncurses_refresh
ncurses_reset_prog_mode
Ncurses Functions
PHP Manual

ncurses_replace_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_replace_panel — Replaces the window associated with panel

Description

int ncurses_replace_panel ( resource $panel , resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

window

ncurses_refresh
ncurses_reset_prog_mode
Ncurses Functions


Resets the prog mode saved by def_prog_mode

ncurses_replace_panel
ncurses_reset_shell_mode
Ncurses Functions
PHP Manual

ncurses_reset_prog_mode

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_reset_prog_mode — Resets the prog mode saved by def_prog_mode

Description

int ncurses_reset_prog_mode ( void )
Warning

This function is currently not documented; only its argument list is available.

ncurses_replace_panel
ncurses_reset_shell_mode
Ncurses Functions


Resets the shell mode saved by def_shell_mode

ncurses_reset_prog_mode
ncurses_resetty
Ncurses Functions
PHP Manual

ncurses_reset_shell_mode

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_reset_shell_mode — Resets the shell mode saved by def_shell_mode

Description

int ncurses_reset_shell_mode ( void )
Warning

This function is currently not documented; only its argument list is available.

ncurses_reset_prog_mode
ncurses_resetty
Ncurses Functions


Restores saved terminal state

ncurses_reset_shell_mode
ncurses_savetty
Ncurses Functions
PHP Manual

ncurses_resetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_resetty — Restores saved terminal state

Description

bool ncurses_resetty ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Restores the terminal state, which was previously saved by calling ncurses_savetty().

Return Values

Always returns FALSE.

See Also

  • ncurses_savetty() - Saves terminal state

ncurses_reset_shell_mode
ncurses_savetty
Ncurses Functions


Saves terminal state

ncurses_resetty
ncurses_scr_dump
Ncurses Functions
PHP Manual

ncurses_savetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_savetty — Saves terminal state

Description

bool ncurses_savetty ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Saves the current terminal state. The saved terminal state can be restored with ncurses_resetty().

Return Values

Always returns FALSE.

See Also

  • ncurses_resetty() - Restores saved terminal state

ncurses_resetty
ncurses_scr_dump
Ncurses Functions


Dump screen content to file

ncurses_savetty
ncurses_scr_init
Ncurses Functions
PHP Manual

ncurses_scr_dump

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_dump — Dump screen content to file

Description

int ncurses_scr_dump ( string $filename )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

ncurses_savetty
ncurses_scr_init
Ncurses Functions


Initialize screen from file dump

ncurses_scr_dump
ncurses_scr_restore
Ncurses Functions
PHP Manual

ncurses_scr_init

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_init — Initialize screen from file dump

Description

int ncurses_scr_init ( string $filename )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

ncurses_scr_dump
ncurses_scr_restore
Ncurses Functions


Restore screen from file dump

ncurses_scr_init
ncurses_scr_set
Ncurses Functions
PHP Manual

ncurses_scr_restore

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_restore — Restore screen from file dump

Description

int ncurses_scr_restore ( string $filename )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

ncurses_scr_init
ncurses_scr_set
Ncurses Functions


Inherit screen from file dump

ncurses_scr_restore
ncurses_scrl
Ncurses Functions
PHP Manual

ncurses_scr_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_set — Inherit screen from file dump

Description

int ncurses_scr_set ( string $filename )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

ncurses_scr_restore
ncurses_scrl
Ncurses Functions


Scroll window content up or down without changing current position

ncurses_scr_set
ncurses_show_panel
Ncurses Functions
PHP Manual

ncurses_scrl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scrl — Scroll window content up or down without changing current position

Description

int ncurses_scrl ( int $count )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

count

ncurses_scr_set
ncurses_show_panel
Ncurses Functions


Places an invisible panel on top of the stack, making it visible

ncurses_scrl
ncurses_slk_attr
Ncurses Functions
PHP Manual

ncurses_show_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_show_panel — Places an invisible panel on top of the stack, making it visible

Description

int ncurses_show_panel ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

ncurses_scrl
ncurses_slk_attr
Ncurses Functions


Returns current soft label key attribute

ncurses_show_panel
ncurses_slk_attroff
Ncurses Functions
PHP Manual

ncurses_slk_attr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attr — Returns current soft label key attribute

Description

int ncurses_slk_attr ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the current soft label key attribute.

Return Values

The attribute, as an integer.

ncurses_show_panel
ncurses_slk_attroff
Ncurses Functions


Turn off the given attributes for soft function-key labels

ncurses_slk_attr
ncurses_slk_attron
Ncurses Functions
PHP Manual

ncurses_slk_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attroff — Turn off the given attributes for soft function-key labels

Description

int ncurses_slk_attroff ( int $intarg )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg

ncurses_slk_attr
ncurses_slk_attron
Ncurses Functions


Turn on the given attributes for soft function-key labels

ncurses_slk_attroff
ncurses_slk_attrset
Ncurses Functions
PHP Manual

ncurses_slk_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attron — Turn on the given attributes for soft function-key labels

Description

int ncurses_slk_attron ( int $intarg )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg

ncurses_slk_attroff
ncurses_slk_attrset
Ncurses Functions


Set given attributes for soft function-key labels

ncurses_slk_attron
ncurses_slk_clear
Ncurses Functions
PHP Manual

ncurses_slk_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attrset — Set given attributes for soft function-key labels

Description

int ncurses_slk_attrset ( int $intarg )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg

ncurses_slk_attron
ncurses_slk_clear
Ncurses Functions


Clears soft labels from screen

ncurses_slk_attrset
ncurses_slk_color
Ncurses Functions
PHP Manual

ncurses_slk_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_clear — Clears soft labels from screen

Description

bool ncurses_slk_clear ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

The function ncurses_slk_clear() clears soft label keys from screen.

Return Values

Returns TRUE on errors, FALSE otherwise.

ncurses_slk_attrset
ncurses_slk_color
Ncurses Functions


Sets color for soft label keys

ncurses_slk_clear
ncurses_slk_init
Ncurses Functions
PHP Manual

ncurses_slk_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_color — Sets color for soft label keys

Description

int ncurses_slk_color ( int $intarg )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg

ncurses_slk_clear
ncurses_slk_init
Ncurses Functions


Initializes soft label key functions

ncurses_slk_color
ncurses_slk_noutrefresh
Ncurses Functions
PHP Manual

ncurses_slk_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_init — Initializes soft label key functions

Description

bool ncurses_slk_init ( int $format )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Initializes soft label key functions

This function must be called before ncurses_init() or ncurses_newwin() is called.

Parameters

format

If ncurses_init() eventually uses a line from stdscr to emulate the soft labels, then this parameter determines how the labels are arranged of the screen.

0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.

Return Values

Returns TRUE on success or FALSE on failure.

ncurses_slk_color
ncurses_slk_noutrefresh
Ncurses Functions


Copies soft label keys to virtual screen

ncurses_slk_init
ncurses_slk_refresh
Ncurses Functions
PHP Manual

ncurses_slk_noutrefresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_noutrefresh — Copies soft label keys to virtual screen

Description

bool ncurses_slk_noutrefresh ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_slk_init
ncurses_slk_refresh
Ncurses Functions


Copies soft label keys to screen

ncurses_slk_noutrefresh
ncurses_slk_restore
Ncurses Functions
PHP Manual

ncurses_slk_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_refresh — Copies soft label keys to screen

Description

int ncurses_slk_refresh ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Copies soft label keys from virtual screen to physical screen.

ncurses_slk_noutrefresh
ncurses_slk_restore
Ncurses Functions


Restores soft label keys

ncurses_slk_refresh
ncurses_slk_set
Ncurses Functions
PHP Manual

ncurses_slk_restore

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_restore — Restores soft label keys

Description

int ncurses_slk_restore ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Restores the soft label keys after ncurses_slk_clear() has been performed.

ncurses_slk_refresh
ncurses_slk_set
Ncurses Functions


Sets function key labels

ncurses_slk_restore
ncurses_slk_touch
Ncurses Functions
PHP Manual

ncurses_slk_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_set — Sets function key labels

Description

bool ncurses_slk_set ( int $labelnr , string $label , int $format )
Warning

This function is currently not documented; only its argument list is available.

Parameters

labelnr

label

format

ncurses_slk_restore
ncurses_slk_touch
Ncurses Functions


Forces output when ncurses_slk_noutrefresh is performed

ncurses_slk_set
ncurses_standend
Ncurses Functions
PHP Manual

ncurses_slk_touch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_touch — Forces output when ncurses_slk_noutrefresh is performed

Description

int ncurses_slk_touch ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.

ncurses_slk_set
ncurses_standend
Ncurses Functions


Stop using 'standout' attribute

ncurses_slk_touch
ncurses_standout
Ncurses Functions
PHP Manual

ncurses_standend

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standend — Stop using 'standout' attribute

Description

int ncurses_standend ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_slk_touch
ncurses_standout
Ncurses Functions


Start using 'standout' attribute

ncurses_standend
ncurses_start_color
Ncurses Functions
PHP Manual

ncurses_standout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standout — Start using 'standout' attribute

Description

int ncurses_standout ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_standend
ncurses_start_color
Ncurses Functions


Initializes color functionality

ncurses_standout
ncurses_termattrs
Ncurses Functions
PHP Manual

ncurses_start_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_start_color — Initializes color functionality

Description

int ncurses_start_color ( void )

Initializes color functionality in ncurses. This function must be called before any color manipulation functions are called and after ncurses_init() is called. It is good practice to call this function right after ncurses_init().

Parameters

This function has no parameters.

Return Values

Returns 0 on success, or -1 if the color table could not be allocated or ncurses was not initialized.

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_can_change_color() - Checks if terminal color definitions can be changed
  • ncurses_has_colors() - Checks if terminal has color capabilities

ncurses_standout
ncurses_termattrs
Ncurses Functions


Returns a logical OR of all attribute flags supported by terminal

ncurses_start_color
ncurses_termname
Ncurses Functions
PHP Manual

ncurses_termattrs

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termattrs — Returns a logical OR of all attribute flags supported by terminal

Description

bool ncurses_termattrs ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_start_color
ncurses_termname
Ncurses Functions


Returns terminals (short)-name

ncurses_termattrs
ncurses_timeout
Ncurses Functions
PHP Manual

ncurses_termname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termname — Returns terminals (short)-name

Description

string ncurses_termname ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns terminals shortname.

Return Values

Returns the shortname of the terminal, truncated to 14 characters. On errors, returns NULL.

See Also

  • ncurses_longname() - Returns terminals description

ncurses_termattrs
ncurses_timeout
Ncurses Functions


Set timeout for special key sequences

ncurses_termname
ncurses_top_panel
Ncurses Functions
PHP Manual

ncurses_timeout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_timeout — Set timeout for special key sequences

Description

void ncurses_timeout ( int $millisec )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

millisec

ncurses_termname
ncurses_top_panel
Ncurses Functions


Moves a visible panel to the top of the stack

ncurses_timeout
ncurses_typeahead
Ncurses Functions
PHP Manual

ncurses_top_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_top_panel — Moves a visible panel to the top of the stack

Description

int ncurses_top_panel ( resource $panel )
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

ncurses_timeout
ncurses_typeahead
Ncurses Functions


Specify different filedescriptor for typeahead checking

ncurses_top_panel
ncurses_ungetch
Ncurses Functions
PHP Manual

ncurses_typeahead

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_typeahead — Specify different filedescriptor for typeahead checking

Description

int ncurses_typeahead ( int $fd )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fd

ncurses_top_panel
ncurses_ungetch
Ncurses Functions


Put a character back into the input stream

ncurses_typeahead
ncurses_ungetmouse
Ncurses Functions
PHP Manual

ncurses_ungetch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetch — Put a character back into the input stream

Description

int ncurses_ungetch ( int $keycode )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

keycode

ncurses_typeahead
ncurses_ungetmouse
Ncurses Functions


Pushes mouse event to queue

ncurses_ungetch
ncurses_update_panels
Ncurses Functions
PHP Manual

ncurses_ungetmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetmouse — Pushes mouse event to queue

Description

bool ncurses_ungetmouse ( array $mevent )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Pushes a KEY_MOUSE event onto the unput queue and associates with this event the given state sata and screen-relative character cell coordinates, specified in mevent .

Parameters

mevent

An associative array specifying the event options:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

Return Values

Returns FALSE on success, TRUE otherwise.

See Also

  • ncurses_getmouse() - Reads mouse event

ncurses_ungetch
ncurses_update_panels
Ncurses Functions


Refreshes the virtual screen to reflect the relations between panels in the stack

ncurses_ungetmouse
ncurses_use_default_colors
Ncurses Functions
PHP Manual

ncurses_update_panels

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_update_panels — Refreshes the virtual screen to reflect the relations between panels in the stack

Description

void ncurses_update_panels ( void )
Warning

This function is currently not documented; only its argument list is available.

ncurses_ungetmouse
ncurses_use_default_colors
Ncurses Functions


Assign terminal default colors to color id -1

ncurses_update_panels
ncurses_use_env
Ncurses Functions
PHP Manual

ncurses_use_default_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_default_colors — Assign terminal default colors to color id -1

Description

bool ncurses_use_default_colors ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

ncurses_update_panels
ncurses_use_env
Ncurses Functions


Control use of environment information about terminal size

ncurses_use_default_colors
ncurses_use_extended_names
Ncurses Functions
PHP Manual

ncurses_use_env

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_env — Control use of environment information about terminal size

Description

void ncurses_use_env ( bool $flag )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

flag

ncurses_use_default_colors
ncurses_use_extended_names
Ncurses Functions


Control use of extended names in terminfo descriptions

ncurses_use_env
ncurses_vidattr
Ncurses Functions
PHP Manual

ncurses_use_extended_names

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_extended_names — Control use of extended names in terminfo descriptions

Description

int ncurses_use_extended_names ( bool $flag )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

flag

ncurses_use_env
ncurses_vidattr
Ncurses Functions


Display the string on the terminal in the video attribute mode

ncurses_use_extended_names
ncurses_vline
Ncurses Functions
PHP Manual

ncurses_vidattr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vidattr — Display the string on the terminal in the video attribute mode

Description

int ncurses_vidattr ( int $intarg )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg

ncurses_use_extended_names
ncurses_vline
Ncurses Functions


Draw a vertical line at current position using an attributed character and max. n characters long

ncurses_vidattr
ncurses_waddch
Ncurses Functions
PHP Manual

ncurses_vline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long

Description

int ncurses_vline ( int $charattr , int $n )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

charattr

n

ncurses_vidattr
ncurses_waddch
Ncurses Functions


Adds character at current position in a window and advance cursor

ncurses_vline
ncurses_waddstr
Ncurses Functions
PHP Manual

ncurses_waddch

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_waddch — Adds character at current position in a window and advance cursor

Description

int ncurses_waddch ( resource $window , int $ch )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ch

ncurses_vline
ncurses_waddstr
Ncurses Functions


Outputs text at current postion in window

ncurses_waddch
ncurses_wattroff
Ncurses Functions
PHP Manual

ncurses_waddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_waddstr — Outputs text at current postion in window

Description

int ncurses_waddstr ( resource $window , string $str [, int $n ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

str

n

ncurses_waddch
ncurses_wattroff
Ncurses Functions


Turns off attributes for a window

ncurses_waddstr
ncurses_wattron
Ncurses Functions
PHP Manual

ncurses_wattroff

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattroff — Turns off attributes for a window

Description

int ncurses_wattroff ( resource $window , int $attrs )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

attrs

ncurses_waddstr
ncurses_wattron
Ncurses Functions


Turns on attributes for a window

ncurses_wattroff
ncurses_wattrset
Ncurses Functions
PHP Manual

ncurses_wattron

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattron — Turns on attributes for a window

Description

int ncurses_wattron ( resource $window , int $attrs )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

attrs

ncurses_wattroff
ncurses_wattrset
Ncurses Functions


Set the attributes for a window

ncurses_wattron
ncurses_wborder
Ncurses Functions
PHP Manual

ncurses_wattrset

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattrset — Set the attributes for a window

Description

int ncurses_wattrset ( resource $window , int $attrs )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

attrs

ncurses_wattron
ncurses_wborder
Ncurses Functions


Draws a border around the window using attributed characters

ncurses_wattrset
ncurses_wclear
Ncurses Functions
PHP Manual

ncurses_wborder

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wborder — Draws a border around the window using attributed characters

Description

int ncurses_wborder ( resource $window , int $left , int $right , int $top , int $bottom , int $tl_corner , int $tr_corner , int $bl_corner , int $br_corner )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Draws the specified lines and corners around the passed window .

Use ncurses_border() for borders around the main window.

Parameters

Each parameter expects 0 to draw a line and 1 to skip it.

window

The window on which we operate

left

right

top

bottom

tl_corner

Top left corner

tr_corner

Top right corner

bl_corner

Bottom left corner

br_corner

Bottom right corner

See Also

  • ncurses_border() - Draw a border around the screen using attributed characters

ncurses_wattrset
ncurses_wclear
Ncurses Functions


Clears window

ncurses_wborder
ncurses_wcolor_set
Ncurses Functions
PHP Manual

ncurses_wclear

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wclear — Clears window

Description

int ncurses_wclear ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ncurses_wborder
ncurses_wcolor_set
Ncurses Functions


Sets windows color pairings

ncurses_wclear
ncurses_werase
Ncurses Functions
PHP Manual

ncurses_wcolor_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wcolor_set — Sets windows color pairings

Description

int ncurses_wcolor_set ( resource $window , int $color_pair )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

color_pair

ncurses_wclear
ncurses_werase
Ncurses Functions


Erase window contents

ncurses_wcolor_set
ncurses_wgetch
Ncurses Functions
PHP Manual

ncurses_werase

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_werase — Erase window contents

Description

int ncurses_werase ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ncurses_wcolor_set
ncurses_wgetch
Ncurses Functions


Reads a character from keyboard (window)

ncurses_werase
ncurses_whline
Ncurses Functions
PHP Manual

ncurses_wgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wgetch — Reads a character from keyboard (window)

Description

int ncurses_wgetch ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ncurses_werase
ncurses_whline
Ncurses Functions


Draws a horizontal line in a window at current position using an attributed character and max. n characters long

ncurses_wgetch
ncurses_wmouse_trafo
Ncurses Functions
PHP Manual

ncurses_whline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_whline — Draws a horizontal line in a window at current position using an attributed character and max. n characters long

Description

int ncurses_whline ( resource $window , int $charattr , int $n )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

charattr

n

ncurses_wgetch
ncurses_wmouse_trafo
Ncurses Functions


Transforms window/stdscr coordinates

ncurses_whline
ncurses_wmove
Ncurses Functions
PHP Manual

ncurses_wmouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmouse_trafo — Transforms window/stdscr coordinates

Description

bool ncurses_wmouse_trafo ( resource $window , int &$y , int &$x , bool $toscreen )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

x

y

toscreen

ncurses_whline
ncurses_wmove
Ncurses Functions


Moves windows output position

ncurses_wmouse_trafo
ncurses_wnoutrefresh
Ncurses Functions
PHP Manual

ncurses_wmove

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmove — Moves windows output position

Description

int ncurses_wmove ( resource $window , int $y , int $x )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

y

x

ncurses_wmouse_trafo
ncurses_wnoutrefresh
Ncurses Functions


Copies window to virtual screen

ncurses_wmove
ncurses_wrefresh
Ncurses Functions
PHP Manual

ncurses_wnoutrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wnoutrefresh — Copies window to virtual screen

Description

int ncurses_wnoutrefresh ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ncurses_wmove
ncurses_wrefresh
Ncurses Functions


Refresh window on terminal screen

ncurses_wnoutrefresh
ncurses_wstandend
Ncurses Functions
PHP Manual

ncurses_wrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wrefresh — Refresh window on terminal screen

Description

int ncurses_wrefresh ( resource $window )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ncurses_wnoutrefresh
ncurses_wstandend
Ncurses Functions


End standout mode for a window

ncurses_wrefresh
ncurses_wstandout
Ncurses Functions
PHP Manual

ncurses_wstandend

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandend — End standout mode for a window

Description

int ncurses_wstandend ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ncurses_wrefresh
ncurses_wstandout
Ncurses Functions


Enter standout mode for a window

ncurses_wstandend
ncurses_wvline
Ncurses Functions
PHP Manual

ncurses_wstandout

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandout — Enter standout mode for a window

Description

int ncurses_wstandout ( resource $window )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ncurses_wstandend
ncurses_wvline
Ncurses Functions


Draws a vertical line in a window at current position using an attributed character and max. n characters long

ncurses_wstandout
Readline
Ncurses Functions
PHP Manual

ncurses_wvline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wvline — Draws a vertical line in a window at current position using an attributed character and max. n characters long

Description

int ncurses_wvline ( resource $window , int $charattr , int $n )
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

charattr

n

ncurses_wstandout
Readline
Ncurses Functions


Send a beep to the terminal

Newt Functions
newt_button_bar
Newt Functions
PHP Manual

newt_bell

(PECL newt >= 0.1)

newt_bell — Send a beep to the terminal

Description

void newt_bell ( void )

This function sends a beep to the terminal.

Note: Depending on the terminal's settings, this beep may or may not be audible.

Return Values

No value is returned.

Newt Functions
newt_button_bar
Newt Functions


Create a new button

newt_button_bar
newt_centered_window
Newt Functions
PHP Manual

newt_button

(PECL newt >= 0.1)

newt_button — Create a new button

Description

resource newt_button ( int $left , int $top , string $text )

Creates a new button.

Parameters

left

X-coordinate of the button.

top

Y-coordinate of the button.

text

The text which should be displayed in the button.

Return Values

Returns a resource link to the created button component, or FALSE on error.

Examples

Example #1 A newt_button() example

<?php

$form = newt_form();

$ok_button = newt_button(5, 12, "Run Tool");

newt_form_add_component($form, $ok_button);

?>

See Also

  • newt_button_bar() - This function returns a grid containing the buttons created.

newt_button_bar
newt_centered_window
Newt Functions


This function returns a grid containing the buttons created.

newt_bell
newt_button
Newt Functions
PHP Manual

newt_button_bar

(PECL newt >= 0.1)

newt_button_bar — This function returns a grid containing the buttons created.

Description

resource newt_button_bar ( array &$buttons )

This function returns a grid containing the buttons created.

Parameters

buttons

Return Values

Returns grid containing the buttons created.

newt_bell
newt_button
Newt Functions


Open a centered window of the specified size

newt_button
newt_checkbox_get_value
Newt Functions
PHP Manual

newt_centered_window

(PECL newt >= 0.1)

newt_centered_window — Open a centered window of the specified size

Description

int newt_centered_window ( int $width , int $height [, string $title ] )

Open a centered window of the specified size.

Parameters

width

Window width

height

Window height

title

Window title

Return Values

Undefined value.

See Also

  • newt_pop_window() - Removes the top window from the display
  • newt_open_window() - Open a window of the specified size and position

newt_button
newt_checkbox_get_value
Newt Functions


newt_checkbox_tree
newt_clear_key_buffer
Newt Functions
PHP Manual

newt_checkbox

(PECL newt >= 0.1)

newt_checkbox —

Description

resource newt_checkbox ( int $left , int $top , string $text , string $def_value [, string $seq ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

def_value

seq

Return Values

newt_checkbox_tree
newt_clear_key_buffer
Newt Functions


Retreives value of checkox resource

newt_centered_window
newt_checkbox_set_flags
Newt Functions
PHP Manual

newt_checkbox_get_value

(PECL newt >= 0.1)

newt_checkbox_get_value — Retreives value of checkox resource

Description

string newt_checkbox_get_value ( resource $checkbox )

This function returns the character in the sequence which indicates the current value of the checkbox.

Parameters

checkbox

Return Values

Returns character indicating the value of the checkbox.

newt_centered_window
newt_checkbox_set_flags
Newt Functions


Configures checkbox resource

newt_checkbox_get_value
newt_checkbox_set_value
Newt Functions
PHP Manual

newt_checkbox_set_flags

(PECL newt >= 0.1)

newt_checkbox_set_flags — Configures checkbox resource

Description

void newt_checkbox_set_flags ( resource $checkbox , int $flags , int $sense )

This function allows to set various flags on checkbox resource.

Parameters

checkbox

flags

sense

Return Values

No value is returned.

newt_checkbox_get_value
newt_checkbox_set_value
Newt Functions


Sets the value of the checkbox

newt_checkbox_set_flags
newt_checkbox_tree_add_item
Newt Functions
PHP Manual

newt_checkbox_set_value

(PECL newt >= 0.1)

newt_checkbox_set_value — Sets the value of the checkbox

Description

void newt_checkbox_set_value ( resource $checkbox , string $value )

This function allows to set the current value of the checkbox resource.

Parameters

checkbox

value

Return Values

No value is returned.

newt_checkbox_set_flags
newt_checkbox_tree_add_item
Newt Functions


newt_checkbox_tree_set_width
newt_checkbox
Newt Functions
PHP Manual

newt_checkbox_tree

(PECL newt >= 0.1)

newt_checkbox_tree —

Description

resource newt_checkbox_tree ( int $left , int $top , int $height [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

height

flags

Return Values

newt_checkbox_tree_set_width
newt_checkbox
Newt Functions


Adds new item to the checkbox tree

newt_checkbox_set_value
newt_checkbox_tree_find_item
Newt Functions
PHP Manual

newt_checkbox_tree_add_item

(PECL newt >= 0.1)

newt_checkbox_tree_add_item — Adds new item to the checkbox tree

Description

void newt_checkbox_tree_add_item ( resource $checkboxtree , string $text , mixed $data , int $flags , int $index [, int $... ] )

This function allows to add new item to the checkbox tree.

Parameters

checkboxtree

text

data

flags

index

Return Values

No value is returned.

newt_checkbox_set_value
newt_checkbox_tree_find_item
Newt Functions


Finds an item in the checkbox tree

newt_checkbox_tree_add_item
newt_checkbox_tree_get_current
Newt Functions
PHP Manual

newt_checkbox_tree_find_item

(PECL newt >= 0.1)

newt_checkbox_tree_find_item — Finds an item in the checkbox tree

Description

array newt_checkbox_tree_find_item ( resource $checkboxtree , mixed $data )

Finds an item in the checkbox tree by item's data.

Parameters

checkboxtree

data

Return Values

Returns checkbox tree item resource, or NULL if it wasn't found.

newt_checkbox_tree_add_item
newt_checkbox_tree_get_current
Newt Functions


Returns checkbox tree selected item

newt_checkbox_tree_find_item
newt_checkbox_tree_get_entry_value
Newt Functions
PHP Manual

newt_checkbox_tree_get_current

(PECL newt >= 0.1)

newt_checkbox_tree_get_current — Returns checkbox tree selected item

Description

mixed newt_checkbox_tree_get_current ( resource $checkboxtree )

This method returns checkbox tree selected tem.

Parameters

checkboxtree

Return Values

Returns current (selected) checkbox tree item.

newt_checkbox_tree_find_item
newt_checkbox_tree_get_entry_value
Newt Functions


newt_checkbox_tree_get_current
newt_checkbox_tree_get_multi_selection
Newt Functions
PHP Manual

newt_checkbox_tree_get_entry_value

(PECL newt >= 0.1)

newt_checkbox_tree_get_entry_value —

Description

string newt_checkbox_tree_get_entry_value ( resource $checkboxtree , mixed $data )
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

data

Return Values

newt_checkbox_tree_get_current
newt_checkbox_tree_get_multi_selection
Newt Functions


newt_checkbox_tree_get_entry_value
newt_checkbox_tree_get_selection
Newt Functions
PHP Manual

newt_checkbox_tree_get_multi_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_multi_selection —

Description

array newt_checkbox_tree_get_multi_selection ( resource $checkboxtree , string $seqnum )
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

seqnum

Return Values

newt_checkbox_tree_get_entry_value
newt_checkbox_tree_get_selection
Newt Functions


newt_checkbox_tree_get_multi_selection
newt_checkbox_tree_multi
Newt Functions
PHP Manual

newt_checkbox_tree_get_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_selection —

Description

array newt_checkbox_tree_get_selection ( resource $checkboxtree )
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

Return Values

newt_checkbox_tree_get_multi_selection
newt_checkbox_tree_multi
Newt Functions


newt_checkbox_tree_get_selection
newt_checkbox_tree_set_current
Newt Functions
PHP Manual

newt_checkbox_tree_multi

(PECL newt >= 0.1)

newt_checkbox_tree_multi —

Description

resource newt_checkbox_tree_multi ( int $left , int $top , int $height , string $seq [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

height

seq

flags

Return Values

newt_checkbox_tree_get_selection
newt_checkbox_tree_set_current
Newt Functions


newt_checkbox_tree_multi
newt_checkbox_tree_set_entry_value
Newt Functions
PHP Manual

newt_checkbox_tree_set_current

(PECL newt >= 0.1)

newt_checkbox_tree_set_current —

Description

void newt_checkbox_tree_set_current ( resource $checkboxtree , mixed $data )
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

data

Return Values

No value is returned.

newt_checkbox_tree_multi
newt_checkbox_tree_set_entry_value
Newt Functions


newt_checkbox_tree_set_entry_value
newt_checkbox_tree_set_width
Newt Functions
PHP Manual

newt_checkbox_tree_set_entry

(PECL newt >= 0.1)

newt_checkbox_tree_set_entry —

Description

void newt_checkbox_tree_set_entry ( resource $checkboxtree , mixed $data , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

data

text

Return Values

No value is returned.

newt_checkbox_tree_set_entry_value
newt_checkbox_tree_set_width
Newt Functions


newt_checkbox_tree_set_current
newt_checkbox_tree_set_entry
Newt Functions
PHP Manual

newt_checkbox_tree_set_entry_value

(PECL newt >= 0.1)

newt_checkbox_tree_set_entry_value —

Description

void newt_checkbox_tree_set_entry_value ( resource $checkboxtree , mixed $data , string $value )
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

data

value

Return Values

No value is returned.

newt_checkbox_tree_set_current
newt_checkbox_tree_set_entry
Newt Functions


newt_checkbox_tree_set_entry
newt_checkbox_tree
Newt Functions
PHP Manual

newt_checkbox_tree_set_width

(PECL newt >= 0.1)

newt_checkbox_tree_set_width —

Description

void newt_checkbox_tree_set_width ( resource $checkbox_tree , int $width )
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkbox_tree

width

Return Values

No value is returned.

newt_checkbox_tree_set_entry
newt_checkbox_tree
Newt Functions


Discards the contents of the terminal's input buffer without waiting for additional input

newt_checkbox
newt_cls
Newt Functions
PHP Manual

newt_clear_key_buffer

(PECL newt >= 0.1)

newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input

Description

void newt_clear_key_buffer ( void )

Discards the contents of the terminal's input buffer without waiting for additional input.

Return Values

No value is returned.

See Also

  • newt_wait_for_key() - Doesn't return until a key has been pressed

newt_checkbox
newt_cls
Newt Functions


newt_clear_key_buffer
newt_compact_button
Newt Functions
PHP Manual

newt_cls

(PECL newt >= 0.1)

newt_cls —

Description

void newt_cls ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.

newt_clear_key_buffer
newt_compact_button
Newt Functions


newt_cls
newt_component_add_callback
Newt Functions
PHP Manual

newt_compact_button

(PECL newt >= 0.1)

newt_compact_button —

Description

resource newt_compact_button ( int $left , int $top , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

Return Values

newt_cls
newt_component_add_callback
Newt Functions


newt_compact_button
newt_component_takes_focus
Newt Functions
PHP Manual

newt_component_add_callback

(PECL newt >= 0.1)

newt_component_add_callback —

Description

void newt_component_add_callback ( resource $component , mixed $func_name , mixed $data )
Warning

This function is currently not documented; only its argument list is available.

Parameters

component

func_name

data

Return Values

No value is returned.

newt_compact_button
newt_component_takes_focus
Newt Functions


newt_component_add_callback
newt_create_grid
Newt Functions
PHP Manual

newt_component_takes_focus

(PECL newt >= 0.1)

newt_component_takes_focus —

Description

void newt_component_takes_focus ( resource $component , bool $takes_focus )
Warning

This function is currently not documented; only its argument list is available.

Parameters

component

takes_focus

Return Values

No value is returned.

newt_component_add_callback
newt_create_grid
Newt Functions


newt_component_takes_focus
newt_cursor_off
Newt Functions
PHP Manual

newt_create_grid

(PECL newt >= 0.1)

newt_create_grid —

Description

resource newt_create_grid ( int $cols , int $rows )
Warning

This function is currently not documented; only its argument list is available.

Parameters

cols

rows

Return Values

newt_component_takes_focus
newt_cursor_off
Newt Functions


newt_create_grid
newt_cursor_on
Newt Functions
PHP Manual

newt_cursor_off

(PECL newt >= 0.1)

newt_cursor_off —

Description

void newt_cursor_off ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.

newt_create_grid
newt_cursor_on
Newt Functions


newt_cursor_off
newt_delay
Newt Functions
PHP Manual

newt_cursor_on

(PECL newt >= 0.1)

newt_cursor_on —

Description

void newt_cursor_on ( void )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

newt_cursor_off
newt_delay
Newt Functions


newt_cursor_on
newt_draw_form
Newt Functions
PHP Manual

newt_delay

(PECL newt >= 0.1)

newt_delay —

Description

void newt_delay ( int $microseconds )
Warning

This function is currently not documented; only its argument list is available.

Parameters

microseconds

Return Values

No value is returned.

newt_cursor_on
newt_draw_form
Newt Functions


newt_delay
newt_draw_root_text
Newt Functions
PHP Manual

newt_draw_form

(PECL newt >= 0.1)

newt_draw_form —

Description

void newt_draw_form ( resource $form )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

Return Values

No value is returned.

newt_delay
newt_draw_root_text
Newt Functions


Displays the string text at the position indicated

newt_draw_form
newt_entry_get_value
Newt Functions
PHP Manual

newt_draw_root_text

(PECL newt >= 0.1)

newt_draw_root_text — Displays the string text at the position indicated

Description

void newt_draw_root_text ( int $left , int $top , string $text )

Displays the string text at the position indicated.

Parameters

left

Column number

Note: If left is negative, the position is measured from the opposite side of the screen.

top

Line number

Note: If top is negative, the position is measured from the opposite side of the screen.

text

Text to display.

Return Values

No value is returned.

Examples

Example #1 A newt_draw_root_text() example

This code demonstrates drawing of titles in the both corners of the screen.

<?php
 newt_init();
 newt_cls();

 newt_draw_root_text (2, 0, "Some root text");
 newt_refresh();
 sleep(1);

 newt_draw_root_text (-30, 0, "Root text in the other corner");
 newt_refresh();
 sleep(1);

 newt_finished();
?>

See Also

  • newt_push_help_line() - Saves the current help line on a stack, and displays the new line
  • newt_pop_help_line() - Replaces the current help line with the one from the stack

newt_draw_form
newt_entry_get_value
Newt Functions


newt_entry_set
newt_finished
Newt Functions
PHP Manual

newt_entry

(PECL newt >= 0.1)

newt_entry —

Description

resource newt_entry ( int $left , int $top , int $width [, string $init_value [, int $flags ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

width

init_value

flags

Return Values

newt_entry_set
newt_finished
Newt Functions


newt_draw_root_text
newt_entry_set_filter
Newt Functions
PHP Manual

newt_entry_get_value

(PECL newt >= 0.1)

newt_entry_get_value —

Description

string newt_entry_get_value ( resource $entry )
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

Return Values

newt_draw_root_text
newt_entry_set_filter
Newt Functions


newt_entry_set_flags
newt_entry
Newt Functions
PHP Manual

newt_entry_set

(PECL newt >= 0.1)

newt_entry_set —

Description

void newt_entry_set ( resource $entry , string $value [, bool $cursor_at_end ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

value

cursor_at_end

Return Values

No value is returned.

newt_entry_set_flags
newt_entry
Newt Functions


newt_entry_get_value
newt_entry_set_flags
Newt Functions
PHP Manual

newt_entry_set_filter

(PECL newt >= 0.1)

newt_entry_set_filter —

Description

void newt_entry_set_filter ( resource $entry , callback $filter , mixed $data )
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

filter

data

Return Values

No value is returned.

newt_entry_get_value
newt_entry_set_flags
Newt Functions


newt_entry_set_filter
newt_entry_set
Newt Functions
PHP Manual

newt_entry_set_flags

(PECL newt >= 0.1)

newt_entry_set_flags —

Description

void newt_entry_set_flags ( resource $entry , int $flags , int $sense )
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

flags

sense

Return Values

No value is returned.

newt_entry_set_filter
newt_entry_set
Newt Functions


Uninitializes newt interface

newt_entry
newt_form_add_component
Newt Functions
PHP Manual

newt_finished

(PECL newt >= 0.1)

newt_finished — Uninitializes newt interface

Description

int newt_finished ( void )

Uninitializes newt interface. This function be called, when program is ready to exit.

Return Values

Returns 1 on success, 0 on failure.

See Also

  • newt_init() - Initialize newt

newt_entry
newt_form_add_component
Newt Functions


Create a form

newt_form_watch_fd
newt_get_screen_size
Newt Functions
PHP Manual

newt_form

(PECL newt >= 0.1)

newt_form — Create a form

Description

resource newt_form ([ resource $vert_bar [, string $help [, int $flags ]]] )

Create a new form.

Parameters

vert_bar

Vertical scrollbar which should be associated with the form

help

Help text string

flags

Various flags

Return Values

Returns a resource link to the created form component, or FALSE on error.

Examples

Example #1 A newt_form() example

Displays a single button "Quit", which closes the application once it's pressed.

<?php
newt_init();
newt_cls();

$myform = newt_form();
$button = newt_button (5, 12, "Quit");

newt_form_add_component ($myform, $button);
newt_refresh ();
newt_run_form ($myform);

newt_finished ();
newt_form_destroy ($myform);
?>

See Also

  • newt_form_run() - Runs a form
  • newt_run_form() - Runs a form
  • newt_form_add_component() - Adds a single component to the form
  • newt_form_add_components() - Add several components to the form
  • newt_form_destroy() - Destroys a form

newt_form_watch_fd
newt_get_screen_size
Newt Functions


Adds a single component to the form

newt_finished
newt_form_add_components
Newt Functions
PHP Manual

newt_form_add_component

(PECL newt >= 0.1)

newt_form_add_component — Adds a single component to the form

Description

void newt_form_add_component ( resource $form , resource $component )

Adds a single component to the form .

Parameters

form

Form to which component will be added

component

Component to add to the form

Return Values

No value is returned.

Examples

Example #1 A newt_form_add_component() example

<?php
$form = newt_form();

$options = array("Authentication configuration", "Firewall configuration",
"Mouse configuration", "Network configuration", "Printer configuration",
"System services");

$list = newt_listbox(3, 2, 10);

foreach ($options as $l_item) {
    newt_listbox_add_entry($list, $l_item, $l_item);
}

newt_form_add_component($form, $list);
?>

See Also

  • newt_form_add_components() - Add several components to the form

newt_finished
newt_form_add_components
Newt Functions


Add several components to the form

newt_form_add_component
newt_form_add_hot_key
Newt Functions
PHP Manual

newt_form_add_components

(PECL newt >= 0.1)

newt_form_add_components — Add several components to the form

Description

void newt_form_add_components ( resource $form , array $components )

Adds several components to the form .

Parameters

form

Form to which components will be added

components

Array of components to add to the form

Return Values

No value is returned.

Examples

Example #1 A newt_form_add_components() example

<?php
$form = newt_form();

$b1 = newt_button(5, 12, "Run Tool");
$b2 = newt_button(21, 12, "Quit");

newt_form_add_components($form, array($b1, $b2));
?>

See Also

  • newt_form_add_component() - Adds a single component to the form

newt_form_add_component
newt_form_add_hot_key
Newt Functions


newt_form_add_components
newt_form_destroy
Newt Functions
PHP Manual

newt_form_add_hot_key

(PECL newt >= 0.1)

newt_form_add_hot_key —

Description

void newt_form_add_hot_key ( resource $form , int $key )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

key

Return Values

No value is returned.

newt_form_add_components
newt_form_destroy
Newt Functions


Destroys a form

newt_form_add_hot_key
newt_form_get_current
Newt Functions
PHP Manual

newt_form_destroy

(PECL newt >= 0.1)

newt_form_destroy — Destroys a form

Description

void newt_form_destroy ( resource $form )

This function frees the memory resources used by the form and all of the components which have been added to the form (including those components which are on subforms). Once a form has been destroyed, none of the form's components can be used.

Parameters

form

Form component, which is going to be destroyed

Return Values

No value is returned.

See Also

  • newt_form_run() - Runs a form
  • newt_run_form() - Runs a form

newt_form_add_hot_key
newt_form_get_current
Newt Functions


newt_form_destroy
newt_form_run
Newt Functions
PHP Manual

newt_form_get_current

(PECL newt >= 0.1)

newt_form_get_current —

Description

resource newt_form_get_current ( resource $form )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

Return Values

newt_form_destroy
newt_form_run
Newt Functions


Runs a form

newt_form_get_current
newt_form_set_background
Newt Functions
PHP Manual

newt_form_run

(PECL newt >= 0.1)

newt_form_run — Runs a form

Description

void newt_form_run ( resource $form , array &$exit_struct )

This function runs the form passed to it.

Parameters

form

Form component

exit_struct

Array, used for returning information after running the form component. Keys and values are described in the following table:

Form Exit Structure
Index Key | Value Type | Description
reason | integer | The reason, why the form has been exited. Possible values are defined here.
watch | resource | Resource link, specified in newt_form_watch_fd()
key | integer | Hotkey
component | resource | Component, which caused the form to exit

Return Values

No value is returned.

See Also

  • newt_run_form() - Runs a form

newt_form_get_current
newt_form_set_background
Newt Functions


newt_form_run
newt_form_set_height
Newt Functions
PHP Manual

newt_form_set_background

(PECL newt >= 0.1)

newt_form_set_background —

Description

void newt_form_set_background ( resource $from , int $background )
Warning

This function is currently not documented; only its argument list is available.

Parameters

from

background

Return Values

No value is returned.

newt_form_run
newt_form_set_height
Newt Functions


newt_form_set_background
newt_form_set_size
Newt Functions
PHP Manual

newt_form_set_height

(PECL newt >= 0.1)

newt_form_set_height —

Description

void newt_form_set_height ( resource $form , int $height )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

height

Return Values

No value is returned.

newt_form_set_background
newt_form_set_size
Newt Functions


newt_form_set_height
newt_form_set_timer
Newt Functions
PHP Manual

newt_form_set_size

(PECL newt >= 0.1)

newt_form_set_size —

Description

void newt_form_set_size ( resource $form )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

Return Values

No value is returned.

newt_form_set_height
newt_form_set_timer
Newt Functions


newt_form_set_size
newt_form_set_width
Newt Functions
PHP Manual

newt_form_set_timer

(PECL newt >= 0.1)

newt_form_set_timer —

Description

void newt_form_set_timer ( resource $form , int $milliseconds )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

milliseconds

Return Values

No value is returned.

newt_form_set_size
newt_form_set_width
Newt Functions


newt_form_set_timer
newt_form_watch_fd
Newt Functions
PHP Manual

newt_form_set_width

(PECL newt >= 0.1)

newt_form_set_width —

Description

void newt_form_set_width ( resource $form , int $width )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

width

Return Values

No value is returned.

newt_form_set_timer
newt_form_watch_fd
Newt Functions


newt_form_set_width
newt_form
Newt Functions
PHP Manual

newt_form_watch_fd

(PECL newt >= 0.1)

newt_form_watch_fd —

Description

void newt_form_watch_fd ( resource $form , resource $stream [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

stream

flags

Return Values

No value is returned.

newt_form_set_width
newt_form
Newt Functions


Fills in the passed references with the current size of the terminal

newt_form
newt_grid_add_components_to_form
Newt Functions
PHP Manual

newt_get_screen_size

(PECL newt >= 0.1)

newt_get_screen_size — Fills in the passed references with the current size of the terminal

Description

void newt_get_screen_size ( int &$cols , int &$rows )

Fills in the passed references with the current size of the terminal.

Parameters

cols

Number of columns in the terminal

rows

Number of rows in the terminal

Return Values

No value is returned.

Examples

Example #1 A newt_get_screen_size() example

This code prints out the screen size of your terminal.

<?php
 newt_init();
 newt_get_screen_size (&$cols, &$rows);
 newt_finished();

 print "Your terminal size is: {$cols}x{$rows}\n";
?>

The above example will output:

Your terminal size is: 138x47

newt_form
newt_grid_add_components_to_form
Newt Functions


newt_get_screen_size
newt_grid_basic_window
Newt Functions
PHP Manual

newt_grid_add_components_to_form

(PECL newt >= 0.1)

newt_grid_add_components_to_form —

Description

void newt_grid_add_components_to_form ( resource $grid , resource $form , bool $recurse )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

form

recurse

Return Values

No value is returned.

newt_get_screen_size
newt_grid_basic_window
Newt Functions


newt_grid_add_components_to_form
newt_grid_free
Newt Functions
PHP Manual

newt_grid_basic_window

(PECL newt >= 0.1)

newt_grid_basic_window —

Description

resource newt_grid_basic_window ( resource $text , resource $middle , resource $buttons )
Warning

This function is currently not documented; only its argument list is available.

Parameters

text

middle

buttons

Return Values

newt_grid_add_components_to_form
newt_grid_free
Newt Functions


newt_grid_basic_window
newt_grid_get_size
Newt Functions
PHP Manual

newt_grid_free

(PECL newt >= 0.1)

newt_grid_free —

Description

void newt_grid_free ( resource $grid , bool $recurse )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

recurse

Return Values

No value is returned.

newt_grid_basic_window
newt_grid_get_size
Newt Functions


newt_grid_free
newt_grid_h_close_stacked
Newt Functions
PHP Manual

newt_grid_get_size

(PECL newt >= 0.1)

newt_grid_get_size —

Description

void newt_grid_get_size ( resouce $grid , int &$width , int &$height )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

width

height

Return Values

No value is returned.

newt_grid_free
newt_grid_h_close_stacked
Newt Functions


newt_grid_get_size
newt_grid_h_stacked
Newt Functions
PHP Manual

newt_grid_h_close_stacked

(PECL newt >= 0.1)

newt_grid_h_close_stacked —

Description

resource newt_grid_h_close_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

element1_type

element1

Return Values

newt_grid_get_size
newt_grid_h_stacked
Newt Functions


newt_grid_h_close_stacked
newt_grid_place
Newt Functions
PHP Manual

newt_grid_h_stacked

(PECL newt >= 0.1)

newt_grid_h_stacked —

Description

resource newt_grid_h_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

element1_type

element1

Return Values

newt_grid_h_close_stacked
newt_grid_place
Newt Functions


newt_grid_h_stacked
newt_grid_set_field
Newt Functions
PHP Manual

newt_grid_place

(PECL newt >= 0.1)

newt_grid_place —

Description

void newt_grid_place ( resource $grid , int $left , int $top )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

left

top

Return Values

No value is returned.

newt_grid_h_stacked
newt_grid_set_field
Newt Functions


newt_grid_place
newt_grid_simple_window
Newt Functions
PHP Manual

newt_grid_set_field

(PECL newt >= 0.1)

newt_grid_set_field —

Description

void newt_grid_set_field ( resource $grid , int $col , int $row , int $type , resource $val , int $pad_left , int $pad_top , int $pad_right , int $pad_bottom , int $anchor [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

col

row

type

val

pad_left

pad_top

pad_right

pad_bottom

anchor

flags

Return Values

No value is returned.

newt_grid_place
newt_grid_simple_window
Newt Functions


newt_grid_set_field
newt_grid_v_close_stacked
Newt Functions
PHP Manual

newt_grid_simple_window

(PECL newt >= 0.1)

newt_grid_simple_window —

Description

resource newt_grid_simple_window ( resource $text , resource $middle , resource $buttons )
Warning

This function is currently not documented; only its argument list is available.

Parameters

text

middle

buttons

Return Values

newt_grid_set_field
newt_grid_v_close_stacked
Newt Functions


newt_grid_simple_window
newt_grid_v_stacked
Newt Functions
PHP Manual

newt_grid_v_close_stacked

(PECL newt >= 0.1)

newt_grid_v_close_stacked —

Description

resource newt_grid_v_close_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

element1_type

element1

Return Values

newt_grid_simple_window
newt_grid_v_stacked
Newt Functions


newt_grid_v_close_stacked
newt_grid_wrapped_window_at
Newt Functions
PHP Manual

newt_grid_v_stacked

(PECL newt >= 0.1)

newt_grid_v_stacked —

Description

resource newt_grid_v_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

element1_type

element1

Return Values

newt_grid_v_close_stacked
newt_grid_wrapped_window_at
Newt Functions


newt_grid_wrapped_window_at
newt_init
Newt Functions
PHP Manual

newt_grid_wrapped_window

(PECL newt >= 0.1)

newt_grid_wrapped_window —

Description

void newt_grid_wrapped_window ( resource $grid , string $title )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

title

Return Values

No value is returned.

newt_grid_wrapped_window_at
newt_init
Newt Functions


newt_grid_v_stacked
newt_grid_wrapped_window
Newt Functions
PHP Manual

newt_grid_wrapped_window_at

(PECL newt >= 0.1)

newt_grid_wrapped_window_at —

Description

void newt_grid_wrapped_window_at ( resource $grid , string $title , int $left , int $top )
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

title

left

top

Return Values

No value is returned.

newt_grid_v_stacked
newt_grid_wrapped_window
Newt Functions


Initialize newt

newt_grid_wrapped_window
newt_label_set_text
Newt Functions
PHP Manual

newt_init

(PECL newt >= 0.1)

newt_init — Initialize newt

Description

int newt_init ( void )

Initializes the newt interface. This function must be called before any other newt function.

Return Values

Returns 1 on success, 0 on failure.

See Also

  • newt_finished() - Uninitializes newt interface

newt_grid_wrapped_window
newt_label_set_text
Newt Functions


newt_label_set_text
newt_listbox_append_entry
Newt Functions
PHP Manual

newt_label

(PECL newt >= 0.1)

newt_label —

Description

resource newt_label ( int $left , int $top , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

Return Values

newt_label_set_text
newt_listbox_append_entry
Newt Functions


newt_init
newt_label
Newt Functions
PHP Manual

newt_label_set_text

(PECL newt >= 0.1)

newt_label_set_text —

Description

void newt_label_set_text ( resource $label , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

label

text

Return Values

No value is returned.

newt_init
newt_label
Newt Functions


newt_listbox_set_width
newt_listitem_get_data
Newt Functions
PHP Manual

newt_listbox

(PECL newt >= 0.1)

newt_listbox —

Description

resource newt_listbox ( int $left , int $top , int $height [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

height

flags

Return Values

newt_listbox_set_width
newt_listitem_get_data
Newt Functions


newt_label
newt_listbox_clear_selection
Newt Functions
PHP Manual

newt_listbox_append_entry

(PECL newt >= 0.1)

newt_listbox_append_entry —

Description

void newt_listbox_append_entry ( resource $listbox , string $text , mixed $data )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

text

data

Return Values

No value is returned.

newt_label
newt_listbox_clear_selection
Newt Functions


newt_listbox_clear_selection
newt_listbox_delete_entry
Newt Functions
PHP Manual

newt_listbox_clear

(PECL newt >= 0.1)

newt_listbox_clear —

Description

void newt_listbox_clear ( resource $listobx )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listobx

Return Values

No value is returned.

newt_listbox_clear_selection
newt_listbox_delete_entry
Newt Functions


newt_listbox_append_entry
newt_listbox_clear
Newt Functions
PHP Manual

newt_listbox_clear_selection

(PECL newt >= 0.1)

newt_listbox_clear_selection —

Description

void newt_listbox_clear_selection ( resource $listbox )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values

No value is returned.

newt_listbox_append_entry
newt_listbox_clear
Newt Functions


newt_listbox_clear
newt_listbox_get_current
Newt Functions
PHP Manual

newt_listbox_delete_entry

(PECL newt >= 0.1)

newt_listbox_delete_entry —

Description

void newt_listbox_delete_entry ( resource $listbox , mixed $key )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

key

Return Values

No value is returned.

newt_listbox_clear
newt_listbox_get_current
Newt Functions


newt_listbox_delete_entry
newt_listbox_get_selection
Newt Functions
PHP Manual

newt_listbox_get_current

(PECL newt >= 0.1)

newt_listbox_get_current —

Description

string newt_listbox_get_current ( resource $listbox )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values

newt_listbox_delete_entry
newt_listbox_get_selection
Newt Functions


newt_listbox_get_current
newt_listbox_insert_entry
Newt Functions
PHP Manual

newt_listbox_get_selection

(PECL newt >= 0.1)

newt_listbox_get_selection —

Description

array newt_listbox_get_selection ( resource $listbox )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values

newt_listbox_get_current
newt_listbox_insert_entry
Newt Functions


newt_listbox_get_selection
newt_listbox_item_count
Newt Functions
PHP Manual

newt_listbox_insert_entry

(PECL newt >= 0.1)

newt_listbox_insert_entry —

Description

void newt_listbox_insert_entry ( resource $listbox , string $text , mixed $data , mixed $key )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

text

data

key

Return Values

No value is returned.

newt_listbox_get_selection
newt_listbox_item_count
Newt Functions


newt_listbox_insert_entry
newt_listbox_select_item
Newt Functions
PHP Manual

newt_listbox_item_count

(PECL newt >= 0.1)

newt_listbox_item_count —

Description

int newt_listbox_item_count ( resource $listbox )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values

newt_listbox_insert_entry
newt_listbox_select_item
Newt Functions


newt_listbox_item_count
newt_listbox_set_current_by_key
Newt Functions
PHP Manual

newt_listbox_select_item

(PECL newt >= 0.1)

newt_listbox_select_item —

Description

void newt_listbox_select_item ( resource $listbox , mixed $key , int $sense )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

key

sense

Return Values

No value is returned.

newt_listbox_item_count
newt_listbox_set_current_by_key
Newt Functions


newt_listbox_set_current_by_key
newt_listbox_set_data
Newt Functions
PHP Manual

newt_listbox_set_current

(PECL newt >= 0.1)

newt_listbox_set_current —

Description

void newt_listbox_set_current ( resource $listbox , int $num )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

num

Return Values

No value is returned.

newt_listbox_set_current_by_key
newt_listbox_set_data
Newt Functions


newt_listbox_select_item
newt_listbox_set_current
Newt Functions
PHP Manual

newt_listbox_set_current_by_key

(PECL newt >= 0.1)

newt_listbox_set_current_by_key —

Description

void newt_listbox_set_current_by_key ( resource $listbox , mixed $key )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

key

Return Values

No value is returned.

newt_listbox_select_item
newt_listbox_set_current
Newt Functions


newt_listbox_set_current
newt_listbox_set_entry
Newt Functions
PHP Manual

newt_listbox_set_data

(PECL newt >= 0.1)

newt_listbox_set_data —

Description

void newt_listbox_set_data ( resource $listbox , int $num , mixed $data )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

num

data

Return Values

No value is returned.

newt_listbox_set_current
newt_listbox_set_entry
Newt Functions


newt_listbox_set_data
newt_listbox_set_width
Newt Functions
PHP Manual

newt_listbox_set_entry

(PECL newt >= 0.1)

newt_listbox_set_entry —

Description

void newt_listbox_set_entry ( resource $listbox , int $num , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

num

text

Return Values

No value is returned.

newt_listbox_set_data
newt_listbox_set_width
Newt Functions


newt_listbox_set_entry
newt_listbox
Newt Functions
PHP Manual

newt_listbox_set_width

(PECL newt >= 0.1)

newt_listbox_set_width —

Description

void newt_listbox_set_width ( resource $listbox , int $width )
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

width

Return Values

No value is returned.

newt_listbox_set_entry
newt_listbox
Newt Functions


newt_listitem_set
newt_open_window
Newt Functions
PHP Manual

newt_listitem

(PECL newt >= 0.1)

newt_listitem —

Description

resource newt_listitem ( int $left , int $top , string $text , bool $is_default , resouce $prev_item , mixed $data [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

is_default

prev_item

data

flags

Return Values

newt_listitem_set
newt_open_window
Newt Functions


newt_listbox
newt_listitem_set
Newt Functions
PHP Manual

newt_listitem_get_data

(PECL newt >= 0.1)

newt_listitem_get_data —

Description

mixed newt_listitem_get_data ( resource $item )
Warning

This function is currently not documented; only its argument list is available.

Parameters

item

Return Values

newt_listbox
newt_listitem_set
Newt Functions


newt_listitem_get_data
newt_listitem
Newt Functions
PHP Manual

newt_listitem_set

(PECL newt >= 0.1)

newt_listitem_set —

Description

void newt_listitem_set ( resource $item , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

item

text

Return Values

No value is returned.

newt_listitem_get_data
newt_listitem
Newt Functions


Open a window of the specified size and position

newt_listitem
newt_pop_help_line
Newt Functions
PHP Manual

newt_open_window

(PECL newt >= 0.1)

newt_open_window — Open a window of the specified size and position

Description

int newt_open_window ( int $left , int $top , int $width , int $height [, string $title ] )

Open a window of the specified size and position.

Parameters

left

Location of the upper left-hand corner of the window (column number)

top

Location of the upper left-hand corner of the window (row number)

width

Window width

height

Window height

title

Window title

Return Values

Returns 1 on success, 0 on failure.

See Also

  • newt_pop_window() - Removes the top window from the display
  • newt_centered_window() - Open a centered window of the specified size

newt_listitem
newt_pop_help_line
Newt Functions


Replaces the current help line with the one from the stack

newt_open_window
newt_pop_window
Newt Functions
PHP Manual

newt_pop_help_line

(PECL newt >= 0.1)

newt_pop_help_line — Replaces the current help line with the one from the stack

Description

void newt_pop_help_line ( void )

Replaces the current help line with the one from the stack.

Note: It's important not to call to newt_pop_help_line() more than newt_push_help_line().

Return Values

No value is returned.

See Also

  • newt_push_help_line() - Saves the current help line on a stack, and displays the new line

newt_open_window
newt_pop_window
Newt Functions


Removes the top window from the display

newt_pop_help_line
newt_push_help_line
Newt Functions
PHP Manual

newt_pop_window

(PECL newt >= 0.1)

newt_pop_window — Removes the top window from the display

Description

void newt_pop_window ( void )

Removes the top window from the display, and redraws the display areas which the window overwrote.

Return Values

No value is returned.

See Also

  • newt_open_window() - Open a window of the specified size and position
  • newt_centered_window() - Open a centered window of the specified size

newt_pop_help_line
newt_push_help_line
Newt Functions


Saves the current help line on a stack, and displays the new line

newt_pop_window
newt_radio_get_current
Newt Functions
PHP Manual

newt_push_help_line

(PECL newt >= 0.1)

newt_push_help_line — Saves the current help line on a stack, and displays the new line

Description

void newt_push_help_line ([ string $text ] )

Saves the current help line on a stack, and displays the new line.

Parameters

text

New help text message

Note: If not specified, the help line is cleared.

Return Values

No value is returned.

See Also

  • newt_pop_help_line() - Replaces the current help line with the one from the stack

newt_pop_window
newt_radio_get_current
Newt Functions


newt_push_help_line
newt_radiobutton
Newt Functions
PHP Manual

newt_radio_get_current

(PECL newt >= 0.1)

newt_radio_get_current —

Description

resource newt_radio_get_current ( resource $set_member )
Warning

This function is currently not documented; only its argument list is available.

Parameters

set_member

Return Values

newt_push_help_line
newt_radiobutton
Newt Functions


newt_radio_get_current
newt_redraw_help_line
Newt Functions
PHP Manual

newt_radiobutton

(PECL newt >= 0.1)

newt_radiobutton —

Description

resource newt_radiobutton ( int $left , int $top , string $text , bool $is_default [, resource $prev_button ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

is_default

prev_button

Return Values

newt_radio_get_current
newt_redraw_help_line
Newt Functions


newt_radiobutton
newt_reflow_text
Newt Functions
PHP Manual

newt_redraw_help_line

(PECL newt >= 0.1)

newt_redraw_help_line —

Description

void newt_redraw_help_line ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.

newt_radiobutton
newt_reflow_text
Newt Functions


newt_redraw_help_line
newt_refresh
Newt Functions
PHP Manual

newt_reflow_text

(PECL newt >= 0.1)

newt_reflow_text —

Description

string newt_reflow_text ( string $text , int $width , int $flex_down , int $flex_up , int &$actual_width , int &$actual_height )
Warning

This function is currently not documented; only its argument list is available.

Parameters

text

width

flex_down

flex_up

actual_width

actual_height

Return Values

newt_redraw_help_line
newt_refresh
Newt Functions


Updates modified portions of the screen

newt_reflow_text
newt_resize_screen
Newt Functions
PHP Manual

newt_refresh

(PECL newt >= 0.1)

newt_refresh — Updates modified portions of the screen

Description

void newt_refresh ( void )

To increase performance, newt only updates the display when it needs to, not when the program tells it to write to the terminal. Applications can force newt to immediately update modified portions of the screen by calling this function.

Return Values

No value is returned.

newt_reflow_text
newt_resize_screen
Newt Functions


newt_refresh
newt_resume
Newt Functions
PHP Manual

newt_resize_screen

(PECL newt >= 0.1)

newt_resize_screen —

Description

void newt_resize_screen ([ bool $redraw ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

redraw

Return Values

No value is returned.

newt_refresh
newt_resume
Newt Functions


Resume using the newt interface after calling newt_suspend

newt_resize_screen
newt_run_form
Newt Functions
PHP Manual

newt_resume

(PECL newt >= 0.1)

newt_resume — Resume using the newt interface after calling newt_suspend()

Description

void newt_resume ( void )

Resume using the newt interface after calling newt_suspend().

Return Values

No value is returned.

See Also

  • newt_suspend() - Tells newt to return the terminal to its initial state

newt_resize_screen
newt_run_form
Newt Functions


Runs a form

newt_resume
newt_scale_set
Newt Functions
PHP Manual

newt_run_form

(PECL newt >= 0.1)

newt_run_form — Runs a form

Description

resource newt_run_form ( resource $form )

This function runs the form passed to it.

Parameters

form

Form component

Return Values

The component which caused the form to stop running.

Note: Notice that this function doesn't fit in with newt's normal naming convention. It is an older interface which will not work for all forms. It was left in newt only for legacy applications. It is a simpler interface than the new newt_form_run() though, and is still used quite often as a result. When an application is done with a form, it destroys the form and all of the components the form contains.

See Also

  • newt_form_run() - Runs a form
  • newt_form_destroy() - Destroys a form

newt_resume
newt_scale_set
Newt Functions


newt_scale_set
newt_scrollbar_set
Newt Functions
PHP Manual

newt_scale

(PECL newt >= 0.1)

newt_scale —

Description

resource newt_scale ( int $left , int $top , int $width , int $full_value )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

width

full_value

Return Values

newt_scale_set
newt_scrollbar_set
Newt Functions


newt_run_form
newt_scale
Newt Functions
PHP Manual

newt_scale_set

(PECL newt >= 0.1)

newt_scale_set —

Description

void newt_scale_set ( resource $scale , int $amount )
Warning

This function is currently not documented; only its argument list is available.

Parameters

scale

amount

Return Values

No value is returned.

newt_run_form
newt_scale
Newt Functions


newt_scale
newt_set_help_callback
Newt Functions
PHP Manual

newt_scrollbar_set

(PECL newt >= 0.1)

newt_scrollbar_set —

Description

void newt_scrollbar_set ( resource $scrollbar , int $where , int $total )
Warning

This function is currently not documented; only its argument list is available.

Parameters

scrollbar

where

total

Return Values

No value is returned.

newt_scale
newt_set_help_callback
Newt Functions


newt_scrollbar_set
newt_set_suspend_callback
Newt Functions
PHP Manual

newt_set_help_callback

(PECL newt >= 0.1)

newt_set_help_callback —

Description

void newt_set_help_callback ( mixed $function )
Warning

This function is currently not documented; only its argument list is available.

Parameters

function

Return Values

No value is returned.

newt_scrollbar_set
newt_set_suspend_callback
Newt Functions


Set a callback function which gets invoked when user presses the suspend key

newt_set_help_callback
newt_suspend
Newt Functions
PHP Manual

newt_set_suspend_callback

(PECL newt >= 0.1)

newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key

Description

void newt_set_suspend_callback ( callback $function , mixed $data )

Set a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.

Parameters

function

A callback function, which accepts one argument: data

data

This data is been passed to the callback function

Return Values

No value is returned.

See Also

  • newt_suspend() - Tells newt to return the terminal to its initial state
  • newt_resume() - Resume using the newt interface after calling newt_suspend

newt_set_help_callback
newt_suspend
Newt Functions


Tells newt to return the terminal to its initial state

newt_set_suspend_callback
newt_textbox_get_num_lines
Newt Functions
PHP Manual

newt_suspend

(PECL newt >= 0.1)

newt_suspend — Tells newt to return the terminal to its initial state

Description

void newt_suspend ( void )

Tells newt to return the terminal to its initial state. Once this is done, the application can suspend itself (by sending itself a SIGTSTP, fork a child program, or do whatever else it likes).

Return Values

No value is returned.

See Also

  • newt_resume() - Resume using the newt interface after calling newt_suspend

newt_set_suspend_callback
newt_textbox_get_num_lines
Newt Functions


newt_textbox_set_text
newt_vertical_scrollbar
Newt Functions
PHP Manual

newt_textbox

(PECL newt >= 0.1)

newt_textbox —

Description

resource newt_textbox ( int $left , int $top , int $width , int $height [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

width

height

flags

Return Values

newt_textbox_set_text
newt_vertical_scrollbar
Newt Functions


newt_suspend
newt_textbox_reflowed
Newt Functions
PHP Manual

newt_textbox_get_num_lines

(PECL newt >= 0.1)

newt_textbox_get_num_lines —

Description

int newt_textbox_get_num_lines ( resource $textbox )
Warning

This function is currently not documented; only its argument list is available.

Parameters

textbox

Return Values

newt_suspend
newt_textbox_reflowed
Newt Functions


newt_textbox_get_num_lines
newt_textbox_set_height
Newt Functions
PHP Manual

newt_textbox_reflowed

(PECL newt >= 0.1)

newt_textbox_reflowed —

Description

resource newt_textbox_reflowed ( int $left , int $top , char $*text , int $width , int $flex_down , int $flex_up [, int $flags ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

*text

width

flex_down

flex_up

flags

Return Values

newt_textbox_get_num_lines
newt_textbox_set_height
Newt Functions


newt_textbox_reflowed
newt_textbox_set_text
Newt Functions
PHP Manual

newt_textbox_set_height

(PECL newt >= 0.1)

newt_textbox_set_height —

Description

void newt_textbox_set_height ( resource $textbox , int $height )
Warning

This function is currently not documented; only its argument list is available.

Parameters

textbox

height

Return Values

No value is returned.

newt_textbox_reflowed
newt_textbox_set_text
Newt Functions


newt_textbox_set_height
newt_textbox
Newt Functions
PHP Manual

newt_textbox_set_text

(PECL newt >= 0.1)

newt_textbox_set_text —

Description

void newt_textbox_set_text ( resource $textbox , string $text )
Warning

This function is currently not documented; only its argument list is available.

Parameters

textbox

text

Return Values

No value is returned.

newt_textbox_set_height
newt_textbox
Newt Functions


newt_textbox
newt_wait_for_key
Newt Functions
PHP Manual

newt_vertical_scrollbar

(PECL newt >= 0.1)

newt_vertical_scrollbar —

Description

resource newt_vertical_scrollbar ( int $left , int $top , int $height [, int $normal_colorset [, int $thumb_colorset ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

height

normal_colorset

thumb_colorset

Return Values

newt_textbox
newt_wait_for_key
Newt Functions


Doesn't return until a key has been pressed

newt_vertical_scrollbar
newt_win_choice
Newt Functions
PHP Manual

newt_wait_for_key

(PECL newt >= 0.1)

newt_wait_for_key — Doesn't return until a key has been pressed

Description

void newt_wait_for_key ( void )

This function doesn't return until a key has been pressed. The keystroke is then ignored. If a key is already in the terminal's buffer, this function discards a keystroke and returns immediately.

Return Values

No value is returned.

See Also

  • newt_clear_key_buffer() - Discards the contents of the terminal's input buffer without waiting for additional input

newt_vertical_scrollbar
newt_win_choice
Newt Functions


newt_wait_for_key
newt_win_entries
Newt Functions
PHP Manual

newt_win_choice

(PECL newt >= 0.1)

newt_win_choice —

Description

int newt_win_choice ( string $title , string $button1_text , string $button2_text , string $format [, mixed $args [, mixed $... ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

button1_text

button2_text

format

args

Return Values

newt_wait_for_key
newt_win_entries
Newt Functions


newt_win_choice
newt_win_menu
Newt Functions
PHP Manual

newt_win_entries

(PECL newt >= 0.1)

newt_win_entries —

Description

int newt_win_entries ( string $title , string $text , int $suggested_width , int $flex_down , int $flex_up , int $data_width , array &$items , string $button1 [, string $... ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

text

suggested_width

flex_down

flex_up

data_width

items

button1

button2

Return Values

Examples

Example #1 A newt_win_entries() example

<?php

newt_init();
newt_cls();

$entries[] = array('text' => 'First name:', 'value' => &$f_name);
$entries[] = array('text' => 'Last name:',  'value' => &$l_name);

$rc = newt_win_entries("User information", "Please enter your credentials:", 50, 7, 7, 30, $entries, "Ok", "Back");
newt_finished ();

if ($rc != 2) {
    echo "Your name is: $f_name $l_name\n";
}
?>

newt_win_choice
newt_win_menu
Newt Functions


newt_win_entries
newt_win_message
Newt Functions
PHP Manual

newt_win_menu

(PECL newt >= 0.1)

newt_win_menu —

Description

int newt_win_menu ( string $title , string $text , int $suggestedWidth , int $flexDown , int $flexUp , int $maxListHeight , array $items , int &$listItem [, string $button1 [, string $... ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

text

suggestedWidth

flexDown

flexUp

maxListHeight

items

listItem

button1

Return Values

No value is returned.

newt_win_entries
newt_win_message
Newt Functions


newt_win_menu
newt_win_messagev
Newt Functions
PHP Manual

newt_win_message

(PECL newt >= 0.1)

newt_win_message —

Description

void newt_win_message ( string $title , string $button_text , string $format [, mixed $args [, mixed $... ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

button_text

format

args

Return Values

No value is returned.

newt_win_menu
newt_win_messagev
Newt Functions


newt_win_message
newt_win_ternary
Newt Functions
PHP Manual

newt_win_messagev

(PECL newt >= 0.1)

newt_win_messagev —

Description

void newt_win_messagev ( string $title , string $button_text , string $format , array $args )
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

button_text

format

args

Return Values

No value is returned.

newt_win_message
newt_win_ternary
Newt Functions


newt_win_messagev
Ncurses
Newt Functions
PHP Manual

newt_win_ternary

(PECL newt >= 0.1)

newt_win_ternary —

Description

int newt_win_ternary ( string $title , string $button1_text , string $button2_text , string $button3_text , string $format [, mixed $args [, mixed $... ]] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

Its description

button1_text

Its description

button2_text

Its description

button3_text

Its description

format

Its description

args

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_win_messagev
Ncurses
Newt Functions


Plural version of gettext

gettext
textdomain
Gettext Functions
PHP Manual

ngettext

(PHP 4 >= 4.2.0, PHP 5)

ngettext — Plural version of gettext

Description

string ngettext ( string $msgid1 , string $msgid2 , int $n )

The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.

Parameters

msgid1

msgid2

n

Return Values

Returns correct plural form of message identified by msgid1 and msgid2 for count n .

Examples

Example #1 ngettext() example

<?php

setlocale(LC_ALL, 'cs_CZ');
printf(ngettext("%d window", "%d windows", 1), 1); // 1 okno
printf(ngettext("%d window", "%d windows", 2), 2); // 2 okna
printf(ngettext("%d window", "%d windows", 5), 5); // 5 oken

?>

gettext
textdomain
Gettext Functions


Obtain a nthmac key (needs 2 arguments)

calculhmac
signeurlpaiement
SPPLUS Functions
PHP Manual

nthmac

(PECL spplus >= 1.0.0)

nthmac — Obtain a nthmac key (needs 2 arguments)

Description

string nthmac ( string $clent , string $data )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

calculhmac
signeurlpaiement
SPPLUS Functions


Clean (erase) the output buffer

flush
ob_end_clean
Output Control Functions
PHP Manual

ob_clean

(PHP 4 >= 4.2.0, PHP 5)

ob_clean — Clean (erase) the output buffer

Description

void ob_clean ( void )

This function discards the contents of the output buffer.

This function does not destroy the output buffer like ob_end_clean() does.

Return Values

No value is returned.

See Also

  • ob_flush() - Flush (send) the output buffer
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering

flush
ob_end_clean
Output Control Functions


Clean (erase) the output buffer and turn off output buffering

ob_clean
ob_end_flush
Output Control Functions
PHP Manual

ob_end_clean

(PHP 4, PHP 5)

ob_end_clean — Clean (erase) the output buffer and turn off output buffering

Description

bool ob_end_clean ( void )

This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called.

Return Values

Returns TRUE on success or FALSE on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

Errors/Exceptions

If the function fails it generates an E_NOTICE.

Changelog

Version | Description
4.2.0 | The boolean return value was added.

Examples

The following example shows an easy way to get rid of all output buffers:

Example #1 ob_end_clean() example

<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>

See Also

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer
  • ob_flush() - Flush (send) the output buffer

ob_clean
ob_end_flush
Output Control Functions


Flush (send) the output buffer and turn off output buffering

ob_end_clean
ob_flush
Output Control Functions
PHP Manual

ob_end_flush

(PHP 4, PHP 5)

ob_end_flush — Flush (send) the output buffer and turn off output buffering

Description

bool ob_end_flush ( void )

This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called.

Note: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.

Return Values

Returns TRUE on success or FALSE on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

Errors/Exceptions

If the function fails it generates an E_NOTICE.

Changelog

Version | Description
4.2.0 | The boolean return value was added.

Examples

Example #1 ob_end_flush() example

The following example shows an easy way to flush and end all output buffers:

<?php
  while (@ob_end_flush());
?>

See Also

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer
  • ob_get_flush() - Flush the output buffer, return it as a string and turn off output buffering
  • ob_flush() - Flush (send) the output buffer
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering

ob_end_clean
ob_flush
Output Control Functions


Flush (send) the output buffer

ob_end_flush
ob_get_clean
Output Control Functions
PHP Manual

ob_flush

(PHP 4 >= 4.2.0, PHP 5)

ob_flush — Flush (send) the output buffer

Description

void ob_flush ( void )

This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.

This function does not destroy the output buffer like ob_end_flush() does.

Return Values

No value is returned.

See Also

  • ob_get_contents() - Return the contents of the output buffer
  • ob_clean() - Clean (erase) the output buffer
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering

ob_end_flush
ob_get_clean
Output Control Functions


Get current buffer contents and delete current output buffer

ob_flush
ob_get_contents
Output Control Functions
PHP Manual

ob_get_clean

(PHP 4 >= 4.3.0, PHP 5)

ob_get_clean — Get current buffer contents and delete current output buffer

Description

string ob_get_clean ( void )

Gets the current buffer contents and delete current output buffer.

ob_get_clean() essentially executes both
ob_get_contents() and
ob_end_clean().

Return Values

Returns the contents of the output buffer and end output buffering. If output buffering isn't active then FALSE is returned.

Examples

Example #1 A simple ob_get_clean() example

<?php

ob_start();

echo "Hello World";

$out = ob_get_clean();
$out = strtolower($out);

var_dump($out);
?>

The above example will output:

string(11) "hello world"

See Also

  • ob_get_contents() - Return the contents of the output buffer
  • ob_start() - Turn on output buffering

ob_flush
ob_get_contents
Output Control Functions


Return the contents of the output buffer

ob_get_clean
ob_get_flush
Output Control Functions
PHP Manual

ob_get_contents

(PHP 4, PHP 5)

ob_get_contents — Return the contents of the output buffer

Description

string ob_get_contents ( void )

Gets the contents of the output buffer without clearing it.

Return Values

This will return the contents of the output buffer or FALSE, if output buffering isn't active.

Examples

Example #1 A simple ob_get_contents() example

<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>

The above example will output:

string(6) "Hello "
string(11) "Hello World"

See Also

  • ob_start() - Turn on output buffering
  • ob_get_length() - Return the length of the output buffer

ob_get_clean
ob_get_flush
Output Control Functions


Flush the output buffer, return it as a string and turn off output buffering

ob_get_contents
ob_get_length
Output Control Functions
PHP Manual

ob_get_flush

(PHP 4 >= 4.3.0, PHP 5)

ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering

Description

string ob_get_flush ( void )

ob_get_flush() flushes the output buffer, return it as a string and turns off output buffering.

Note: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.

Return Values

Returns the output buffer or FALSE if no buffering is active.

Examples

Example #1 ob_get_flush() example

<?php
//using output_buffering=On
print_r(ob_list_handlers());

//save buffer in a file
$buffer = ob_get_flush();
file_put_contents('buffer.txt', $buffer);

print_r(ob_list_handlers());
?>

The above example will output:

Array
(
    [0] => default output handler
)
Array
(
)

See Also

  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_list_handlers() - List all output handlers in use

ob_get_contents
ob_get_length
Output Control Functions


Return the length of the output buffer

ob_get_flush
ob_get_level
Output Control Functions
PHP Manual

ob_get_length

(PHP 4 >= 4.0.2, PHP 5)

ob_get_length — Return the length of the output buffer

Description

int ob_get_length ( void )

This will return the length of the contents in the output buffer.

Return Values

Returns the length of the output buffer contents or FALSE if no buffering is active.

Examples

Example #1 A simple ob_get_length() example

<?php

ob_start();

echo "Hello ";

$len1 = ob_get_length();

echo "World";

$len2 = ob_get_length();

ob_end_clean();

echo $len1 . ", ." . $len2;
?>

The above example will output:

6, 11

See Also

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer

ob_get_flush
ob_get_level
Output Control Functions


Return the nesting level of the output buffering mechanism

ob_get_length
ob_get_status
Output Control Functions
PHP Manual

ob_get_level

(PHP 4 >= 4.2.0, PHP 5)

ob_get_level — Return the nesting level of the output buffering mechanism

Description

int ob_get_level ( void )

Returns the nesting level of the output buffering mechanism.

Return Values

Returns the level of nested output buffering handlers or zero if output buffering is not active.

See Also

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer

ob_get_length
ob_get_status
Output Control Functions


Get status of output buffers

ob_get_level
ob_gzhandler
Output Control Functions
PHP Manual

ob_get_status

(PHP 4 >= 4.2.0, PHP 5)

ob_get_status — Get status of output buffers

Description

array ob_get_status ([ bool $full_status = FALSE ] )

ob_get_status() returns status information on either the top level output buffer or all active output buffer levels if full_status is set to TRUE.

Parameters

full_status

TRUE to return all active output buffer levels. If FALSE or not set, only the top level output buffer is returned.

Return Values

If called without the full_status parameter or with full_status = FALSE a simple array with the following elements is returned:

Array
(
    [level] => 2
    [type] => 0
    [status] => 0
    [name] => URL-Rewriter
    [del] => 1
)

Simple ob_get_status() results
Key:level
Value:Output nesting level
Key:type
Value:PHP_OUTPUT_HANDLER_INTERNAL (0) or PHP_OUTPUT_HANDLER_USER (1)
Key:status
Value:One of PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1) or PHP_OUTPUT_HANDLER_END (2)
Key:name
Value:Name of active output handler or ' default output handler' if none is set
Key:del
Value:Erase-flag as set by ob_start()

If called with full_status = TRUE an array with one element for each active output buffer level is returned. The output level is used as key of the top level array and each array element itself is another array holding status information on one active output level.

Array
(
    [0] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] => 10240
            [type] => 1
            [status] => 0
            [name] => default output handler
            [del] => 1
        )

    [1] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] => 10240
            [type] => 0
            [buffer_size] => 0
            [status] => 0
            [name] => URL-Rewriter
            [del] => 1
        )

)

The full output contains these additional elements:

Full ob_get_status() results
Key:chunk_size
Value:Chunk size as set by ob_start()
Key:size
Value:...
Key:blocksize
Value:...

See Also

  • ob_get_level() - Return the nesting level of the output buffering mechanism
  • ob_list_handlers() - List all output handlers in use

ob_get_level
ob_gzhandler
Output Control Functions


ob_start callback function to gzip output buffer

ob_get_status
ob_implicit_flush
Output Control Functions
PHP Manual

ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5)

ob_gzhandler — ob_start callback function to gzip output buffer

Description

string ob_gzhandler ( string $buffer , int $mode )

ob_gzhandler() is intended to be used as a callback function for ob_start() to help facilitate sending gz-encoded data to web browsers that support compressed web pages. Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return its output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages. If a browser doesn't support compressed pages this function returns FALSE.

Parameters

buffer

mode

Return Values

Changelog

Version | Description
4.0.5 | The mode parameter was added.

Examples

Example #1 ob_gzhandler() example

<?php

ob_start("ob_gzhandler");

?>
<html>
<body>
<p>This should be a compressed page.</p>
</html>
<body>

Notes

Note: ob_gzhandler() requires the zlib extension.

Note: You cannot use both ob_gzhandler() and zlib.output_compression. Also note that using zlib.output_compression is preferred over ob_gzhandler().

See Also

  • ob_start() - Turn on output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering

ob_get_status
ob_implicit_flush
Output Control Functions


Convert character encoding as output buffer handler

iconv
intl
iconv Functions
PHP Manual

ob_iconv_handler

(PHP 4 >= 4.0.5, PHP 5)

ob_iconv_handler — Convert character encoding as output buffer handler

Description

string ob_iconv_handler ( string $contents , int $status )

Converts the string encoded in internal_encoding to output_encoding .

internal_encoding and output_encoding should be defined in the php.ini file or in iconv_set_encoding().

Parameters

See ob_start() for information about this handler parameters.

Return Values

See ob_start() for information about this handler return values.

Examples

Example #1 ob_iconv_handler() example:

<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
ob_start("ob_iconv_handler"); // start output buffering
?>

See Also

  • iconv_get_encoding() - Retrieve internal configuration variables of iconv extension
  • iconv_set_encoding() - Set current setting for character encoding conversion
  • output-control functions

iconv
intl
iconv Functions


Turn implicit flush on/off

ob_gzhandler
ob_list_handlers
Output Control Functions
PHP Manual

ob_implicit_flush

(PHP 4, PHP 5)

ob_implicit_flush — Turn implicit flush on/off

Description

void ob_implicit_flush ([ int $flag = true ] )

ob_implicit_flush() will turn implicit flushing on or off. Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.

Parameters

flag

TRUE to turn implicit flushing on, FALSE otherwise.

Return Values

No value is returned.

See Also

  • flush() - Flush the output buffer
  • ob_start() - Turn on output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering

ob_gzhandler
ob_list_handlers
Output Control Functions


List all output handlers in use

ob_implicit_flush
ob_start
Output Control Functions
PHP Manual

ob_list_handlers

(PHP 4 >= 4.3.0, PHP 5)

ob_list_handlers — List all output handlers in use

Description

array ob_list_handlers ( void )

Lists all output handlers in use.

Return Values

This will return an array with the output handlers in use (if any). If output_buffering is enabled or an anonymous function was used with ob_start(), ob_list_handlers() will return "default output handler".

Examples

Example #1 ob_list_handlers() example

<?php
//using output_buffering=On
print_r(ob_list_handlers());
ob_end_flush();

ob_start("ob_gzhandler");
print_r(ob_list_handlers());
ob_end_flush();

// anonymous functions
ob_start(create_function('$string', 'return $string;'));
print_r(ob_list_handlers());
ob_end_flush();
?>

The above example will output:

Array
(
    [0] => default output handler
)

Array
(
    [0] => ob_gzhandler
)

Array
(
    [0] => default output handler
)

See Also

  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_get_flush() - Flush the output buffer, return it as a string and turn off output buffering
  • ob_start() - Turn on output buffering

ob_implicit_flush
ob_start
Output Control Functions


Turn on output buffering

ob_list_handlers
output_add_rewrite_var
Output Control Functions
PHP Manual

ob_start

(PHP 4, PHP 5)

ob_start — Turn on output buffering

Description

bool ob_start ([ callback $output_callback [, int $chunk_size [, bool $erase ]]] )

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.

Warning

Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.

Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

Parameters

output_callback

An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when the output buffer is flushed (sent) or cleaned (with ob_flush(), ob_clean() or similar function) or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. If the output_callback is not a callable function, this function will return FALSE.

If the callback function has two parameters, the second parameter is filled with a bit-field consisting of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END.

If output_callback returns FALSE original input is sent to the browser.

The output_callback parameter may be bypassed by passing a NULL value.

ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function. You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function.

Note: In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return its output accordingly.

chunk_size

If the optional parameter chunk_size is passed, the buffer will be flushed after any output call which causes the buffer's length to equal or exceed chunk_size . Default value 0 means that the function is called only in the end, other special value 1 sets chunk_size to 4096.

erase

If the optional parameter erase is set to FALSE, the buffer will not be deleted until the script finishes. This causes that flushing and cleaning functions would issue a notice and return FALSE if called.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
6.0.0 | Value 1 is no more special.
4.3.2 | This function was changed to return FALSE in case the passed output_callback can not be executed.
4.2.0 | Added the erase parameter.

Examples

Example #1 User defined callback function example

<?php

function callback($buffer)
{
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php

ob_end_flush();

?>

The above example will output:

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

See Also

  • ob_get_contents() - Return the contents of the output buffer
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_implicit_flush() - Turn implicit flush on/off
  • ob_gzhandler() - ob_start callback function to gzip output buffer
  • ob_iconv_handler() - Convert character encoding as output buffer handler
  • mb_output_handler() - Callback function converts character encoding in output buffer
  • ob_tidyhandler() - ob_start callback function to repair the buffer

ob_list_handlers
output_add_rewrite_var
Output Control Functions


Binds PHP array to Oracle PL/SQL array by name

OCI8 Functions
oci_bind_by_name
OCI8 Functions
PHP Manual

oci_bind_array_by_name

(PHP 5 >= 5.1.2, PECL OCI8 >= 1.2.0)

oci_bind_array_by_name — Binds PHP array to Oracle PL/SQL array by name

Description

bool oci_bind_array_by_name ( resource $statement , string $name , array &$var_array , int $max_table_length [, int $max_item_length = -1 [, int $type = SQLT_AFC ]] )

Binds the PHP array var_array to the Oracle placeholder name , which points to Oracle PL/SQL array. Whether it will be used for input or output will be determined at run-time.

Parameters

statement

A valid OCI statement identifier.

name

The Oracle placeholder.

var_array

An array.

max_table_length

Sets the maximum length both for incoming and result arrays.

max_item_length

Sets maximum length for array items. If not specified or equals to -1, oci_bind_array_by_name() will use find the longest element in the incoming array and will use it as maximum length for array items.

type

Should be used to set the type of PL/SQL array items. See list of available types below:

  • SQLT_NUM - for arrays of NUMBER.

  • SQLT_INT - for arrays of INTEGER (Note: INTEGER it is actually a synonym for NUMBER(38), but SQLT_NUM type won't work in this case even though they are synonyms).

  • SQLT_FLT - for arrays of FLOAT.

  • SQLT_AFC - for arrays of CHAR.

  • SQLT_CHR - for arrays of VARCHAR2.

  • SQLT_VCS - for arrays of VARCHAR.

  • SQLT_AVC - for arrays of CHARZ.

  • SQLT_STR - for arrays of STRING.

  • SQLT_LVC - for arrays of LONG VARCHAR.

  • SQLT_ODT - for arrays of DATE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_bind_array_by_name() example

<?php

$c = oci_connect("scott", "tiger");

$create = "CREATE TABLE bind_example(name VARCHAR(20))";
$statement = oci_parse($c, $create);
oci_execute($statement);

$create_pkg = "
CREATE OR REPLACE PACKAGE ARRAYBINDPKG1 AS
  TYPE ARRTYPE IS TABLE OF VARCHAR(20) INDEX BY BINARY_INTEGER;
  PROCEDURE iobind(c1 IN OUT ARRTYPE);
END ARRAYBINDPKG1;";
$statement = oci_parse($c, $create_pkg);
oci_execute($statement);

$create_pkg_body = "
CREATE OR REPLACE PACKAGE BODY ARRAYBINDPKG1 AS
  CURSOR CUR IS SELECT name FROM bind_example;
  PROCEDURE iobind(c1 IN OUT ARRTYPE) IS
    BEGIN
    FOR i IN 1..5 LOOP
      INSERT INTO bind_example VALUES (c1(i));
    END LOOP;
    IF NOT CUR%ISOPEN THEN
      OPEN CUR;
    END IF;
    FOR i IN REVERSE 1..5 LOOP
      FETCH CUR INTO c1(i);
      IF CUR%NOTFOUND THEN
        CLOSE CUR;
        EXIT;
      END IF;
    END LOOP;
  END iobind;
END ARRAYBINDPKG1;";
$statement = oci_parse($c, $create_pkg_body);
oci_execute($statement);

$statement = oci_parse($c, "BEGIN ARRAYBINDPKG1.iobind(:c1); END;");

$array = array("one", "two", "three", "four", "five");

oci_bind_array_by_name($statement, ":c1", $array, 5, -1, SQLT_CHR);

oci_execute($statement);

var_dump($array);

?>

Notes

Note: This function is available since OCI8 release 1.2.

OCI8 Functions
oci_bind_by_name
OCI8 Functions


Binds a PHP variable to an Oracle placeholder

oci_bind_array_by_name
oci_cancel
OCI8 Functions
PHP Manual

oci_bind_by_name

(PHP 5, PECL OCI8 >= 1.1.0)

oci_bind_by_name — Binds a PHP variable to an Oracle placeholder

Description

bool oci_bind_by_name ( resource $statement , string $bv_name , mixed &$variable [, int $maxlength = -1 [, int $type = SQLT_CHR ]] )

Binds a PHP variable variable to the Oracle bind variable placeholder bv_name . Binding is important for Oracle database performance and also as a way to avoid SQL Injection security issues.

Binding allows the database to reuse the statement context and caches from previous executions of the statement, even if another user or process originally executed it. Binding reduces SQL Injection concerns because the data associated with a bind variable is never treated as part of the SQL statement. It does not need quoting or escaping.

PHP variables that have been bound can be changed and the statement re-executed without needing to re-parse the statement or re-bind.

In Oracle, bind variables are commonly divided into IN binds for values that are passed into the database, and OUT binds for values that are returned to PHP. A bind variable may be both IN and OUT. Whether a bind variable will be used for input or output is determined at run-time.

You must specify maxlength when using an OUT bind so that PHP allocates enough memory to hold the returned value.

For IN binds it is recommended to set the maxlength length if the statement is re-executed multiple times with different values for the PHP variable. Otherwise Oracle may truncate data to the length of the initial PHP variable value. If you don't know what the maximum length will be, then re-call oci_bind_by_name() with the current data size prior to each oci_execute() call. Binding an unnecessarily large length will have an impact on process memory in the database.

A bind call tells Oracle which memory address to read data from. For IN binds that address needs to contain valid data when oci_execute() is called. This means that the variable bound must remain in scope until execution. If it doesn't, unexpected results or errors such as "ORA-01460: unimplemented or unreasonable conversion requested" may occur. For OUT binds one symptom is no value being set in the PHP variable.

For a statement that is repeatedly executed, binding values that never change may reduce the ability of the Oracle optimizer to choose the best statement execution plan. Long running statements that are rarely re-executed may not benefit from binding. However in both cases, binding might be safer than joining strings into a SQL statement, as this can be a security risk if unfiltered user text is concatenated.

Parameters

statement

A valid OCI8 statement identifer.

bv_name

The colon-prefixed bind variable placeholder used in the statement. The colon is optional in bv_name . Oracle does not use question marks for placeholders.

variable

The PHP variable to be associated with bv_name

maxlength

Sets the maximum length for the data. If you set it to -1, this function will use the current length of variable to set the maximum length. In this case the variable must exist and contain data when oci_bind_by_name() is called.

type

The datatype that Oracle will treat the data as. The default type used is SQLT_CHR. Oracle will convert the data between this type and the database column (or PL/SQL variable type), when possible.

If you need to bind an abstract datatype (LOB/ROWID/BFILE) you need to allocate it first using the oci_new_descriptor() function. The length is not used for abstract datatypes and should be set to -1.

Possible values for type are:

  • SQLT_BFILEE or OCI_B_BFILE - for BFILEs;

  • SQLT_CFILEE or OCI_B_CFILEE - for CFILEs;

  • SQLT_CLOB or OCI_B_CLOB - for CLOBs;

  • SQLT_BLOB or OCI_B_BLOB - for BLOBs;

  • SQLT_RDD or OCI_B_ROWID - for ROWIDs;

  • SQLT_NTY or OCI_B_NTY - for named datatypes;

  • SQLT_INT or OCI_B_INT - for integers;

  • SQLT_CHR - for VARCHARs;

  • SQLT_BIN or OCI_B_BIN - for RAW columns;

  • SQLT_LNG - for LONG columns;

  • SQLT_LBI - for LONG RAW columns;

  • SQLT_RSET - for cursors created with oci_new_cursor().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Inserting data with oci_bind_by_name()

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, text VARCHAR2(40));

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn,"INSERT INTO mytab (id, text) VALUES(:id_bv, :text_bv)");

$id = 1;
$text = "Data to insert     ";
oci_bind_by_name($stid, ":id_bv", $id);
oci_bind_by_name($stid, ":text_bv", $text);
oci_execute($stid);

// Table now contains: 1, 'Data to insert     '

?>

Example #2 Binding once for multiple executions

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$a = array(1,3,5,7,11);  // data to insert

$stid = oci_parse($conn, 'INSERT INTO mytab (id) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $v, 20);
foreach ($a as $v) {
    $r = oci_execute($stid, OCI_DEFAULT);  // don't auto commit
}
oci_commit($conn); // commit everything at once

// Table contains five rows: 1, 3, 5, 7, 11

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Binding with a foreach() loop

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT * FROM departments WHERE department_name = :dname AND location_id = :loc';
$stid = oci_parse($conn, $sql);

$ba = array(':dname' => 'IT Support', ':loc' => 1700);

foreach ($ba as $key => $val) {

    // oci_bind_by_name($stid, $key, $val) does not work
    // because it binds each placeholder to the same location: $val
    // instead use the actual location of the data: $ba[$key]
    oci_bind_by_name($stid, $key, $ba[$key]);
}

oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
foreach ($row as $item) {
    print $item."<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Binding in a WHERE clause

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT last_name FROM employees WHERE employee_id = :eidbv';
$stid = oci_parse($conn, $sql);
$myeid = 101;
oci_bind_by_name($stid, ':eidbv', $myeid);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
echo $row['LAST_NAME'] ."<br>\n";

// Output is
//    Kochhar

oci_free_statement($stid);
oci_close($conn);

?>

Example #5 Binding with a LIKE clause

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

// Find all cities that begin with 'South'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE city LIKE :bv");
$city = 'South%';  // '%' is a wildcard in SQL
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);

foreach ($res['CITY'] as $c) {
    print $c . "<br>\n";
}
// Output is
//   South Brunswick
//   South San Francisco
//   Southlake

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 Binding with REGEXP_LIKE

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

// Find all cities that contain 'ing'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE REGEXP_LIKE(city, :bv)");
$city = '.*ing.*';
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);

foreach ($res['CITY'] as $c) {
    print $c . "<br>\n";
}
// Output is
//   Beijing
//   Singapore

oci_free_statement($stid);
oci_close($conn);

?>

For a small, fixed number of IN clause conditions, use individual bind variables. Values unknown at run time can be set to NULL. This allows a single statement to be used by all application users, maximizing Oracle DB cache efficiency.

Example #7 Binding Multiple Values in an IN Clause

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT last_name FROM employees WHERE employee_id in (:e1, :e2, :e3)';
$stid = oci_parse($conn, $sql);
$mye1 = 103;
$mye2 = 104;
$mye3 = NULL; // pretend we were not given this value
oci_bind_by_name($stid, ':e1', $mye1);
oci_bind_by_name($stid, ':e2', $mye2);
oci_bind_by_name($stid, ':e3', $mye3);
oci_execute($stid);
oci_fetch_all($stid, $res);
foreach ($res['LAST_NAME'] as $name) {
    print $name ."<br>\n";
}

// Output is
//   Ernst
//   Hunold

oci_free_statement($stid);
oci_close($conn);

?>

Example #8 Binding a ROWID returned by a query

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//   INSERT INTO mytab (id, salary, name) VALUES (1, 100, 'Chris');
//   COMMIT;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT ROWID, name FROM mytab WHERE id = :id_bv FOR UPDATE');
$id = 1;
oci_bind_by_name($stid, ':id_bv', $id);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$rid = $row['ROWID'];
$name = $row['NAME'];

// Change name to upper case & save the changes
$name = strtoupper($name);
$stid = oci_parse($conn, 'UPDATE mytab SET name = :n_bv WHERE ROWID = :r_bv');
oci_bind_by_name($stid, ':n_bv', $name);
oci_bind_by_name($stid, ':r_bv', $rid, -1, OCI_B_ROWID);
oci_execute($stid);

// The table now contains 1, 100, CHRIS

oci_free_statement($stid);
oci_close($conn);

?>

Example #9 Binding a ROWID on INSERT

<?php

// This example inserts an id & name, and then updates the salary
// Create the table with:
//   CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//
// Based on original ROWID example by thies at thieso dot net (980221)

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = "INSERT INTO mytab (id, name) VALUES(:id_bv, :name_bv)
        RETURNING ROWID INTO :rid";

$ins_stid = oci_parse($conn, $sql);

$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_bind_by_name($ins_stid, ":id_bv",   $id,    10);
oci_bind_by_name($ins_stid, ":name_bv", $name,  32);
oci_bind_by_name($ins_stid, ":rid",     $rowid, -1, OCI_B_ROWID);

$sql = "UPDATE mytab SET salary = :salary WHERE ROWID = :rid";
$upd_stid = oci_parse($conn, $sql);
oci_bind_by_name($upd_stid, ":rid", $rowid, -1, OCI_B_ROWID);
oci_bind_by_name($upd_stid, ":salary", $salary,   32);

// ids and names to insert
$data = array(1111 => "Larry",
              2222 => "Bill",
              3333 => "Jim");

// Salary of each person
$salary = 10000;

// Insert and immediately update each row
foreach ($data as $id => $name) {
    oci_execute($ins_stid);
    oci_execute($upd_stid);
}

$rowid->free();
oci_free_statement($upd_stid);
oci_free_statement($ins_stid);

// Show the new rows
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    var_dump($row);
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #10 Binding for a PL/SQL stored function

<?php

//  Before running the PHP program, create a stored function in
//  SQL*Plus or SQL Developer:
//
//  CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
//  BEGIN
//      RETURN p * 3;
//  END;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$p = 8;

$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);

// The return value is an OUT bind. The default type will be a string
// type so binding a length 40 means that at most 40 digits will be
// returned.
oci_bind_by_name($stid, ':r', $r, 40);

oci_execute($stid);

print "$r\n";   // prints 24

oci_free_statement($stid);
oci_close($conn);

?>

Example #11 Binding parameters for a PL/SQL stored procedure

<?php

//  Before running the PHP program, create a stored procedure in
//  SQL*Plus or SQL Developer:
//
//  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
//  BEGIN
//      p2 := p1 * 2;
//  END;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$p1 = 8;

$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);

// The second procedure parameter is an OUT bind. The default type
// will be a string type so binding a length 40 means that at most 40
// digits will be returned.
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Example #12 Binding a CLOB column

<?php

// Before running, create the table:
//     CREATE TABLE mytab (mykey NUMBER, myclob CLOB);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$mykey = 12343;  // arbitrary key for this example;

$sql = "INSERT INTO mytab (mykey, myclob)
        VALUES (:mykey, EMPTY_CLOB())
        RETURNING myclob INTO :myclob";

$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_DEFAULT);
$clob->save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query = 'SELECT myclob FROM mytab WHERE mykey = :mykey';

$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);

print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC)) {
  $result = $row['MYCLOB']->load();
  print '<tr><td>'.$result.'</td></tr>';
}
print '</table>';

?>

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

Do not use magic_quotes_gpc or addslashes() and oci_bind_by_name() simultaneously as no quoting is needed. Any magically applied quotes will be written into your database because oci_bind_by_name() inserts data verbatim and does not remove quotes or escape characters.

Note: If you bind a string to a CHAR column in a WHERE clause, remember that Oracle uses blank-padded comparison semantics for CHAR columns. Your PHP variable should be blank padded to the same width as the column for the WHERE clause to succeed.

Note: The PHP variable argument is a reference. Some forms of loops do not work as expected:

foreach ($myarray as $key => $value)  {
    oci_bind_by_name($stid, $key, $value);
}

This binds each key to the location of $value, so all bound variables end up pointing to the last loop iteration's value. Instead use the following:

foreach ($myarray as $key => $value) {
    oci_bind_by_name($stid, $key, $myarray[$key]);
}

Note: In PHP versions before 5.0.0 you must use ocibindbyname() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_bind_array_by_name() - Binds PHP array to Oracle PL/SQL array by name
  • oci_parse() - Prepares an Oracle statement for execution

oci_bind_array_by_name
oci_cancel
OCI8 Functions


Cancels reading from cursor

oci_bind_by_name
oci_close
OCI8 Functions
PHP Manual

oci_cancel

(PHP 5, PECL OCI8 >= 1.1.0)

oci_cancel — Cancels reading from cursor

Description

bool oci_cancel ( resource $statement )

Invalidates a cursor, freeing all associated resources and cancels the ability to read from it.

Parameters

statement

An OCI statement.

Return Values

Returns TRUE on success or FALSE on failure.

oci_bind_by_name
oci_close
OCI8 Functions


Closes an Oracle connection

oci_cancel
OCI-Collection->append
OCI8 Functions
PHP Manual

oci_close

(PHP 5, PECL OCI8 >= 1.1.0)

oci_close — Closes an Oracle connection

Description

bool oci_close ( resource $connection )

Unsets connection . The underlying database connection is closed if no other resources are using it and if it was created with oci_connect() or oci_new_connect().

It is recommended to close connections that are no longer needed because this makes database resources available for other users.

Parameters

connection

An Oracle connection identifier returned by oci_connect(), oci_pconnect(), or oci_new_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a connection

Resources associated with a connection should be closed to ensure the underlying database connection is properly terminated and the database resources are released.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM departments');
$r = oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);

// Free the statement identifier when closing the connection
oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Database connections are not closed until all references are closed

The internal refcount of a connection identifier must be zero before the underlying connection to the database is closed.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM departments');  // this increases the refcount on $conn
oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);

oci_close($conn);

// $conn is no long usable in the script but the underlying database
// connection is still held open until $stid is freed.
var_dump($conn);  // prints NULL

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user is still connected.
sleep(10);

// When $stid is freed, the database connection is physically closed
oci_free_statement($stid);

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user has disconnected.
sleep(10);

?>

Example #3 Closing a connection opened more than once

When database credentials are reused, both connections must be closed before the underlying database connection is closed.

<?php

$conn1 = oci_connect('hr', 'welcome', 'localhost/XE');

// Using the same credentials reuses the same underlying database connection
// Any uncommitted changes done on $conn1 will be visible in $conn2
$conn2 = oci_connect('hr', 'welcome', 'localhost/XE');

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that only one database user is connected.
sleep(10);

oci_close($conn1); // doesn't close the underlying database connection
var_dump($conn1);  // prints NULL because the variable $conn1 is no longer usable
var_dump($conn2);  // displays that $conn2 is still a valid connection resource

?>

Example #4 Connections are closed when variables go out of scope

When all variables referencing a connection go out of scope and are freed by PHP, a rollback occurs (if necessary) and the underlying connection to the database is closed.

<?php

function myfunc() {
    $conn = oci_connect('hr', 'hrpwd', 'localhost/XE');
    if (!$conn) {
        $e = oci_error();
        trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    }

    $stid = oci_parse($conn, 'UPDATE mytab SET id = 100');
    oci_execute($stid, OCI_NO_AUTO_COMMIT);
    return "Finished";
}

$r = myfunc();
// At this point a rollback occurred and the underlying database connection was released.

print $r;  // displays the function return value "Finished"

?>

Notes

Note: Variables that have a dependency on the connection identifier, such as statement identifiers returned by oci_parse(), must also be freed before the underlying database connection is closed.

Note: Prior to version PHP 5.1.2 (PECL OCI8 1.1) oci_close() was a no-op. In more recent versions it correctly closes the Oracle connection. Use oci8.old_oci_close_semantics option to restore old behavior of this function.

Note: The oci_close() function does not close the underlying database connections created with oci_pconnect().

Note: In PHP versions before 5.0.0 you must use ocilogoff() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_connect() - Connect to an Oracle database
  • oci_free_statement() - Frees all resources associated with statement or cursor

oci_cancel
OCI-Collection->append
OCI8 Functions


Appends element to the collection

oci_close
OCI-Collection->assign
OCI8 Functions
PHP Manual

OCI-Collection->append

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection->append — Appends element to the collection

Description

OCI-Collection
bool append ( mixed $value )

Appends element to the end of the collection.

Parameters

value

The value to be added to the collection. Can be a string or a number.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Collection->assign

oci_close
OCI-Collection->assign
OCI8 Functions


Assigns a value to the collection from another existing collection

OCI-Collection->append
OCI-Collection->assignElem
OCI8 Functions
PHP Manual

OCI-Collection->assign

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection->assign — Assigns a value to the collection from another existing collection

Description

OCI-Collection
bool assign ( OCI-Collection $from )

Assigns a value to the collection from another, previously created collection. Both collections must be created with oci_new_collection() prior to using them.

Parameters

from

An instance of OCI-Collection.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Collection->append

OCI-Collection->append
OCI-Collection->assignElem
OCI8 Functions


Assigns a value to the element of the collection

OCI-Collection->assign
OCI-Collection->free
OCI8 Functions
PHP Manual

OCI-Collection->assignElem

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection->assignElem — Assigns a value to the element of the collection

Description

OCI-Collection
bool assignElem ( int $index , mixed $value )

Assigns a value to the element with index index .

Parameters

index

The element index. First index is 1.

value

Can be a string or a number.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Collection->getElem

OCI-Collection->assign
OCI-Collection->free
OCI8 Functions


Returns value of the element

OCI-Collection->free
OCI-Collection->max
OCI8 Functions
PHP Manual

OCI-Collection->getElem

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection->getElem — Returns value of the element

Description

OCI-Collection
mixed getElem ( int $index )

Returns element's value with the index index (1-based).

Parameters

index

The element index. First index is 1.

Return Values

Returns FALSE if such element doesn't exist; NULL if element is NULL; string if element is column of a string datatype or number if element is numeric field.

See Also

  • OCI-Collection->assignElem

OCI-Collection->free
OCI-Collection->max
OCI8 Functions


Frees the resources associated with the collection object

OCI-Collection->assignElem
OCI-Collection->getElem
OCI8 Functions
PHP Manual

OCI-Collection->free

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection->free — Frees the resources associated with the collection object

Description

OCI-Collection
bool free ( void )

Frees the resources associated with the collection object.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • oci_new_collection

OCI-Collection->assignElem
OCI-Collection->getElem
OCI8 Functions


Returns the maximum number of elements in the collection

OCI-Collection->getElem
OCI-Collection->size
OCI8 Functions
PHP Manual

OCI-Collection->max

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection->max — Returns the maximum number of elements in the collection

Description

OCI-Collection
int max ( void )

Returns the maximum number of elements in the collection.

Return Values

Returns the maximum number as an integer, or FALSE on errors.

If the returned value is 0, then the number of elements is not limited.

See Also

  • OCI-Collection->size

OCI-Collection->getElem
OCI-Collection->size
OCI8 Functions


Returns size of the collection

OCI-Collection->max
OCI-Collection->trim
OCI8 Functions
PHP Manual

OCI-Collection->size

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection->size — Returns size of the collection

Description

OCI-Collection
int size ( void )

Returns the size of the collection.

Return Values

Returns the number of elements in the collection or FALSE on error.

See Also

  • OCI-Collection->max

OCI-Collection->max
OCI-Collection->trim
OCI8 Functions


Trims elements from the end of the collection

OCI-Collection->size
oci_commit
OCI8 Functions
PHP Manual

OCI-Collection->trim

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection->trim — Trims elements from the end of the collection

Description

OCI-Collection
bool trim ( int $num )

Trims num of elements from the end of the collection.

Parameters

num

The number of elements to be trimmed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Collection->size

OCI-Collection->size
oci_commit
OCI8 Functions


Commits the outstanding database transaction

OCI-Collection->trim
oci_connect
OCI8 Functions
PHP Manual

oci_commit

(PHP 5, PECL OCI8 >= 1.1.0)

oci_commit — Commits the outstanding database transaction

Description

bool oci_commit ( resource $connection )

Commits the outstanding transaction for the Oracle connection . A commit ends the current transaction and makes permanent all changes. It releases all locks held.

A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. Further data changes made by other statements become part of the same transaction. Data changes made in a transaction are temporary until the transaction is committed or rolled back. Other users of the database will not see the changes until they are committed.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_commit() example

<?php

// Insert into several tables, rolling back the changes if an error occurs

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");

// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1.  The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    oci_rollback($conn);  // rollback changes to both tables
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

// Commit the changes to both tables
$r = oci_commit($conn);
if (!r) {
    $e = oci_error($conn);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

?>

Notes

Note: Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction.
Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.
Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

Note: In PHP versions before 5.0.0 you must use ocicommit() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_execute() - Executes a statement
  • oci_rollback() - Rolls back the outstanding database transaction

OCI-Collection->trim
oci_connect
OCI8 Functions


Connect to an Oracle database

oci_commit
oci_define_by_name
OCI8 Functions
PHP Manual

oci_connect

(PHP 5, PECL OCI8 >= 1.1.0)

oci_connect — Connect to an Oracle database

Description

resource oci_connect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] )

Returns a connection identifier needed for most other OCI8 operations.

See Connection Handling for general information on connection management and connection pooling.

From PHP 5.1.2 (PECL OCI8 1.1) oci_close() can be used to close the connection.

The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call. This means that transactions in one handle are also in the other handles, because they use the same underlying database connection. If two handles need to be transactionally isolated from each other, use oci_new_connect() instead.

Parameters

username

The Oracle user name.

password

The password for username .

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. With Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce connection time.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Return Values

Returns a connection identifier or FALSE on error.

Examples

Example #1 Basic oci_connect() using Easy Connect syntax

<?php

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Example #2 Basic oci_connect() using a Network Connect name

<?php

// Connects to the MYDB database described in tnsnames.ora file,
// One example tnsnames.ora entry for MYDB could be:
//   MYDB =
//     (DESCRIPTION =
//       (ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.oracle.com)(PORT = 1521))
//       (CONNECT_DATA =
//         (SERVER = DEDICATED)
//         (SERVICE_NAME = XE)
//       )
//     )

$conn = oci_connect('hr', 'welcome', 'MYDB');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Example #3 oci_connect() with an explicit character set

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE', 'AL32UTF8');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Example #4 Using multiple calls to oci_connect()

<?php

$c1 = oci_connect("hr", "welcome", 'localhost/XE');
$c2 = oci_connect("hr", "welcome", 'localhost/XE');

// Both $c1 and $c2 show the same PHP resource id meaning they use the
// same underlying database connection
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";

function create_table($conn)
{
    $stmt = oci_parse($conn, "create table hallo (test varchar2(64))");
    oci_execute($stmt);
    echo "Created table<br>\n";
}

function drop_table($conn)
{
    $stmt = oci_parse($conn, "drop table hallo");
    oci_execute($stmt);
    echo "Dropped table<br>\n";
}

function insert_data($connname, $conn)
{
    $stmt = oci_parse($conn, "insert into hallo
              values(to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
    oci_execute($stmt, OCI_DEFAULT);
    echo "$connname inserted row without committing<br>\n";
}

function rollback($connname, $conn)
{
    oci_rollback($conn);
    echo "$connname rollback<br>\n";
}

function select_data($connname, $conn)
{
    $stmt = oci_parse($conn, "select * from hallo");
    oci_execute($stmt, OCI_DEFAULT);
    echo "$connname ----selecting<br>\n";
    while (oci_fetch($stmt)) {
        echo "    " . oci_result($stmt, "TEST") . "<br>\n";
    }
    echo "$connname ----done<br>\n";
}

create_table($c1);

insert_data('c1', $c1);   // Insert a row using c1
sleep(2);                 // sleep to show a different timestamp for the 2nd row
insert_data('c2', $c2);   // Insert a row using c2

select_data('c1', $c1);   // Results of both inserts are returned
select_data('c2', $c2);   // Results of both inserts are returned

rollback('c1', $c1);      // Rollback using c1

select_data('c1', $c1);   // Both inserts have been rolled back
select_data('c2', $c2);

drop_table($c1);

// Closing one of the connections makes the PHP variable unusable, but
// the other could be used
oci_close($c1);
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";

// Output is:
//    c1 is Resource id #5
//    c2 is Resource id #5
//    Created table
//    c1 inserted row without committing
//    c2 inserted row without committing
//    c1 ----selecting
//        09-DEC-09 12:14:43
//        09-DEC-09 12:14:45
//    c1 ----done
//    c2 ----selecting
//        09-DEC-09 12:14:43
//        09-DEC-09 12:14:45
//    c2 ----done
//    c1 rollback
//    c1 ----selecting
//    c1 ----done
//    c2 ----selecting
//    c2 ----done
//    Dropped table
//    c1 is
//    c2 is Resource id #5

?>

Notes

Note: An incorrectly installed or configured OCI8 extension will often manifest itself as a connection problem or error. See Installing/Configuring for troubleshooting information.

Note: In PHP versions before 5.0.0 use ocilogon() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_pconnect() - Connect to an Oracle database using a persistent connection
  • oci_new_connect() - Connect to the Oracle server using a unique connection
  • oci_close() - Closes an Oracle connection

oci_commit
oci_define_by_name
OCI8 Functions


Associates a PHP variable with a column for query fetches

oci_connect
oci_error
OCI8 Functions
PHP Manual

oci_define_by_name

(PHP 5, PECL OCI8 >= 1.1.0)

oci_define_by_name — Associates a PHP variable with a column for query fetches

Description

bool oci_define_by_name ( resource $statement , string $column_name , mixed &$variable [, int $type = SQLT_CHR ] )

Associates a PHP variable with a column for query fetches using oci_fetch().

The oci_define_by_name() call must occur before executing oci_execute().

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

column_name

The column name used in the query.

Use uppercase for Oracle's default, non-case sensitive column names. Use the exact column name case for case-sensitive column names.

variable

The PHP variable that will contain the returned column value.

type

The data type to be returned. Generally not needed. Note that Oracle-style data conversions are not performed. For example, SQLT_INT will be ignored and the returned data type will still be SQLT_CHR.

You can optionally use oci_new_descriptor() to allocate LOB/ROWID/BFILE descriptors.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_define_by_name() example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);

// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);

oci_execute($stid);

// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
    echo "Location id $locid is $city<br>\n";
}

// Displays:
//   Location id 1000 is Roma
//   Location id 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_define_by_name() with case sensitive column names

<?php

/*
  Before running, create the table with a case sensitive column name:
    CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
    INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// Use uppercase for non case-sensitive column names
oci_define_by_name($stid, 'ID', $id);

// Use the exact case for case-sensitive column names
oci_define_by_name($stid, 'MyDescription', $mydesc);

oci_execute($stid);

while (oci_fetch($stid)) {
    echo "id $id is $mydesc<br>\n";
}

// Displays:
//   id 1 is Iced Coffee

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_define_by_name() with LOB columns

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, fruit CLOB);
    INSERT INTO mytab (id, fruit) values (1, 'apple');
    INSERT INTO mytab (id, fruit) values (2, 'orange');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);
oci_define_by_name($stid, 'FRUIT', $fruit);  // $fruit will become a LOB descriptor

oci_execute($stid);

while (oci_fetch($stid)) {
    echo $id . " is " . $fruit->load(100) . "<br>\n";
}

// Displays:
//   1 is apple
//   2 is orange

$fruit->free();
oci_free_statement($stid);
oci_close($conn);

?>

Example #4 oci_define_by_name() with an explicit type

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, fruit CLOB);
    INSERT INTO mytab (id, fruit) values (1, 'apple');
    INSERT INTO mytab (id, fruit) values (2, 'orange');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);

$fruit = oci_new_descriptor($conn, OCI_D_LOB);
oci_define_by_name($stid, 'FRUIT', $fruit, OCI_D_CLOB);

oci_execute($stid);

while (oci_fetch($stid)) {
    echo $id . " is " . $fruit->load(100) . "<br>\n";
}

// Displays:
//   1 is apple
//   2 is orange

$fruit->free();
oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note: In PHP versions before 5.0.0 use ocidefinebyname() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_new_descriptor() - Initializes a new empty LOB or FILE descriptor

oci_connect
oci_error
OCI8 Functions


Returns the last error found

oci_define_by_name
oci_execute
OCI8 Functions
PHP Manual

oci_error

(PHP 5, PECL OCI8 >= 1.1.0)

oci_error — Returns the last error found

Description

array oci_error ([ resource $resource ] )

Returns the last error found.

The function should be called immediately after an error occurs. Errors are cleared by a successful statement.

Parameters

resource

For most errors, resource is the resource handle that was passed to the failing function call. For connection errors with oci_connect(), oci_new_connect() or oci_pconnect() do not pass resource .

Return Values

If no error is found, oci_error() returns FALSE. Otherwise, oci_error() returns the error information as an associative array.

oci_error() Array Description
Array key | Type | Description
code | integer | The Oracle error number.
message | string | The Oracle error text.
offset | integer | The byte position of an error in the SQL statement. If there was no statement, this is 0
sqltext | string | The SQL statement text. If there was no statement, this is an empty string.

Changelog

Version | Description
PHP 4.3 | The offset and sqltext entries were added.

Examples

Example #1 Displaying the Oracle error message after a connection error

$conn = oci_connect("hr", "welcome", "localhost/XE");
if (!$conn) {
    $e = oci_error();   // For oci_connect errors do not pass a handle
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

Example #2 Displaying the Oracle error message after a parsing error

$stid = oci_parse($conn, "select ' from dual");  // note mismatched quote
if (!$stid) {
    $e = oci_error($conn);  // For oci_parse errors pass the connection handle
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

Example #3 Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error

$r = oci_execute($stid);
if (!$r) {
    $e = oci_error($stid);  // For oci_execute errors pass the statement handle
    print htmlentities($e['message']);
    print "\n<pre>\n";
    print htmlentities($e['sqltext']);
    printf("\n%".($e['offset']+1)."s", "^");
    print  "\n</pre>\n";
}

Notes

Note: In PHP versions before 5.0.0 you must use ocierror() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

oci_define_by_name
oci_execute
OCI8 Functions


Executes a statement

oci_error
oci_fetch_all
OCI8 Functions
PHP Manual

oci_execute

(PHP 5, PECL OCI8 >= 1.1.0)

oci_execute — Executes a statement

Description

bool oci_execute ( resource $statement [, int $mode = OCI_COMMIT_ON_SUCCESS ] )

Executes a statement previously returned from oci_parse().

After execution, statements like INSERT will have data committed to the database by default. For statements like SELECT, execution performs the logic of the query. Query results can subsequently be fetched in PHP with functions like oci_fetch_array().

Each parsed statement may be executed multiple times, saving the cost of re-parsing. This is commonly used for INSERT statements when data is bound with oci_bind_by_name().

Parameters

statement

A valid OCI statement identifier.

mode

An optional second parameter can be one of the following constants:

Execution Modes
Constant | Description
OCI_COMMIT_ON_SUCCESS | Automatically commit all outstanding changes for this connection when the statement has succeeded. This is the default.
OCI_DEFAULT | Obsolete as of PHP 5.3.2 (PECL OCI8 1.4) but still available for backward compatibility. Use the equivalent OCI_NO_AUTO_COMMIT in new code.
OCI_DESCRIBE_ONLY | Make query meta data available to functions like oci_field_name() but do not create a result set. Any subsequent fetch call such as oci_fetch_array() will fail.
OCI_NO_AUTO_COMMIT | Do not automatically commit changes. Prior to PHP 5.3.2 (PECL OCI8 1.4) use OCI_DEFAULT which is an alias for OCI_NO_AUTO_COMMIT.

Using OCI_NO_AUTO_COMMIT mode starts a transaction. Transactions are automatically rolled back when the connection is closed, or when the script ends. Explicitly call oci_commit() to commit a transaction, or oci_rollback() to abort it.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

If OCI_NO_AUTO_COMMIT mode is used for any statement including queries, and oci_commit() or oci_rollback() is not subsequently called, then OCI8 will perform a rollback at the end of the script even if no data was changed. To avoid an unnecessary rollback, many scripts do not use OCI_NO_AUTO_COMMIT mode for queries or PL/SQL. Be careful to ensure the appropriate transactional consistency for the application when using oci_execute() with different modes in the same script.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_execute() for queries

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Example #2 oci_execute() without specifying a mode example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');

oci_execute($stid); // The row is committed and immediately visible to other users

?>

Example #3 oci_execute() with OCI_NO_AUTO_COMMIT example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $i, 10);
for ($i = 1; $i <= 5; ++$i) {
    oci_execute($stid, OCI_NO_AUTO_COMMIT);  // use OCI_DEFAULT for PHP <= 5.3.1
}
oci_commit($conn);  // commits all new values: 1, 2, 3, 4, 5

?>

Example #4 oci_execute() with different commit modes example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');
oci_execute($stid, OCI_NO_AUTO_COMMIT);  // data not committed

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (456)');
oci_execute($stid);  // commits both 123 and 456 values

?>

Example #5 oci_execute() with OCI_DESCRIBE_ONLY example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM locations');
oci_execute($s, OCI_DESCRIBE_ONLY);
for ($i = 1; $i <= oci_num_fields($stid); ++$i) {
    echo oci_field_name($stid, $i) . "<br>\n";
}

?>

Notes

Note: Transactions are automatically rolled back when connections are closed, or when the script ends, whichever is soonest. Explicitly call oci_commit() to commit a transaction.
Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.
Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

Note: Because the oci_execute() function generally sends the statement to the database, oci_execute() can identify some statement syntax errors that the lightweight, local oci_parse() function does not.

Note: In PHP versions before 5.0.0 use ociexecute() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_parse() - Prepares an Oracle statement for execution

oci_error
oci_fetch_all
OCI8 Functions


Fetches the next row from a query into internal buffers

oci_fetch_row
oci_field_is_null
OCI8 Functions
PHP Manual

oci_fetch

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch — Fetches the next row from a query into internal buffers

Description

bool oci_fetch ( resource $statement )

Fetches the next row from a query into internal buffers accessible either with oci_result(), or by using variables previously defined with oci_define_by_name().

See oci_fetch_array() for general information about fetching data.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns TRUE on success or FALSE if there are no more rows in the statement .

Examples

Example #1 oci_fetch() with defined variables

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);

// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);

oci_execute($stid);

// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
    echo "Location id $locid is $city<br>\n";
}

// Displays:
//   Location id 1000 is Roma
//   Location id 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch() with oci_result()

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
oci_execute($stid);

while (oci_fetch($stid)) {
    echo oci_result($stid, 'LOCATION_ID') . " is ";
    echo oci_result($stid, 'CITY') . "<br>\n";
}

// Displays:
//   1000 is Roma
//   1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note: In PHP versions before 5.0.0 use ocifetch() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_define_by_name() - Associates a PHP variable with a column for query fetches
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_result() - Returns field's value from the fetched row

oci_fetch_row
oci_field_is_null
OCI8 Functions


Fetches multiple rows from a query into a two-dimensional array

oci_execute
oci_fetch_array
OCI8 Functions
PHP Manual

oci_fetch_all

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array

Description

int oci_fetch_all ( resource $statement , array &$output [, int $skip = 0 [, int $maxrows = -1 [, int $flags = OCI_FETCHSTATEMENT_BY_COLUMN + OCI_ASSOC ]]] )

Fetches multiple rows from a query into a two-dimensional array. By default, all rows are returned.

This function can be called only once for each query executed with oci_execute().

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

output

The variable to contain the returned rows.

LOB columns are returned as strings, where Oracle supports conversion.

See oci_fetch_array() for more information on how data and types are fetched.

skip

The number of initial rows to discard when fetching the result. The default value is 0, so the first row onwards is returned.

maxrows

The number of rows to return. The default is -1 meaning return all the rows from skip + 1 onwards.

flags

Parameter flags indicates the array structure and whether associative arrays should be used.

oci_fetch_all() Array Structure Modes
Constant | Description
OCI_FETCHSTATEMENT_BY_ROW | The outer array will contain one sub-array per query row.
OCI_FETCHSTATEMENT_BY_COLUMN | The outer array will contain one sub-array per query column. This is the default.

Arrays can be indexed by column heading or numerically.

oci_fetch_all() Array Index Modes
Constant | Description
OCI_NUM | Numeric indexes are used for each column's array.
OCI_ASSOC | Associative indexes are used for each column's array. This is the default.

Use the addition operator "+" to choose a combination of array structure and index modes.

Oracle's default, non-case sensitive column names will have uppercase array keys. Case-sensitive column names will have array keys using the exact column case. Use var_dump() on output to verify the appropriate case to use for each query.

Queries that have more than one column with the same name should use column aliases. Otherwise only one of the columns will appear in an associative array.

Return Values

Returns the number of rows in output , which may be 0 or more, or FALSE on failure.

Examples

Example #1 oci_fetch_all() example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// var_dump output is:
//    2 rows fetched
//    array(2) {
//      ["POSTAL_CODE"]=>
//      array(2) {
//        [0]=>
//        string(6) "00989x"
//        [1]=>
//        string(6) "10934x"
//      }
//      ["CITY"]=>
//      array(2) {
//        [0]=>
//        string(4) "Roma"
//        [1]=>
//        string(6) "Venice"
//      }
//    }

// Pretty-print the results
echo "<table border='1'>\n";
foreach ($res as $col) {
    echo "<tr>\n";
    foreach ($col as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_all() example with OCI_FETCHSTATEMENT_BY_ROW

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// Output is:
//    2 rows fetched
//    array(2) {
//      [0]=>
//      array(2) {
//        ["POSTAL_CODE"]=>
//        string(6) "00989x"
//        ["CITY"]=>
//        string(4) "Roma"
//      }
//      [1]=>
//      array(2) {
//        ["POSTAL_CODE"]=>
//        string(6) "10934x"
//        ["CITY"]=>
//        string(6) "Venice"
//      }
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_all() with OCI_NUM

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW + OCI_NUM);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// Output is:
//    2 rows fetched
//    array(2) {
//      [0]=>
//      array(2) {
//        [0]=>
//        string(6) "00989x"
//        [1]=>
//        string(4) "Roma"
//      }
//      [1]=>
//      array(2) {
//        [0]=>
//        string(6) "10934x"
//        [1]=>
//        string(6) "Venice"
//      }
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note: Using skip is very inefficient. All the rows to be skipped are included in the result set that is returned from the database to PHP. They are then discarded. It is more efficient to use SQL to restrict the offset and range of rows in the query. See oci_fetch_array() for an example.

Note: Queries that return a large number of rows can be more memory efficient if a single-row fetching function like oci_fetch_array() is used.

Note: For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

Note: In PHP versions before 5.0.0 you must use ocifetchstatement() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_set_prefetch() - Sets number of rows to be prefetched by queries

oci_execute
oci_fetch_array
OCI8 Functions


Returns the next row from a query as an associative or numeric array

oci_fetch_all
oci_fetch_assoc
OCI8 Functions
PHP Manual

oci_fetch_array

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_array — Returns the next row from a query as an associative or numeric array

Description

array oci_fetch_array ( resource $statement [, int $mode ] )

Returns an array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

mode

An optional second parameter can be any combination of the following constants:

oci_fetch_array() Modes
Constant | Description
OCI_BOTH | Returns an array with both associative and numeric indices. This is the same as OCI_ASSOC + OCI_NUM and is the default behavior.
OCI_ASSOC | Returns an associative array.
OCI_NUM | Returns a numeric array.
OCI_RETURN_NULLS | Creates elements for NULL fields. The element values will be a PHP NULL.
OCI_RETURN_LOBS | Returns the contents of LOBs instead of the LOB descriptors.

The default mode is OCI_BOTH.

Use the addition operator "+" to specify more than one mode at a time.

Return Values

Returns an array with associative and/or numeric indices. If there are no more rows in the statement then FALSE is returned.

By default, LOB columns are returned as LOB descriptors.

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

Oracle's default, non-case sensitive column names will have uppercase associative indices in the result array. Case-sensitive column names will have array indices using the exact column case. Use var_dump() on the result array to verify the appropriate case to use for each query.

Examples

Example #1 oci_fetch_array() with OCI_BOTH

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_BOTH))) {
    // Use the uppercase column names for the associative array indices
    echo $row[0] . " and " . $row['DEPARTMENT_ID']   . " are the same<br>\n";
    echo $row[1] . " and " . $row['DEPARTMENT_NAME'] . " are the same<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_array() with OCI_NUM

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_NUM))) {
    echo $row[0] . "<br>\n";
    echo $row[1]->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_array() with OCI_ASSOC

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
    echo $row['ID'] . "<br>\n";
    echo $row['DESCRIPTION']->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 oci_fetch_array() with OCI_RETURN_NULLS

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC))) { // Ignore NULLs
    var_dump($row);
}

/*
The above code prints:
  array(1) {
    [1]=>
    string(1) "1"
  }
*/

$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC+OCI_RETURN_NULLS))) { // Fetch NULLs
    var_dump($row);
}

/*
The above code prints:
  array(2) {
    [1]=>
    string(1) "1"
    ["NULL"]=>
    NULL
  }
*/

?>

Example #5 oci_fetch_array() with OCI_RETURN_LOBS

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS))) {
    echo $row['ID'] . "<br>\n";
    echo $row['DESCRIPTION'] . "<br>\n"; // this contains all of DESCRIPTION
}

// Output is:
//    1
//    A very long string

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 oci_fetch_array() with case sensitive column names

<?php

/*
   Before running, create the table:
      CREATE TABLE mytab ("Name" VARCHAR2(20), city VARCHAR2(20));
      INSERT INTO mytab ("Name", city) values ('Chris', 'Melbourne');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);

// Because 'Name' was created as a case-sensitive column, that same
// case is used for the array index.  However uppercase 'CITY' must
// be used for the case-insensitive column index
print $row['Name'] . "<br>\n";   //  prints Chris
print $row['CITY'] . "<br>\n";   //  prints Melbourne

oci_free_statement($stid);
oci_close($conn);

?>

Example #7 oci_fetch_array() with columns having duplicate names

<?php

/*
  Before running, create the tables:
      CREATE TABLE mycity (id NUMBER, name VARCHAR2(20));
      INSERT INTO mycity (id, name) values (1, 'Melbourne');
      CREATE TABLE mycountry (id NUMBER, name VARCHAR2(20));
      INSERT INTO mycountry (id, name) values (1, 'Australia');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT mycity.name, mycountry.name
        FROM mycity, mycountry
        WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);

// Output only contains one "NAME" entry:
//    array(1) {
//      ["NAME"]=>
//      string(9) "Australia"
//    }

// To query a repeated column name, use a SQL column alias like "AS ctnm":
$sql = 'SELECT mycity.name AS ctnm, mycountry.name
        FROM mycity, mycountry
        WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);

// Output now contains both columns selected:
//    array(2) {
//      ["CTNM"]=>
//      string(9) "Melbourne"
//      ["NAME"]=>
//      string(9) "Australia"
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Example #8 oci_fetch_array() with DATE columns

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Set the date format for this connection.
// For performance reasons, consider changing the format
// in a trigger or with environment variables instead
$stid = oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
oci_execute($stid);

$stid = oci_parse($conn, 'SELECT hire_date FROM employees WHERE employee_id = 188');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
echo $row['HIRE_DATE'] . "<br>\n";  // prints 1997-06-14

oci_free_statement($stid);
oci_close($conn);

?>

Example #9 oci_fetch_array() with REF CURSOR

<?php
/*
  Create the PL/SQL stored procedure as:

  CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
  BEGIN
    OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
  END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Execute the returned REF CURSOR and fetch from it like a statement identifier
oci_execute($refcur);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);

?>

Example #10 oci_fetch_array() with a LIMIT-like query

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// This is the query you want to execute
$sql = 'SELECT city, postal_code FROM locations ORDER BY city';

// This nested query selects a subset of rows from $sql.
// In production environments, be careful to avoid SQL Injection
// issues with concatenated SQL statements
$limit_sql =
   'select *
    from ( select a.*, rownum as rnum
        from (' . $sql . ') a
        where rownum < :FIRST_ROW + :NUM_ROWS )
    where rnum >= :FIRST_ROW';

$first = 1;  // start with the first row
$num   = 5;  // return 5 rows
$stid = oci_parse($conn, $limit_sql);
oci_bind_by_name($stid, ':FIRST_ROW', $first);
oci_bind_by_name($stid, ':NUM_ROWS', $num);
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
    echo $row['CITY'] . " " . $row['POSTAL_CODE'] . "<br>\n";
}

// Output is:
//    Beijing 190518x
//    Bern 3095x
//    Bombay 490231x
//    Geneva 1730x
//    Hiroshima 6823x

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note: Associative array indices need to be in uppercase for standard Oracle columns that were created with case insensitive names.

Note: For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

Note: The function oci_fetch_array() is insignificantly slower than oci_fetch_assoc() or oci_fetch_row(), but is more flexible.

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_set_prefetch() - Sets number of rows to be prefetched by queries

oci_fetch_all
oci_fetch_assoc
OCI8 Functions


Returns the next row from a query as an associative array

oci_fetch_array
oci_fetch_object
OCI8 Functions
PHP Manual

oci_fetch_assoc

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_assoc — Returns the next row from a query as an associative array

Description

array oci_fetch_assoc ( resource $statement )

Returns an associative array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

Calling oci_fetch_assoc() is identical to calling oci_fetch_array() with OCI_ASSOC + OCI_RETURN_NULLS.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns an associative array. If there are no more rows in the statement then FALSE is returned.

Notes

Note: See oci_fetch_array() for examples of fetching rows.

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array

oci_fetch_array
oci_fetch_object
OCI8 Functions


Returns the next row from a query as an object

oci_fetch_assoc
oci_fetch_row
OCI8 Functions
PHP Manual

oci_fetch_object

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_object — Returns the next row from a query as an object

Description

object oci_fetch_object ( resource $statement )

Returns an object containing the next result-set row of a query. Each attribute of the object corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns an object. Each attribute of the object corresponds to a column of the row. If there are no more rows in the statement then FALSE is returned.

Any LOB columns are returned as LOB descriptors.

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

Oracle's default, non-case sensitive column names will have uppercase attribute names. Case-sensitive column names will have attribute names using the exact column case. Use var_dump() on the result object to verify the appropriate case to use for each query.

Attribute values will be NULL for any NULL data fields.

Examples

Example #1 oci_fetch_object() example

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, description VARCHAR2(30));
    INSERT INTO mytab (id, description) values (1, 'Fish and Chips');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid))) {
    // Use upper case attribute names for each standard Oracle column
    echo $row->ID . "<br>\n";
    echo $row->DESCRIPTION . "<br>\n";
}

// Output is:
//    1
//    Fish and Chips

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_object() with case sensitive column names

<?php

/*
  Before running, create the table with a case sensitive column name:
    CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
    INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, "MyDescription" FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid))) {
    // Use upper case attribute names for each standard Oracle column
    echo $row->ID . "<br>\n";
    // Use the exact case for the case sensitive column name
    echo $row->MyDescription . "<br>\n";
}

// Output is:
//    1
//    Iced Coffee

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_object() with LOBs

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, description CLOB);
    INSERT INTO mytab (id, description) values (1, 'A very long string');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid))) {
    echo $row->ID . "<br>\n";
    // The following will output the first 11 bytes from DESCRIPTION
    echo $row->DESCRIPTION->read(11) . "<br>\n";
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_row() - Returns the next row from a query as a numeric array

oci_fetch_assoc
oci_fetch_row
OCI8 Functions


Returns the next row from a query as a numeric array

oci_fetch_object
oci_fetch
OCI8 Functions
PHP Manual

oci_fetch_row

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_row — Returns the next row from a query as a numeric array

Description

array oci_fetch_row ( resource $statement )

Returns a numerically indexed array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

Calling oci_fetch_row() is identical to calling oci_fetch_array() with OCI_NUM + OCI_RETURN_NULLS.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns a numerically indexed array. If there are no more rows in the statement then FALSE is returned.

Notes

Note: See oci_fetch_array() for examples of fetching rows.

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object

oci_fetch_object
oci_fetch
OCI8 Functions


Checks if the field is NULL

oci_fetch
oci_field_name
OCI8 Functions
PHP Manual

oci_field_is_null

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_is_null — Checks if the field is NULL

Description

bool oci_field_is_null ( resource $statement , mixed $field )

Checks if the given field from the statement is NULL.

Parameters

statement

A valid OCI statement identifier.

field

Can be a field's index or a field's name (uppercased).

Return Values

Returns TRUE if field is NULL, FALSE otherwise.

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumnisnull() instead. This name still can be used, it was left as alias of oci_field_is_null() for downwards compatability. This, however, is deprecated and not recommended.

oci_fetch
oci_field_name
OCI8 Functions


Returns the name of a field from the statement

oci_field_is_null
oci_field_precision
OCI8 Functions
PHP Manual

oci_field_name

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_name — Returns the name of a field from the statement

Description

string oci_field_name ( resource $statement , int $field )

Returns the name of the field .

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the name as a string, or FALSE on errors.

Examples

Example #1 oci_field_name() example

<?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "<table border=\"1\">";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>";
}

echo "</table>\n";
oci_free_statement($stmt);
oci_close($conn);
?>

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumnname() instead. This name still can be used, it was left as alias of oci_field_name() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_num_fields() - Returns the number of result columns in a statement
  • oci_field_type() - Returns field's data type
  • oci_field_size() - Returns field's size

oci_field_is_null
oci_field_precision
OCI8 Functions


Tell the precision of a field

oci_field_name
oci_field_scale
OCI8 Functions
PHP Manual

oci_field_precision

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_precision — Tell the precision of a field

Description

int oci_field_precision ( resource $statement , int $field )

Returns precision of the field .

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the precision as an integer, or FALSE on errors.

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumnprecision() instead. This name still can be used, it was left as alias of oci_field_precision() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_field_scale() - Tell the scale of the field
  • oci_field_type() - Returns field's data type

oci_field_name
oci_field_scale
OCI8 Functions


Tell the scale of the field

oci_field_precision
oci_field_size
OCI8 Functions
PHP Manual

oci_field_scale

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_scale — Tell the scale of the field

Description

int oci_field_scale ( resource $statement , int $field )

Returns the scale of the column with field index.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the scale as an integer, or FALSE on errors.

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This name still can be used, it was left as alias of oci_field_scale() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_field_precision() - Tell the precision of a field
  • oci_field_type() - Returns field's data type

oci_field_precision
oci_field_size
OCI8 Functions


Returns field's size

oci_field_scale
oci_field_type_raw
OCI8 Functions
PHP Manual

oci_field_size

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_size — Returns field's size

Description

int oci_field_size ( resource $statement , mixed $field )

Returns the size of a field .

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the size of a field in bytes, or FALSE on errors.

Examples

Example #1 oci_field_size() example

<?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "<table border=\"1\">";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);
    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>";
}

echo "</table>";

oci_free_statement($stmt);
oci_close($conn);
?>

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumnsize() instead. This name still can be used, it was left as alias of oci_field_size() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_num_fields() - Returns the number of result columns in a statement
  • oci_field_name() - Returns the name of a field from the statement

oci_field_scale
oci_field_type_raw
OCI8 Functions


Returns field's data type

oci_field_type_raw
oci_free_statement
OCI8 Functions
PHP Manual

oci_field_type

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_type — Returns field's data type

Description

mixed oci_field_type ( resource $statement , int $field )

Returns a field's data type.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the field data type as a string, or FALSE on errors.

Return Values

Example #1 oci_field_type() example

<?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "<table border=\"1\">";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>";
}

echo "</table>\n";

oci_free_statement($stmt);
oci_close($conn);
?>

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumntype() instead. This name still can be used, it was left as alias of oci_field_type() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_num_fields() - Returns the number of result columns in a statement
  • oci_field_name() - Returns the name of a field from the statement
  • oci_field_size() - Returns field's size

oci_field_type_raw
oci_free_statement
OCI8 Functions


Tell the raw Oracle data type of the field

oci_field_size
oci_field_type
OCI8 Functions
PHP Manual

oci_field_type_raw

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_type_raw — Tell the raw Oracle data type of the field

Description

int oci_field_type_raw ( resource $statement , int $field )

Returns Oracle's raw data type of the field .

However, if you want to get field's type, then oci_field_type() will suit you better.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns Oracle's raw data type as a string, or FALSE on errors.

Notes

Note: In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead. This name still can be used, it was left as alias of oci_field_type_raw() for downwards compatability. This, however, is deprecated and not recommended.

oci_field_size
oci_field_type
OCI8 Functions


Frees all resources associated with statement or cursor

oci_field_type
oci_internal_debug
OCI8 Functions
PHP Manual

oci_free_statement

(PHP 5, PECL OCI8 >= 1.1.0)

oci_free_statement — Frees all resources associated with statement or cursor

Description

bool oci_free_statement ( resource $statement )

Frees resources associated with Oracle's cursor or statement, which was received from as a result of oci_parse() or obtained from Oracle.

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns TRUE on success or FALSE on failure.

oci_field_type
oci_internal_debug
OCI8 Functions


Enables or disables internal debug output

oci_free_statement
OCI-Lob->append
OCI8 Functions
PHP Manual

oci_internal_debug

(PHP 5, PECL OCI8 >= 1.1.0)

oci_internal_debug — Enables or disables internal debug output

Description

void oci_internal_debug ( bool $onoff )

Enables or disables internal debug output.

Parameters

onoff

Set this to FALSE to turn debug output off or TRUE to turn it on.

Return Values

No value is returned.

Notes

Note: In PHP versions before 5.0.0 you must use ociinternaldebug() instead. This name still can be used, it was left as alias of oci_internal_debug() for downwards compatability. This, however, is deprecated and not recommended.

oci_free_statement
OCI-Lob->append
OCI8 Functions


Appends data from the large object to another large object

oci_internal_debug
OCI-Lob->close
OCI8 Functions
PHP Manual

OCI-Lob->append

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->append — Appends data from the large object to another large object

Description

OCI-Lob
bool append ( OCI-Lob $lob_from )

Appends data from the large object to the end of another large object.

Writing to the large object with this method will fail if buffering was previously enabled. You must disable buffering before appending. You may need to flush buffers with OCI-Lob->flush before disabling buffering.

Parameters

lob_from

The copied LOB.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob->flush
  • OCI-Lob->setBuffering
  • OCI-Lob->getBuffering

oci_internal_debug
OCI-Lob->close
OCI8 Functions


Closes LOB descriptor

OCI-Lob->append
oci_lob_copy
OCI8 Functions
PHP Manual

OCI-Lob->close

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->close — Closes LOB descriptor

Description

OCI-Lob
bool close ( void )

Closes descriptor of LOB or FILE. This function should be used only with OCI-Lob->writeTemporary.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob->writeTemporary

OCI-Lob->append
oci_lob_copy
OCI8 Functions


Copies large object

OCI-Lob->close
OCI-Lob->eof
OCI8 Functions
PHP Manual

oci_lob_copy

(PHP 5, PECL OCI8 >= 1.1.0)

oci_lob_copy — Copies large object

Description

bool oci_lob_copy ( OCI-Lob $lob_to , OCI-Lob $lob_from [, int $length = 0 ] )

Copies a large object or a part of a large object to another large object. Old LOB-recipient data will be overwritten.

If you need to copy a particular part of a LOB to a particular position of a LOB, use oci_lob_seek() to move LOB internal pointers.

Parameters

lob_to

The destination LOB.

lob_from

The copied LOB.

length

Indicates the length of data to be copied.

Return Values

Returns TRUE on success or FALSE on failure.

OCI-Lob->close
OCI-Lob->eof
OCI8 Functions


Tests for end-of-file on a large object's descriptor

oci_lob_copy
OCI-Lob->erase
OCI8 Functions
PHP Manual

OCI-Lob->eof

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->eof — Tests for end-of-file on a large object's descriptor

Description

OCI-Lob
bool eof ( void )

Tells whether the internal pointer of large object is at the end of LOB.

Return Values

Returns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.

See Also

  • OCI-Lob->size

oci_lob_copy
OCI-Lob->erase
OCI8 Functions


Erases a specified portion of the internal LOB data

OCI-Lob->eof
OCI-Lob->export
OCI8 Functions
PHP Manual

OCI-Lob->erase

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->erase — Erases a specified portion of the internal LOB data

Description

OCI-Lob
int erase ([ int $offset [, int $length ]] )

Erases a specified portion of the internal LOB data starting at a specified offset . If called without parameters, it erases all LOB data.

For BLOBs, erasing means that the existing LOB value is overwritten with zero-bytes. For CLOBs, the existing LOB value is overwritten with spaces.

Parameters

offset

length

Return Values

Returns the actual number of characters/bytes erased or FALSE on failure.

See Also

  • OCI-Lob->truncate

OCI-Lob->eof
OCI-Lob->export
OCI8 Functions


Exports LOB's contents to a file

OCI-Lob->erase
OCI-Lob->flush
OCI8 Functions
PHP Manual

OCI-Lob->export

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->export — Exports LOB's contents to a file

Description

OCI-Lob
bool export ( string $filename [, int $start [, int $length ]] )

Exports LOB contents to a file.

Parameters

filename

Path to the file.

start

Indicates from where to start exporting.

length

Indicates the length of data to be exported.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob->import

OCI-Lob->erase
OCI-Lob->flush
OCI8 Functions


Flushes/writes buffer of the LOB to the server

OCI-Lob->export
OCI-Lob->free
OCI8 Functions
PHP Manual

OCI-Lob->flush

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->flush — Flushes/writes buffer of the LOB to the server

Description

OCI-Lob
bool flush ([ int $flag ] )

OCI-Lob->flush() actually writes data to the server.

Parameters

flag

By default, resources are not freed, but using flag OCI_LOB_BUFFER_FREE you can do it explicitly. Be sure you know what you're doing - next read/write operation to the same part of LOB will involve a round-trip to the server and initialize new buffer resources. It is recommended to use OCI_LOB_BUFFER_FREE flag only when you are not going to work with the LOB anymore.

Return Values

Returns TRUE on success or FALSE on failure.

Returns FALSE if buffering was not enabled or an error occurred.

See Also

  • OCI-Lob->getBuffering
  • OCI-Lob->setBuffering

OCI-Lob->export
OCI-Lob->free
OCI8 Functions


Frees resources associated with the LOB descriptor

OCI-Lob->flush
OCI-Lob->getBuffering
OCI8 Functions
PHP Manual

OCI-Lob->free

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->free — Frees resources associated with the LOB descriptor

Description

OCI-Lob
bool free ( void )

Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().

Return Values

Returns TRUE on success or FALSE on failure.

OCI-Lob->flush
OCI-Lob->getBuffering
OCI8 Functions


Returns current state of buffering for the large object

OCI-Lob->free
OCI-Lob->import
OCI8 Functions
PHP Manual

OCI-Lob->getBuffering

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->getBuffering — Returns current state of buffering for the large object

Description

OCI-Lob
bool getBuffering ( void )

Tells whether the buffering for the large object is on or off.

Return Values

Returns FALSE if buffering for the large object is off and TRUE if buffering is used.

See Also

  • OCI-Lob->setBuffering

OCI-Lob->free
OCI-Lob->import
OCI8 Functions


Imports file data to the LOB

OCI-Lob->getBuffering
oci_lob_is_equal
OCI8 Functions
PHP Manual

OCI-Lob->import

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->import — Imports file data to the LOB

Description

OCI-Lob
bool import ( string $filename )

Writes data from the filename in to the current position of large object.

Parameters

filename

Path to the file.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob->export
  • OCI-Lob->write

OCI-Lob->getBuffering
oci_lob_is_equal
OCI8 Functions


Compares two LOB/FILE locators for equality

OCI-Lob->import
OCI-Lob->load
OCI8 Functions
PHP Manual

oci_lob_is_equal

(PHP 5, PECL OCI8 >= 1.1.0)

oci_lob_is_equal — Compares two LOB/FILE locators for equality

Description

bool oci_lob_is_equal ( OCI-Lob $lob1 , OCI-Lob $lob2 )

Compares two LOB/FILE locators.

Parameters

lob1

A LOB identifier.

lob2

A LOB identifier.

Return Values

Returns TRUE if these objects are equal, FALSE otherwise.

OCI-Lob->import
OCI-Lob->load
OCI8 Functions


Returns large object's contents

oci_lob_is_equal
OCI-Lob->read
OCI8 Functions
PHP Manual

OCI-Lob->load

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->load — Returns large object's contents

Description

OCI-Lob
string load ( void )

Returns large object's contents. As script execution is terminated when the memory_limit is reached, ensure that the LOB does not exceed this limit. In most cases it's recommended to use OCI-Lob->read instead.

Return Values

Returns the contents of the object, or FALSE on errors.

See Also

  • OCI-Lob->read

oci_lob_is_equal
OCI-Lob->read
OCI8 Functions


Reads part of the large object

OCI-Lob->load
OCI-Lob->rewind
OCI8 Functions
PHP Manual

OCI-Lob->read

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->read — Reads part of the large object

Description

OCI-Lob
string read ( int $length )

Reads length bytes from the current position of LOB's internal pointer.

Reading stops when length bytes have been read or end of the large object is reached. Internal pointer of the large object will be shifted on the amount of bytes read.

Parameters

length

The length of data to read, in bytes.

Return Values

Returns the contents as a string, or FALSE on failure.

See Also

  • OCI-Lob->load
  • OCI-Lob->write

OCI-Lob->load
OCI-Lob->rewind
OCI8 Functions


Moves the internal pointer to the beginning of the large object

OCI-Lob->read
OCI-Lob->save
OCI8 Functions
PHP Manual

OCI-Lob->rewind

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->rewind — Moves the internal pointer to the beginning of the large object

Description

OCI-Lob
bool rewind ( void )

Sets the internal pointer to the beginning of the large object.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob->seek
  • OCI-Lob->tell

OCI-Lob->read
OCI-Lob->save
OCI8 Functions


Saves data to the large object

OCI-Lob->rewind
OCI-Lob->saveFile
OCI8 Functions
PHP Manual

OCI-Lob->save

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->save — Saves data to the large object

Description

OCI-Lob
bool save ( string $data [, int $offset ] )

Saves data to the large object.

Parameters

data

The data to be saved.

offset

Can be used to indicate offset from the beginning of the large object.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob->write
  • OCI-Lob->import

OCI-Lob->rewind
OCI-Lob->saveFile
OCI8 Functions


Alias of oci_lob_import

OCI-Lob->save
OCI-Lob->seek
OCI8 Functions
PHP Manual

OCI-Lob->saveFile

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->saveFile — Alias of oci_lob_import()

Description

This function is an alias of: oci_lob_import().

OCI-Lob->save
OCI-Lob->seek
OCI8 Functions


Sets the internal pointer of the large object

OCI-Lob->saveFile
OCI-Lob->setBuffering
OCI8 Functions
PHP Manual

OCI-Lob->seek

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->seek — Sets the internal pointer of the large object

Description

OCI-Lob
bool seek ( int $offset [, int $whence ] )

Sets the internal pointer of the large object.

Parameters

offset

Indicates the amount of bytes, on which internal pointer should be moved from the position, pointed by whence .

whence

May be one of:

  • OCI_SEEK_SET - sets the position equal to offset
  • OCI_SEEK_CUR - adds offset bytes to the current position
  • OCI_SEEK_END - adds offset bytes to the end of large object (use negative value to move to a position before the end of large object)

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob->rewind
  • OCI-Lob->tell
  • OCI-Lob->eof

OCI-Lob->saveFile
OCI-Lob->setBuffering
OCI8 Functions


Changes current state of buffering for the large object

OCI-Lob->seek
OCI-Lob->size
OCI8 Functions
PHP Manual

OCI-Lob->setBuffering

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->setBuffering — Changes current state of buffering for the large object

Description

OCI-Lob
bool setBuffering ( bool $on_off )

Sets the buffering for the large object, depending on the value of the on_off parameter.

Use of this function may provide performance improvements by buffering small reads and writes of LOBs by reducing the number of network round-trips and LOB versions. oci_lob_flush() should be used to flush buffers, when you have finished working with the large object.

Parameters

on_off

TRUE for on and FALSE for off.

Return Values

Returns TRUE on success or FALSE on failure. Repeated calls to this method with the same flag will return TRUE.

See Also

  • OCI-Lob->getBuffering

OCI-Lob->seek
OCI-Lob->size
OCI8 Functions


Returns size of large object

OCI-Lob->setBuffering
OCI-Lob->tell
OCI8 Functions
PHP Manual

OCI-Lob->size

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->size — Returns size of large object

Description

OCI-Lob
int size ( void )

Gets the size of the large object.

Return Values

Returns length of large object value or FALSE on failure. Empty objects have zero length.

OCI-Lob->setBuffering
OCI-Lob->tell
OCI8 Functions


Returns current position of internal pointer of large object

OCI-Lob->size
OCI-Lob->truncate
OCI8 Functions
PHP Manual

OCI-Lob->tell

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->tell — Returns current position of internal pointer of large object

Description

OCI-Lob
int tell ( void )

Gets the current position of a LOB's internal pointer.

Return Values

Returns current position of a LOB's internal pointer or FALSE if an error occurred.

See Also

  • OCI-Lob->rewind
  • OCI-Lob->size
  • OCI-Lob->eof

OCI-Lob->size
OCI-Lob->truncate
OCI8 Functions


Truncates large object

OCI-Lob->tell
OCI-Lob->write
OCI8 Functions
PHP Manual

OCI-Lob->truncate

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->truncate — Truncates large object

Description

OCI-Lob
bool truncate ([ int $length ] )

Truncates the LOB.

Parameters

length

If provided, this method will truncate the LOB to length bytes. Otherwise, it will completrely purge the LOB.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob->erase

OCI-Lob->tell
OCI-Lob->write
OCI8 Functions


Writes data to the large object

OCI-Lob->truncate
OCI-Lob->writeTemporary
OCI8 Functions
PHP Manual

OCI-Lob->write

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->write — Writes data to the large object

Description

OCI-Lob
int write ( string $data [, int $length ] )

Writes data from the parameter data into the current position of LOB's internal pointer.

Parameters

data

The data to write in the LOB.

length

If this parameter is given, writing will stop after length bytes have been written or the end of data is reached, whichever comes first.

Return Values

Returns the number of bytes written or FALSE on failure.

See Also

  • OCI-Lob->read

OCI-Lob->truncate
OCI-Lob->writeTemporary
OCI8 Functions


Writes temporary large object

OCI-Lob->write
OCI-Lob->writeToFile
OCI8 Functions
PHP Manual

OCI-Lob->writeTemporary

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->writeTemporary — Writes temporary large object

Description

OCI-Lob
bool writeTemporary ( string $data [, int $lob_type = OCI_TEMP_CLOB ] )

Creates a temporary large object and writes data to it.

You should use OCI-Lob->close when you are done with this object.

Parameters

data

The data to write.

lob_type

Can be one of the following:

  • OCI_TEMP_BLOB is used to create temporary BLOBs
  • OCI_TEMP_CLOB is used to create temporary CLOBs

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob->close

OCI-Lob->write
OCI-Lob->writeToFile
OCI8 Functions


Alias of oci_lob_export

OCI-Lob->writeTemporary
oci_new_collection
OCI8 Functions
PHP Manual

OCI-Lob->writeToFile

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob->writeToFile — Alias of oci_lob_export()

Description

This function is an alias of: oci_lob_export().

OCI-Lob->writeTemporary
oci_new_collection
OCI8 Functions


Allocates new collection object

OCI-Lob->writeToFile
oci_new_connect
OCI8 Functions
PHP Manual

oci_new_collection

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_collection — Allocates new collection object

Description

OCI-Collection oci_new_collection ( resource $connection , string $tdo [, string $schema = NULL ] )

Allocates a new collection object.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

tdo

Should be a valid named type (uppercase).

schema

Should point to the scheme, where the named type was created. The name of the current user is the default value.

Return Values

Returns a new OCICollection object or FALSE on error.

Notes

Note: In PHP versions before 5.0.0 you must use ocinewcollection() instead. This name still can be used, it was left as alias of oci_new_collection() for downwards compatability. This, however, is deprecated and not recommended.

OCI-Lob->writeToFile
oci_new_connect
OCI8 Functions


Connect to the Oracle server using a unique connection

oci_new_collection
oci_new_cursor
OCI8 Functions
PHP Manual

oci_new_connect

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_connect — Connect to the Oracle server using a unique connection

Description

resource oci_new_connect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] )

Establishes a new connection to an Oracle server and logs on.

Unlike oci_connect() and oci_pconnect(), oci_new_connect() does not cache connections and will always return a brand-new freshly opened connection handle. This is useful if your application needs transactional isolation between two sets of queries.

Parameters

username

The Oracle user name.

password

The password for username .

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. With Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce connection time.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Return Values

Returns a connection identifier or FALSE on error.

Examples

The following demonstrates how you can separate connections.

Example #1 oci_new_connect() example

<?php
echo "<html><pre>";
$db = "";

$c1 = oci_connect("scott", "tiger", $db);
$c2 = oci_new_connect("scott", "tiger", $db);

function create_table($conn)
{
  $stmt = oci_parse($conn, "create table scott.hallo (test
varchar2(64))");
  oci_execute($stmt);
  echo $conn . " created table\n\n";
}

function drop_table($conn)
{
  $stmt = oci_parse($conn, "drop table scott.hallo");
  oci_execute($stmt);
  echo $conn . " dropped table\n\n";
}

function insert_data($conn)
{
  $stmt = oci_parse($conn, "insert into scott.hallo
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " inserted hallo\n\n";
}

function delete_data($conn)
{
  $stmt = oci_parse($conn, "delete from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " deleted hallo\n\n";
}

function commit($conn)
{
  oci_commit($conn);
  echo $conn . " committed\n\n";
}

function rollback($conn)
{
  oci_rollback($conn);
  echo $conn . " rollback\n\n";
}

function select_data($conn)
{
  $stmt = oci_parse($conn, "select * from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . "----selecting\n\n";
  while (oci_fetch($stmt)) {
    echo $conn . " <" . oci_result($stmt, "TEST") . ">\n\n";
  }
  echo $conn . "----done\n\n";
}

create_table($c1);
insert_data($c1);

select_data($c1);
select_data($c2);

rollback($c1);

select_data($c1);
select_data($c2);

insert_data($c2);
commit($c2);

select_data($c1);

delete_data($c1);
select_data($c1);
select_data($c2);
commit($c1);

select_data($c1);
select_data($c2);

drop_table($c1);
echo "</pre></html>";
?>

Notes

Note: In PHP versions before 5.0.0 you must use ocinlogon() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_connect() - Connect to an Oracle database
  • oci_pconnect() - Connect to an Oracle database using a persistent connection

oci_new_collection
oci_new_cursor
OCI8 Functions


Allocates and returns a new cursor (statement handle)

oci_new_connect
oci_new_descriptor
OCI8 Functions
PHP Manual

oci_new_cursor

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_cursor — Allocates and returns a new cursor (statement handle)

Description

resource oci_new_cursor ( resource $connection )

Allocates a new statement handle on the specified connection.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

Return Values

Returns a new statement handle, or FALSE on error.

Examples

Example #1 Using REF CURSOR in an Oracle's stored procedure

<?php
// suppose your stored procedure info.output returns a ref cursor in :data

$conn = oci_connect("scott", "tiger");
$curs = oci_new_cursor($conn);
$stmt = oci_parse($conn, "begin info.output(:data); end;");

oci_bind_by_name($stmt, "data", $curs, -1, OCI_B_CURSOR);
oci_execute($stmt);
oci_execute($curs);

while ($data = oci_fetch_row($curs)) {
    var_dump($data);
}

oci_free_statement($stmt);
oci_free_statement($curs);
oci_close($conn);
?>

Example #2 Using REF CURSOR in an Oracle's select statement

<?php
echo "<html><body>";
$conn = oci_connect("scott", "tiger");
$count_cursor = "CURSOR(select count(empno) num_emps from emp " .
                "where emp.deptno = dept.deptno) as EMPCNT from dept";
$stmt = oci_parse($conn, "select deptno,dname,$count_cursor");

oci_execute($stmt);
echo "<table border=\"1\">";
echo "<tr>";
echo "<th>DEPT NAME</th>";
echo "<th>DEPT #</th>";
echo "<th># EMPLOYEES</th>";
echo "</tr>";

while ($data = oci_fetch_assoc($stmt)) {
    echo "<tr>";
    $dname  = $data["DNAME"];
    $deptno = $data["DEPTNO"];
    echo "<td>$dname</td>";
    echo "<td>$deptno</td>";
    oci_execute($data["EMPCNT"]);
    while ($subdata = oci_fetch_assoc($data["EMPCNT"])) {
        $num_emps = $subdata["NUM_EMPS"];
        echo  "<td>$num_emps</td>";
    }
    echo "</tr>";
}
echo "</table>";
echo "</body></html>";
oci_free_statement($stmt);
oci_close($conn);
?>

Notes

Note: In PHP versions before 5.0.0 you must use ocinewcursor() instead. This name still can be used, it was left as alias of oci_new_cursor() for downwards compatability. This, however, is deprecated and not recommended.

oci_new_connect
oci_new_descriptor
OCI8 Functions


Initializes a new empty LOB or FILE descriptor

oci_new_cursor
oci_num_fields
OCI8 Functions
PHP Manual

oci_new_descriptor

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_descriptor — Initializes a new empty LOB or FILE descriptor

Description

OCI-Lob oci_new_descriptor ( resource $connection [, int $type = OCI_DTYPE_LOB ] )

Allocates resources to hold descriptor or LOB locator.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

type

Valid values for type are: OCI_DTYPE_FILE, OCI_DTYPE_LOB and OCI_DTYPE_ROWID.

Return Values

Returns a new LOB or FILE descriptor on success, FALSE on error.

Examples

Example #1 oci_new_descriptor() example

<?php
/* This script is designed to be called from a HTML form.
 * It expects $user, $password, $table, $where, and $commitsize
 * to be passed in from the form.  The script then deletes
 * the selected rows using the ROWID and commits after each
 * set of $commitsize rows. (Use with care, there is no rollback)
 */
$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "select rowid from $table $where");
$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_define_by_name($stmt, "ROWID", $rowid);
oci_execute($stmt);
while (oci_fetch($stmt)) {
    $nrows = oci_num_rows($stmt);
    $delete = oci_parse($conn, "delete from $table where ROWID = :rid");
    oci_bind_by_name($delete, ":rid", $rowid, -1, OCI_B_ROWID);
    oci_execute($delete);
    echo "$nrows\n";
    if (($nrows % $commitsize) == 0) {
        oci_commit($conn);
    }
}
$nrows = oci_num_rows($stmt);
echo "$nrows deleted...\n";
oci_free_statement($stmt);
oci_close($conn);
?>
<?php
    /* This script demonstrates file upload to LOB columns
     * The formfield used for this example looks like this
     * <form action="upload.php" method="post" enctype="multipart/form-data">
     * <input type="file" name="lob_upload" />
     * ...
     */
  if (!isset($lob_upload) || $lob_upload == 'none'){
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload file: <input type="file" name="lob_upload" /><br />
<input type="submit" value="Upload" /> - <input type="reset" value="Reset" />
</form>
<?php
  } else {

     // $lob_upload contains the temporary filename of the uploaded file

     // see also the features section on file upload,
     // if you would like to use secure uploads

     $conn = oci_connect($user, $password);
     $lob = oci_new_descriptor($conn, OCI_D_LOB);
     $stmt = oci_parse($conn, "insert into $table (id, the_blob)
               values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
     oci_bind_by_name($stmt, ':the_blob', $lob, -1, OCI_B_BLOB);
     oci_execute($stmt, OCI_DEFAULT);
     if ($lob->savefile($lob_upload)){
        oci_commit($conn);
        echo "Blob successfully uploaded\n";
     }else{
        echo "Couldn't upload Blob\n";
     }
     oci_free_descriptor($lob);
     oci_free_statement($stmt);
     oci_close($conn);
  }
?>

Example #2 oci_new_descriptor() example

<?php
/* Calling PL/SQL stored procedures which contain clobs as input
 * parameters (PHP 4 >= 4.0.6).
 * Example PL/SQL stored procedure signature is:
 *
 * PROCEDURE save_data
 *   Argument Name                  Type                    In/Out Default?
 *   ------------------------------ ----------------------- ------ --------
 *   KEY                            NUMBER(38)              IN
 *   DATA                           CLOB                    IN
 *
 */

$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "begin save_data(:key, :data); end;");
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':key', $key);
oci_bind_by_name($stmt, ':data', $clob, -1, OCI_B_CLOB);
$clob->write($data);
oci_execute($stmt, OCI_DEFAULT);
oci_commit($conn);
$clob->free();
oci_free_statement($stmt);
?>

Notes

Note: In PHP versions before 5.0.0 you must use ocinewdescriptor() instead. This name still can be used, it was left as alias of oci_new_descriptor() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_bind_by_name() - Binds a PHP variable to an Oracle placeholder

oci_new_cursor
oci_num_fields
OCI8 Functions


Returns the number of result columns in a statement

oci_new_descriptor
oci_num_rows
OCI8 Functions
PHP Manual

oci_num_fields

(PHP 5, PECL OCI8 >= 1.1.0)

oci_num_fields — Returns the number of result columns in a statement

Description

int oci_num_fields ( resource $statement )

Gets the number of columns in the given statement .

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns the number of columns as an integer, or FALSE on errors.

Examples

Example #1 oci_num_fields() example

<?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "select * from emp");

oci_execute($stmt);

while (oci_fetch($stmt)) {
    echo "\n";
    $ncols = oci_num_fields($stmt);
    for ($i = 1; $i <= $ncols; $i++) {
        $column_name  = oci_field_name($stmt, $i);
        $column_value = oci_result($stmt, $i);
        echo $column_name . ': ' . $column_value . "\n";
    }
    echo "\n";
}

oci_free_statement($stmt);
oci_close($conn);
?>

Notes

Note: In PHP versions before 5.0.0 you must use ocinumcols() instead. This name still can be used, it was left as alias of oci_num_fields() for downwards compatability. This, however, is deprecated and not recommended.

oci_new_descriptor
oci_num_rows
OCI8 Functions


Returns number of rows affected during statement execution

oci_num_fields
oci_parse
OCI8 Functions
PHP Manual

oci_num_rows

(PHP 5, PECL OCI8 >= 1.1.0)

oci_num_rows — Returns number of rows affected during statement execution

Description

int oci_num_rows ( resource $statement )

Gets the number of rows affected during statement execution.

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns the number of rows affected as an integer, or FALSE on errors.

Examples

Example #1 oci_num_rows() example

<?php
$conn = oci_connect("scott", "tiger");

$stmt = oci_parse($conn, "create table emp2 as select * from emp");
oci_execute($stmt);
echo oci_num_rows($stmt) . " rows inserted.<br />";
oci_free_statement($stmt);

$stmt = oci_parse($conn, "delete from emp2");
oci_execute($stmt, OCI_DEFAULT);
echo oci_num_rows($stmt) . " rows deleted.<br />";
oci_commit($conn);
oci_free_statement($stmt);

$stmt = oci_parse($conn, "drop table emp2");
oci_execute($stmt);
oci_free_statement($stmt);

oci_close($conn);
?>

Notes

Note: This function does not return number of rows selected! For SELECT statements this function will return the number of rows, that were fetched to the buffer with oci_fetch*() functions.

Note: In PHP versions before 5.0.0 you must use ocirowcount() instead. This name still can be used, it was left as alias of oci_num_rows() for downwards compatability. This, however, is deprecated and not recommended.

oci_num_fields
oci_parse
OCI8 Functions


Prepares an Oracle statement for execution

oci_num_rows
oci_password_change
OCI8 Functions
PHP Manual

oci_parse

(PHP 5, PECL OCI8 >= 1.1.0)

oci_parse — Prepares an Oracle statement for execution

Description

resource oci_parse ( resource $connection , string $sql_text )

Prepares sql_text using connection and returns the statement identifier, which can be used with oci_bind_by_name(), oci_execute() and other functions.

Statement identifiers can be freed with oci_free_statement() or by setting the variable to null.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

sql_text

The SQL or PL/SQL statement.

SQL statements should not end with a semi-colon (";"). PL/SQL statements should end with a semi-colon (";").

Return Values

Returns a statement handle on success, or FALSE on error.

Examples

Example #1 oci_parse() example for SQL statements

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

// Parse the statement. Note there is no final semi-colon in the SQL statement
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Example #2 oci_parse() example for PL/SQL statements

<?php

/*
  Before running the PHP program, create a stored procedure in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
  BEGIN
      p2 := p1 * 2;
  END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p1 = 8;

// When parsing PL/SQL programs, there should be a final semi-colon in the string
$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note: This function does not validate sql_text . The only way to find out if sql_text is a valid SQL or PL/SQL statement is to execute it.

Note: In PHP versions before 5.0.0 use ociparse() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_execute() - Executes a statement
  • oci_free_statement() - Frees all resources associated with statement or cursor

oci_num_rows
oci_password_change
OCI8 Functions


Changes password of Oracle's user

oci_parse
oci_pconnect
OCI8 Functions
PHP Manual

oci_password_change

(PHP 5, PECL OCI8 >= 1.1.0)

oci_password_change — Changes password of Oracle's user

Description

bool oci_password_change ( resource $connection , string $username , string $old_password , string $new_password )
resource oci_password_change ( string $dbname , string $username , string $old_password , string $new_password )

Changes password for user with username .

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

username

The Oracle user name.

old_password

The old password.

new_password

The new password to be set.

dbname

The database name.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: The second oci_password_change() syntax is available since version 1.1.

Note: In PHP versions before 5.0.0 you must use ocipasswordchange() instead. This name still can be used, it was left as alias of oci_password_change() for downwards compatability. This, however, is deprecated and not recommended.

oci_parse
oci_pconnect
OCI8 Functions


Connect to an Oracle database using a persistent connection

oci_password_change
oci_result
OCI8 Functions
PHP Manual

oci_pconnect

(PHP 5, PECL OCI8 >= 1.1.0)

oci_pconnect — Connect to an Oracle database using a persistent connection

Description

resource oci_pconnect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] )

Creates a persistent connection to an Oracle server and logs on.

Persistent connections are cached and re-used between requests, resulting in reduced overhead on each page load; a typical PHP application will have a single persistent connection open against an Oracle server per Apache child process (or PHP FastCGI/CGI process). See the Persistent Database Connections section for more information.

Parameters

username

The Oracle user name.

password

The password for username .

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. With Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce connection time.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Return Values

Returns a connection identifier or FALSE on error.

Notes

Note: Starting with PHP 5.1.2 and PECL oci8 1.1, the lifetime and maximum number of persistent Oracle connections can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.

Note: In PHP versions before 5.0.0 you must use ociplogon() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_connect() - Connect to an Oracle database
  • oci_new_connect() - Connect to the Oracle server using a unique connection

oci_password_change
oci_result
OCI8 Functions


Returns field's value from the fetched row

oci_pconnect
oci_rollback
OCI8 Functions
PHP Manual

oci_result

(PHP 5, PECL OCI8 >= 1.1.0)

oci_result — Returns field's value from the fetched row

Description

mixed oci_result ( resource $statement , mixed $field )

Returns the data from field in the current row, fetched by oci_fetch().

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parameters

statement

field

Can be either use the column number (1-based) or the column name (in uppercase).

Return Values

Returns everything as strings except for abstract types (ROWIDs, LOBs and FILEs). Returns FALSE on error.

Notes

Note: In PHP versions before 5.0.0 you must use ociresult() instead. This name still can be used, it was left as alias of oci_result() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array

oci_pconnect
oci_rollback
OCI8 Functions


Rolls back the outstanding database transaction

oci_result
oci_server_version
OCI8 Functions
PHP Manual

oci_rollback

(PHP 5, PECL OCI8 >= 1.1.0)

oci_rollback — Rolls back the outstanding database transaction

Description

bool oci_rollback ( resource $connection )

Reverts all uncommitted changes for the Oracle connection and ends the transaction. It releases all locks held. All Oracle SAVEPOINTS are erased.

A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. Further data changes made by other statements become part of the same transaction. Data changes made in a transaction are temporary until the transaction is committed or rolled back. Other users of the database will not see the changes until they are committed.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect() or oci_new_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_rollback() example

<?php

// Insert into several tables, rolling back the changes if an error occurs

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");

// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1.  The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    oci_rollback($conn);  // rollback changes to both tables
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

// Commit the changes to both tables
$r = oci_commit($conn);
if (!r) {
    $e = oci_error($conn);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

?>

Example #2 Rolling back to a SAVEPOINT example

$stid = oci_parse($conn, 'UPDATE mytab SET id = 1111');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

// Create the savepoint
$stid = oci_parse($conn, 'SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

$stid = oci_parse($conn, 'UPDATE mytab SET id = 2222');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

// Use an explicit SQL statement to rollback to the savepoint
$stid = oci_parse($conn, 'ROLLBACK TO SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

oci_commit($conn);  // mytab now has id of 1111

Notes

Note: Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction.
Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.
Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

Note: In PHP versions before 5.0.0 you must use ocirollback() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_commit() - Commits the outstanding database transaction
  • oci_execute() - Executes a statement

oci_result
oci_server_version
OCI8 Functions


Returns server version

oci_rollback
oci_set_action
OCI8 Functions
PHP Manual

oci_server_version

(PHP 5, PECL OCI8 >= 1.1.0)

oci_server_version — Returns server version

Description

string oci_server_version ( resource $connection )

Returns a string with version information of the Oracle server, which uses the provided connection .

Parameters

connection

Return Values

Returns the version information as a string or FALSE on error.

Examples

Example #1 oci_server_version() example

<?php
    $conn = oci_connect("scott", "tiger");
    echo "Server Version: " . oci_server_version($conn);
    oci_close($conn);
?>

Notes

Note: In PHP versions before 5.0.0 you must use ociserverversion() instead. This name still can be used, it was left as alias of oci_server_version() for downwards compatability. This, however, is deprecated and not recommended.

oci_rollback
oci_set_action
OCI8 Functions


Sets the action name

oci_server_version
oci_set_client_identifier
OCI8 Functions
PHP Manual

oci_set_action

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_action — Sets the action name

Description

bool oci_set_action ( resource $connection , string $action_name )

Sets the action name for Oracle tracing.

The action name is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when a SQL statement is executed.

The action name can subsequently be queried from database administration views such as V$SESSION. It can be used for tracing and monitoring such as with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.

The value may be retained across persistent connections.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

action_name

User chosen string up to 32 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the action

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the action
oci_set_action($c, 'Friend Lookup');

// Code that causes a roundtrip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);

?>
// While the script is running, the administrator can see the actions
// being performed:

sqlplus system/welcome
SQL> select action from v$session;

Notes

Note: Oracle version requirement
This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Caution

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

See Also

  • oci_set_module_name() - Sets the module name
  • oci_set_client_info() - Sets the client information
  • oci_set_client_identifier() - Sets the client identifier

oci_server_version
oci_set_client_identifier
OCI8 Functions


Sets the client identifier

oci_set_action
oci_set_client_info
OCI8 Functions
PHP Manual

oci_set_client_identifier

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_client_identifier — Sets the client identifier

Description

bool oci_set_client_identifier ( resource $connection , string $client_identifier )

Sets the client identifier used by various database components to identify lightweight application users who authenticate as the same database user.

The client identifier is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when a SQL statement is executed.

The identifier can subsequently be queried from database administration views such as V$SESSION. It can be used with DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE for tracing. It can be used for auditing.

The value may be retained across persistent connections.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

client_identifier

User chosen string up to 64 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the client identifier to the application user

<?php

// Find the application user's login name
session_start();
$un = my_validate_session($_SESSION['username']);
$c = oci_connect('myschema', 'welcome', 'localhost/XE');

// Tell Oracle who that user is
oci_set_client_identifier($c, $un);

// The next roundtrip to the database will piggyback the identifier
$s = oci_parse($c, 'select mydata from mytable');
oci_execute($s);

...

?>

Notes

Caution

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

See Also

  • oci_set_module_name() - Sets the module name
  • oci_set_action() - Sets the action name
  • oci_set_client_info() - Sets the client information

oci_set_action
oci_set_client_info
OCI8 Functions


Sets the client information

oci_set_client_identifier
oci_set_edition
OCI8 Functions
PHP Manual

oci_set_client_info

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_client_info — Sets the client information

Description

bool oci_set_client_info ( resource $connection , string $client_info )

Sets the client information for Oracle tracing.

The client information is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when a SQL statement is executed.

The client information can subsequently be queried from database administration views such as V$SESSION.

The value may be retained across persistent connections.

Parameters

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

User chosen string up to 64 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the client information

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the client information
oci_set_client_info($c, 'My Application Version 2');

// Code that causes a roundtrip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);

?>
// While the script is running, the administrator can see the client
// information:

sqlplus system/welcome
SQL> select client_info from v$session;

Notes

Note: Oracle version requirement
This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Caution

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

See Also

  • oci_set_module_name() - Sets the module name
  • oci_set_action() - Sets the action name
  • oci_set_client_identifier() - Sets the client identifier

oci_set_client_identifier
oci_set_edition
OCI8 Functions


Sets the database edition

oci_set_client_info
oci_set_module_name
OCI8 Functions
PHP Manual

oci_set_edition

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_edition — Sets the database edition

Description

bool oci_set_edition ( string $edition )

Sets the database "edition" of objects to be used by a subsequent connections.

Oracle Editions allow concurrent versions of applications to run using the same schema and object names. This is useful for upgrading live systems.

Call oci_set_edition() before calling
oci_connect(), oci_pconnect()
or oci_new_connect().

If an edition is set that is not valid in the database, connection will fail even if oci_set_edition() returns success.

When using persistent connections, if a connection with the requested edition setting already exists, it is reused. Otherwise, a different persistent connection is created

Parameters

edition

Oracle Database edition name previously created with the SQL "CREATE EDITION" command.

Notes

Note: Oracle version requirement
This function is available from Oracle 11gR2 onwards.

Caution

Persistent connections

To avoid inconsistencies and unexpected errors, do not use ALTER SESSION SET EDITION to change the edition on persistent connections.

Caution

DRCP Connection Pooling

To avoid inconsistencies and unexpected errors when using editions and DRCP with Oracle 11.2.0.1, keep a one-to-one correspondence between the oci8.connection_class and the edition name used by applications. Each pooled server of a given connection class should only be used with one edition.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Two scripts can use different versions of myfunc() at the same time

<?php

// File 1

echo "Version 1 of application\n";

oci_set_edition('ORA$BASE');
$c = oci_connect('hr', 'welcome', 'localhost/XE');

$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";

?>
<?php

// File 2

echo "Version 2 of application\n";

oci_set_edition('E1');
$c = oci_connect('hr', 'welcome', 'localhost/XE');

$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";

?>

oci_set_client_info
oci_set_module_name
OCI8 Functions


Sets the module name

oci_set_edition
oci_set_prefetch
OCI8 Functions
PHP Manual

oci_set_module_name

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_module_name — Sets the module name

Description

bool oci_set_module_name ( resource $connection , string $module_name )

Sets the module name for Oracle tracing.

The module name is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when a SQL statement is executed.

The name can subsequently be queried from database administration views such as V$SESSION. It can be used for tracing and monitoring such as with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.

The value may be retained across persistent connections.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

module_name

User chosen string up to 48 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Oracle version requirement
This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Caution

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

Examples

Example #1 Setting the module name

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the module
oci_set_module_name($c, 'Home Page');

// Code that causes a roundtrip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);
?>
// While the script is running, the administrator can see the
// modules in use:

sqlplus system/welcome
SQL> select module from v$session;

See Also

  • oci_set_action() - Sets the action name
  • oci_set_client_info() - Sets the client information
  • oci_set_client_identifier() - Sets the client identifier

oci_set_edition
oci_set_prefetch
OCI8 Functions


Sets number of rows to be prefetched by queries

oci_set_module_name
oci_statement_type
OCI8 Functions
PHP Manual

oci_set_prefetch

(PHP 5, PECL OCI8 >= 1.1.0)

oci_set_prefetch — Sets number of rows to be prefetched by queries

Description

bool oci_set_prefetch ( resource $statement , int $rows )

Sets the number of rows to be buffered by the Oracle Client libraries after a successful query call to oci_execute() and for each subsequent internal fetch request to the database. For queries returning a large number of rows, performance can be significantly improved by increasing the prefetch count above the default oci8.default_prefetch value.

Prefetching is Oracle's efficient way of returning more than one data row from the database in each network request. This can result in better network and CPU utilization. The buffering of rows is internal to OCI8 and the behavior of OCI8 fetching functions is unchanged regardless of the prefetch count. For example, oci_fetch_row() will always return one row. The prefetch buffer is per-statement and is not used by re-executed statements or by other connections.

Call oci_set_prefetch() before calling oci_execute().

A tuning goal is to set the prefetch value to a reasonable size for the network and database to handle. For queries returning a very large number of rows, overall system efficiency might be better if rows are retrieved from the database in several chunks (i.e set the prefetch value smaller than the number of rows). This allows the database to handle other users' statements while the PHP script is processing the current set of rows.

Query prefetching was introduced in Oracle 8i. REF CURSOR prefetching was introduced in Oracle 11gR2 and occurs when PHP is linked with Oracle 11gR2 Client libraries and connected to 11gR2 or previous versions of the database. Nested cursor prefetching was introduced in Oracle 11gR2 and requires both the Oracle Client libraries and the database to be version 11gR2.

Prefetching is not supported when queries contain LONG or LOB columns. The prefetch value is ignored and single-row fetches will be used in all the situations when prefetching is not supported.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

rows

The number of rows to be prefetched, >= 0

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
PHP 5.3.2 (PECL OCI8 1.4) | Before this release, rows must be >= 1.
PHP 5.3 (PECL OCI8 1.3.4) | Before this release, prefetching was limited to the lesser of rows rows and 1024 * rows bytes. The byte size restriction has now been removed.

Examples

Example #1 Changing the default prefetch value for a query

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM myverybigtable');
oci_set_prefetch($stid, 300);  // Set before calling oci_execute()
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Changing the default prefetch for a REF CURSOR fetch

<?php
/*
  Create the PL/SQL stored procedure as:

  CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
  BEGIN
    OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
  END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Change the prefetch before executing the cursor.
// REF CURSOR prefetching works when PHP is linked with Oracle 11gR2 Client libraries
oci_set_prefetch($refcur, 200);
oci_execute($refcur);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);

?>

If PHP OCI8 fetches from a REF CURSOR and then passes the REF CURSOR back to a second PL/SQL procedure for further processing, then set the REF CURSOR prefetch count to 0 to avoid rows being "lost" from the result set. The prefetch value is the number of extra rows fetched in each OCI8 internal request to the database, so setting it to 0 means only fetch one row at a time.

Example #3 Setting the prefetch value when passing a REF CURSOR back to Oracle

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/orcl');

// get the REF CURSOR
$stid = oci_parse($conn, 'BEGIN myproc(:rc_out); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc_out', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Display two rows, but don't prefetch any extra rows otherwise
// those extra rows would not be passed back to myproc_use_rc().
// A prefetch value of 0 is allowed in PHP 5.3.2 and PECL OCI8 1.4
oci_set_prefetch($refcur, 0);
oci_execute($refcur);
$row = oci_fetch_array($refcur);
var_dump($row);
$row = oci_fetch_array($refcur);
var_dump($row);

// pass the REF CURSOR to myproc_use_rc() to do more data processing
// with the result set
$stid = oci_parse($conn, 'begin myproc_use_rc(:rc_in); end;');
oci_bind_by_name($stid, ':rc_in', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

?>

Notes

Note: In PHP versions before 5.0.0 use ocisetprefetch() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci8.default_prefetch ini option

oci_set_module_name
oci_statement_type
OCI8 Functions


Returns the type of a statement

oci_set_prefetch
OCI8 Obsolete Aliases and Functions
OCI8 Functions
PHP Manual

oci_statement_type

(PHP 5, PECL OCI8 >= 1.1.0)

oci_statement_type — Returns the type of a statement

Description

string oci_statement_type ( resource $statement )

Returns a keyword identifying the type of the OCI8 statement .

Parameters

statement

A valid OCI8 statement identifier from oci_parse().

Return Values

Returns the type of statement as one of the following strings.

Statement type
Return String | Notes
ALTER |
BEGIN |
CALL | Introduced in PHP 5.2.1 (PECL OCI8 1.2.3)
CREATE |
DECLARE |
DELETE |
DROP |
INSERT |
SELECT |
UPDATE |
UNKNOWN |

Returns FALSE on error.

Examples

Example #1 oci_statement_type() example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'DELETE FROM departments WHERE department_id = 130;');
if (oci_statement_type($stid) == "DELETE") {
    trigger_error('You are not allowed to delete from this table', E_USER_ERROR);
}
else {
    oci_execute($stid);  // delete the row
}

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note: In PHP versions before 5.0.0 you must use ocistatementtype() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

oci_set_prefetch
OCI8 Obsolete Aliases and Functions
OCI8 Functions


Alias of oci_bind_by_name

OCI8 Obsolete Aliases and Functions
ocicancel
OCI8 Obsolete Aliases and Functions
PHP Manual

ocibindbyname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocibindbyname — Alias of oci_bind_by_name()

Description

This function is an alias of: oci_bind_by_name().

OCI8 Obsolete Aliases and Functions
ocicancel
OCI8 Obsolete Aliases and Functions


Alias of oci_cancel

ocibindbyname
ocicloselob
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicancel

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicancel — Alias of oci_cancel()

Description

This function is an alias of: oci_cancel().

ocibindbyname
ocicloselob
OCI8 Obsolete Aliases and Functions


Alias of

ocicancel
ocicollappend
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicloselob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicloselob — Alias of OCI-Lob->close

Description

This function is an alias of: OCI-Lob->close.

ocicancel
ocicollappend
OCI8 Obsolete Aliases and Functions


Alias of

ocicloselob
ocicollassign
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollappend

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollappend — Alias of OCI-Collection->append

Description

This function is an alias of: OCI-Collection->append.

ocicloselob
ocicollassign
OCI8 Obsolete Aliases and Functions


Alias of

ocicollappend
ocicollassignelem
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollassign

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicollassign — Alias of OCI-Collection->assign

Description

This function is an alias of: OCI-Collection->assign.

ocicollappend
ocicollassignelem
OCI8 Obsolete Aliases and Functions


Alias of

ocicollassign
ocicollgetelem
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollassignelem — Alias of OCI-Collection->assignElem

Description

This function is an alias of: OCI-Collection->assignElem.

ocicollassign
ocicollgetelem
OCI8 Obsolete Aliases and Functions


Alias of

ocicollassignelem
ocicollmax
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollgetelem — Alias of OCI-Collection->getElem

Description

This function is an alias of: OCI-Collection->getElem.

ocicollassignelem
ocicollmax
OCI8 Obsolete Aliases and Functions


Alias of

ocicollgetelem
ocicollsize
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollmax

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollmax — Alias of OCI-Collection->max

Description

This function is an alias of: OCI-Collection->max.

ocicollgetelem
ocicollsize
OCI8 Obsolete Aliases and Functions


Alias of

ocicollmax
ocicolltrim
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollsize

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollsize — Alias of OCI-Collection->size

Description

This function is an alias of: OCI-Collection->size.

ocicollmax
ocicolltrim
OCI8 Obsolete Aliases and Functions


Alias of

ocicollsize
ocicolumnisnull
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolltrim

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicolltrim — Alias of OCI-Collection->trim

Description

This function is an alias of: OCI-Collection->trim.

ocicollsize
ocicolumnisnull
OCI8 Obsolete Aliases and Functions


Alias of oci_field_is_null

ocicolltrim
ocicolumnname
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnisnull

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnisnull — Alias of oci_field_is_null()

Description

This function is an alias of: oci_field_is_null().

ocicolltrim
ocicolumnname
OCI8 Obsolete Aliases and Functions


Alias of oci_field_name

ocicolumnisnull
ocicolumnprecision
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnname — Alias of oci_field_name()

Description

This function is an alias of: oci_field_name().

ocicolumnisnull
ocicolumnprecision
OCI8 Obsolete Aliases and Functions


Alias of oci_field_precision

ocicolumnname
ocicolumnscale
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnprecision

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnprecision — Alias of oci_field_precision()

Description

This function is an alias of: oci_field_precision().

ocicolumnname
ocicolumnscale
OCI8 Obsolete Aliases and Functions


Alias of oci_field_scale

ocicolumnprecision
ocicolumnsize
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnscale

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnscale — Alias of oci_field_scale()

Description

This function is an alias of: oci_field_scale().

ocicolumnprecision
ocicolumnsize
OCI8 Obsolete Aliases and Functions


Alias of oci_field_size

ocicolumnscale
ocicolumntype
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnsize

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnsize — Alias of oci_field_size()

Description

This function is an alias of: oci_field_size().

ocicolumnscale
ocicolumntype
OCI8 Obsolete Aliases and Functions


Alias of oci_field_type

ocicolumnsize
ocicolumntyperaw
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumntype

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumntype — Alias of oci_field_type()

Description

This function is an alias of: oci_field_type().

ocicolumnsize
ocicolumntyperaw
OCI8 Obsolete Aliases and Functions


Alias of oci_field_type_raw

ocicolumntype
ocicommit
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumntyperaw

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumntyperaw — Alias of oci_field_type_raw()

Description

This function is an alias of: oci_field_type_raw().

ocicolumntype
ocicommit
OCI8 Obsolete Aliases and Functions


Alias of oci_commit

ocicolumntyperaw
ocidefinebyname
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicommit

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicommit — Alias of oci_commit()

Description

This function is an alias of: oci_commit().

ocicolumntyperaw
ocidefinebyname
OCI8 Obsolete Aliases and Functions


Alias of oci_define_by_name

ocicommit
ocierror
OCI8 Obsolete Aliases and Functions
PHP Manual

ocidefinebyname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocidefinebyname — Alias of oci_define_by_name()

Description

This function is an alias of: oci_define_by_name().

ocicommit
ocierror
OCI8 Obsolete Aliases and Functions


Alias of oci_error

ocidefinebyname
ociexecute
OCI8 Obsolete Aliases and Functions
PHP Manual

ocierror

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocierror — Alias of oci_error()

Description

This function is an alias of: oci_error().

ocidefinebyname
ociexecute
OCI8 Obsolete Aliases and Functions


Alias of oci_execute

ocierror
ocifetch
OCI8 Obsolete Aliases and Functions
PHP Manual

ociexecute

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociexecute — Alias of oci_execute()

Description

This function is an alias of: oci_execute().

ocierror
ocifetch
OCI8 Obsolete Aliases and Functions


Alias of oci_fetch

ociexecute
ocifetchinto
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifetch

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetch — Alias of oci_fetch()

Description

This function is an alias of: oci_fetch().

ociexecute
ocifetchinto
OCI8 Obsolete Aliases and Functions


Fetches the next row into an array (deprecated)

ocifetch
ocifetchstatement
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifetchinto

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetchinto — Fetches the next row into an array (deprecated)

Description

int ocifetchinto ( resource $statement , array &$result [, int $mode ] )

This function is deprecated. Recommended alternatives:
oci_fetch_array(), oci_fetch_object(),
oci_fetch_assoc() and
oci_fetch_row().

ocifetch
ocifetchstatement
OCI8 Obsolete Aliases and Functions


Alias of oci_fetch_all

ocifetchinto
ocifreecollection
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifetchstatement

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetchstatement — Alias of oci_fetch_all()

Description

This function is an alias of: oci_fetch_all().

ocifetchinto
ocifreecollection
OCI8 Obsolete Aliases and Functions


Alias of

ocifetchstatement
ocifreecursor
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreecollection

(PHP 4 >= 4.0.7, PHP 5, PECL OCI8 >= 1.0.0)

ocifreecollection — Alias of OCI-Collection->free

Description

This function is an alias of: OCI-Collection->free.

ocifetchstatement
ocifreecursor
OCI8 Obsolete Aliases and Functions


Alias of oci_free_statement

ocifreecollection
ocifreedesc
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreecursor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreecursor — Alias of oci_free_statement()

Description

This function is an alias of: oci_free_statement().

ocifreecollection
ocifreedesc
OCI8 Obsolete Aliases and Functions


Alias of

ocifreecursor
ocifreestatement
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreedesc

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreedesc — Alias of OCI-Lob->free

Description

This function is an alias of: OCI-Lob->free.

ocifreecursor
ocifreestatement
OCI8 Obsolete Aliases and Functions


Alias of oci_free_statement

ocifreedesc
ociinternaldebug
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreestatement

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreestatement — Alias of oci_free_statement()

Description

This function is an alias of: oci_free_statement().

ocifreedesc
ociinternaldebug
OCI8 Obsolete Aliases and Functions


Alias of oci_internal_debug

ocifreestatement
ociloadlob
OCI8 Obsolete Aliases and Functions
PHP Manual

ociinternaldebug

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociinternaldebug — Alias of oci_internal_debug()

Description

This function is an alias of: oci_internal_debug().

ocifreestatement
ociloadlob
OCI8 Obsolete Aliases and Functions


Alias of

ociinternaldebug
ocilogoff
OCI8 Obsolete Aliases and Functions
PHP Manual

ociloadlob

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociloadlob — Alias of OCI-Lob->load

Description

This function is an alias of: OCI-Lob->load.

ociinternaldebug
ocilogoff
OCI8 Obsolete Aliases and Functions


Alias of oci_close

ociloadlob
ocilogon
OCI8 Obsolete Aliases and Functions
PHP Manual

ocilogoff

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocilogoff — Alias of oci_close()

Description

This function is an alias of: oci_close().

ociloadlob
ocilogon
OCI8 Obsolete Aliases and Functions


Alias of oci_connect

ocilogoff
ocinewcollection
OCI8 Obsolete Aliases and Functions
PHP Manual

ocilogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocilogon — Alias of oci_connect()

Description

This function is an alias of: oci_connect().

ocilogoff
ocinewcollection
OCI8 Obsolete Aliases and Functions


Alias of oci_new_collection

ocilogon
ocinewcursor
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinewcollection

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocinewcollection — Alias of oci_new_collection()

Description

This function is an alias of: oci_new_collection().

ocilogon
ocinewcursor
OCI8 Obsolete Aliases and Functions


Alias of oci_new_cursor

ocinewcollection
ocinewdescriptor
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinewcursor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinewcursor — Alias of oci_new_cursor()

Description

This function is an alias of: oci_new_cursor().

ocinewcollection
ocinewdescriptor
OCI8 Obsolete Aliases and Functions


Alias of oci_new_descriptor

ocinewcursor
ocinlogon
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinewdescriptor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinewdescriptor — Alias of oci_new_descriptor()

Description

This function is an alias of: oci_new_descriptor().

ocinewcursor
ocinlogon
OCI8 Obsolete Aliases and Functions


Alias of oci_new_connect

ocinewdescriptor
ocinumcols
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinlogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinlogon — Alias of oci_new_connect()

Description

This function is an alias of: oci_new_connect().

ocinewdescriptor
ocinumcols
OCI8 Obsolete Aliases and Functions


Alias of oci_num_fields

ocinlogon
ociparse
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinumcols

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinumcols — Alias of oci_num_fields()

Description

This function is an alias of: oci_num_fields().

ocinlogon
ociparse
OCI8 Obsolete Aliases and Functions


Alias of oci_parse

ocinumcols
ociplogon
OCI8 Obsolete Aliases and Functions
PHP Manual

ociparse

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociparse — Alias of oci_parse()

Description

This function is an alias of: oci_parse().

ocinumcols
ociplogon
OCI8 Obsolete Aliases and Functions


Alias of oci_pconnect

ociparse
ociresult
OCI8 Obsolete Aliases and Functions
PHP Manual

ociplogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociplogon — Alias of oci_pconnect()

Description

This function is an alias of: oci_pconnect().

ociparse
ociresult
OCI8 Obsolete Aliases and Functions


Alias of oci_result

ociplogon
ocirollback
OCI8 Obsolete Aliases and Functions
PHP Manual

ociresult

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociresult — Alias of oci_result()

Description

This function is an alias of: oci_result().

ociplogon
ocirollback
OCI8 Obsolete Aliases and Functions


Alias of oci_rollback

ociresult
ocirowcount
OCI8 Obsolete Aliases and Functions
PHP Manual

ocirollback

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocirollback — Alias of oci_rollback()

Description

This function is an alias of: oci_rollback().

ociresult
ocirowcount
OCI8 Obsolete Aliases and Functions


Alias of oci_num_rows

ocirollback
ocisavelob
OCI8 Obsolete Aliases and Functions
PHP Manual

ocirowcount

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocirowcount — Alias of oci_num_rows()

Description

This function is an alias of: oci_num_rows().

ocirollback
ocisavelob
OCI8 Obsolete Aliases and Functions


Alias of

ocirowcount
ocisavelobfile
OCI8 Obsolete Aliases and Functions
PHP Manual

ocisavelob

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisavelob — Alias of OCI-Lob->save

Description

This function is an alias of: OCI-Lob->save.

ocirowcount
ocisavelobfile
OCI8 Obsolete Aliases and Functions


Alias of

ocisavelob
ociserverversion
OCI8 Obsolete Aliases and Functions
PHP Manual

ocisavelobfile

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisavelobfile — Alias of OCI-Lob->import

Description

This function is an alias of: OCI-Lob->import.

ocisavelob
ociserverversion
OCI8 Obsolete Aliases and Functions


Alias of oci_server_version

ocisavelobfile
ocisetprefetch
OCI8 Obsolete Aliases and Functions
PHP Manual

ociserverversion

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociserverversion — Alias of oci_server_version()

Description

This function is an alias of: oci_server_version().

ocisavelobfile
ocisetprefetch
OCI8 Obsolete Aliases and Functions


Alias of oci_set_prefetch

ociserverversion
ocistatementtype
OCI8 Obsolete Aliases and Functions
PHP Manual

ocisetprefetch

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisetprefetch — Alias of oci_set_prefetch()

Description

This function is an alias of: oci_set_prefetch().

ociserverversion
ocistatementtype
OCI8 Obsolete Aliases and Functions


Alias of oci_statement_type

ocisetprefetch
ociwritelobtofile
OCI8 Obsolete Aliases and Functions
PHP Manual

ocistatementtype

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocistatementtype — Alias of oci_statement_type()

Description

This function is an alias of: oci_statement_type().

ocisetprefetch
ociwritelobtofile
OCI8 Obsolete Aliases and Functions


Alias of

ocistatementtype
ociwritetemporarylob
OCI8 Obsolete Aliases and Functions
PHP Manual

ociwritelobtofile

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociwritelobtofile — Alias of OCI-Lob->export

Description

This function is an alias of: OCI-Lob->export.

ocistatementtype
ociwritetemporarylob
OCI8 Obsolete Aliases and Functions


Alias of

ociwritelobtofile
Ovrimos SQL
OCI8 Obsolete Aliases and Functions
PHP Manual

ociwritetemporarylob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ociwritetemporarylob — Alias of OCI-Lob->writeTemporary

Description

This function is an alias of: OCI-Lob->writeTemporary.

ociwritelobtofile
Ovrimos SQL
OCI8 Obsolete Aliases and Functions


Octal to decimal

mt_srand
pi
Math Functions
PHP Manual

octdec

(PHP 4, PHP 5)

octdec — Octal to decimal

Description

number octdec ( string $octal_string )

Returns the decimal equivalent of the octal number represented by the octal_string argument.

Parameters

octal_string

The octal string to convert

Return Values

The decimal representation of octal_string

Changelog

Version | Description
Since 4.1.0 | The function can now convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

Examples

Example #1 octdec() example

<?php
echo octdec('77') . "\n";
echo octdec(decoct(45));
?>

The above example will output:

63
45

See Also

  • decoct() - Decimal to octal
  • bindec() - Binary to decimal
  • hexdec() - Hexadecimal to decimal
  • base_convert() - Convert a number between arbitrary bases

mt_srand
pi
Math Functions


Toggle autocommit behaviour

ODBC Functions
odbc_binmode
ODBC Functions
PHP Manual

odbc_autocommit

(PHP 4, PHP 5)

odbc_autocommit — Toggle autocommit behaviour

Description

mixed odbc_autocommit ( resource $connection_id [, bool $OnOff = false ] )

Toggles autocommit behaviour.

By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

OnOff

If OnOff is TRUE, auto-commit is enabled, if it is FALSE auto-commit is disabled.

Return Values

Without the OnOff parameter, this function returns auto-commit status for connection_id . Non-zero is returned if auto-commit is on, 0 if it is off, or FALSE if an error occurs.

If OnOff is set, this function returns TRUE on success and FALSE on failure.

See Also

  • odbc_commit() - Commit an ODBC transaction
  • odbc_rollback() - Rollback a transaction

ODBC Functions
odbc_binmode
ODBC Functions


Handling of binary column data

odbc_autocommit
odbc_close_all
ODBC Functions
PHP Manual

odbc_binmode

(PHP 4, PHP 5)

odbc_binmode — Handling of binary column data

Description

bool odbc_binmode ( resource $result_id , int $mode )

Enables handling of binary column data. ODBC SQL types affected are BINARY, VARBINARY, and LONGVARBINARY.

When binary SQL data is converted to character C data, each byte (8 bits) of source data is represented as two ASCII characters. These characters are the ASCII character representation of the number in its hexadecimal form. For example, a binary 00000001 is converted to "01" and a binary 11111111 is converted to "FF".

LONGVARBINARY handling
binmode | longreadlen | result
ODBC_BINMODE_PASSTHRU | 0 | passthru
ODBC_BINMODE_RETURN | 0 | passthru
ODBC_BINMODE_CONVERT | 0 | passthru
ODBC_BINMODE_PASSTHRU | 0 | passthru
ODBC_BINMODE_PASSTHRU | >0 | passthru
ODBC_BINMODE_RETURN | >0 | return as is
ODBC_BINMODE_CONVERT | >0 | return as char

If odbc_fetch_into() is used, passthru means that an empty string is returned for these columns.

Parameters

result_id

The result identifier.

If result_id is 0, the settings apply as default for new results.

Note: Default for longreadlen is 4096 and mode defaults to ODBC_BINMODE_RETURN. Handling of binary long columns is also affected by odbc_longreadlen().

mode

Possible values for mode are:

  • ODBC_BINMODE_PASSTHRU: Passthru BINARY data
  • ODBC_BINMODE_RETURN: Return as is
  • ODBC_BINMODE_CONVERT: Convert to char and return

Return Values

Returns TRUE on success or FALSE on failure.

odbc_autocommit
odbc_close_all
ODBC Functions


Close an ODBC connection

odbc_close_all
odbc_columnprivileges
ODBC Functions
PHP Manual

odbc_close

(PHP 4, PHP 5)

odbc_close — Close an ODBC connection

Description

void odbc_close ( resource $connection_id )

Closes down the connection to the database server.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

No value is returned.

Notes

Note: This function will fail if there are open transactions on this connection. The connection will remain open in this case.

odbc_close_all
odbc_columnprivileges
ODBC Functions


Close all ODBC connections

odbc_binmode
odbc_close
ODBC Functions
PHP Manual

odbc_close_all

(PHP 4, PHP 5)

odbc_close_all — Close all ODBC connections

Description

void odbc_close_all ( void )

odbc_close_all() will close down all connections to database server(s).

Parameters

This function has no parameters.

Return Values

No value is returned.

Notes

Note: This function will fail if there are open transactions on a connection. This connection will remain open in this case.

odbc_binmode
odbc_close
ODBC Functions


Lists columns and associated privileges for the given table

odbc_close
odbc_columns
ODBC Functions
PHP Manual

odbc_columnprivileges

(PHP 4, PHP 5)

odbc_columnprivileges — Lists columns and associated privileges for the given table

Description

resource odbc_columnprivileges ( resource $connection_id , string $qualifier , string $owner , string $table_name , string $column_name )

Lists columns and associated privileges for the given table.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner.

table_name

The table name.

column_name

The column_name argument accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

The owner , table_name , and column_name accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Return Values

Returns an ODBC result identifier or FALSE on failure. This result identifier can be used to fetch a list of columns and associated privileges.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • GRANTOR
  • GRANTEE
  • PRIVILEGE
  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

odbc_close
odbc_columns
ODBC Functions


Lists the column names in specified tables

odbc_columnprivileges
odbc_commit
ODBC Functions
PHP Manual

odbc_columns

(PHP 4, PHP 5)

odbc_columns — Lists the column names in specified tables

Description

resource odbc_columns ( resource $connection_id [, string $qualifier [, string $schema [, string $table_name [, string $column_name ]]]] )

Lists all columns in the requested range.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

schema

The owner.

table_name

The table name.

column_name

The column name.

The schema , table_name , and column_name accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_SCHEM
  • TABLE_NAME
  • COLUMN_NAME
  • DATA_TYPE
  • TYPE_NAME
  • PRECISION
  • LENGTH
  • SCALE
  • RADIX
  • NULLABLE
  • REMARKS

The result set is ordered by TABLE_QUALIFIER, TABLE_SCHEM and TABLE_NAME.

See Also

  • odbc_columnprivileges() - Lists columns and associated privileges for the given table to retrieve associated privileges

odbc_columnprivileges
odbc_commit
ODBC Functions


Commit an ODBC transaction

odbc_columns
odbc_connect
ODBC Functions
PHP Manual

odbc_commit

(PHP 4, PHP 5)

odbc_commit — Commit an ODBC transaction

Description

bool odbc_commit ( resource $connection_id )

Commits all pending transactions on the connection.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

Returns TRUE on success or FALSE on failure.

odbc_columns
odbc_connect
ODBC Functions


Connect to a datasource

odbc_commit
odbc_cursor
ODBC Functions
PHP Manual

odbc_connect

(PHP 4, PHP 5)

odbc_connect — Connect to a datasource

Description

resource odbc_connect ( string $dsn , string $user , string $password [, int $cursor_type ] )

The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once as long as they either use different db or different credentials.

With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.

Parameters

dsn

The database source name for the connection. Alternatively, a DNS-less connection string can be used.

user

The username.

password

The password.

cursor_type

This sets the type of cursor to be used for this connection. This parameter is not normally needed, but can be useful for working around problems with some ODBC drivers.

The following constants are defined for cursortype:

  • SQL_CUR_USE_IF_NEEDED
  • SQL_CUR_USE_ODBC
  • SQL_CUR_USE_DRIVER
  • SQL_CUR_DEFAULT

Return Values

Returns an ODBC connection id or 0 (FALSE) on error.

Examples

Example #1 DNS-less connections

<?php
// Microsoft SQL Server using the SQL Native Client 10.0 ODBC Driver - allows connection to SQL 7, 2000, 2005 and 2008
$connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);

// Microsoft Access
$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

// Microsoft Excel
$excelFile = realpath('C:/ExcelData.xls');
$excelDir = dirname($excelFile);
$connection = odbc_connect("Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=$excelFile;DefaultDir=$excelDir" , '', '');
?>

See Also

  • For persistent connections: odbc_pconnect() - Open a persistent database connection

odbc_commit
odbc_cursor
ODBC Functions


Get cursorname

odbc_connect
odbc_data_source
ODBC Functions
PHP Manual

odbc_cursor

(PHP 4, PHP 5)

odbc_cursor — Get cursorname

Description

string odbc_cursor ( resource $result_id )

Gets the cursorname for the given result_id.

Parameters

result_id

The result identifier.

Return Values

Returns the cursor name, as a string.

odbc_connect
odbc_data_source
ODBC Functions


Returns information about a current connection

odbc_cursor
odbc_do
ODBC Functions
PHP Manual

odbc_data_source

(PHP 4 >= 4.3.0, PHP 5)

odbc_data_source — Returns information about a current connection

Description

array odbc_data_source ( resource $connection_id , int $fetch_type )

This function will return the list of available DNS (after calling it several times).

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

fetch_type

The fetch_type can be one of two constant types: SQL_FETCH_FIRST, SQL_FETCH_NEXT. Use SQL_FETCH_FIRST the first time this function is called, thereafter use the SQL_FETCH_NEXT.

Return Values

Returns FALSE on error, and an array upon success.

odbc_cursor
odbc_do
ODBC Functions


Alias of odbc_exec

odbc_data_source
odbc_error
ODBC Functions
PHP Manual

odbc_do

(PHP 4, PHP 5)

odbc_do — Alias of odbc_exec()

Description

This function is an alias of: odbc_exec().

odbc_data_source
odbc_error
ODBC Functions


Get the last error code

odbc_do
odbc_errormsg
ODBC Functions
PHP Manual

odbc_error

(PHP 4 >= 4.0.5, PHP 5)

odbc_error — Get the last error code

Description

string odbc_error ([ resource $connection_id ] )

Returns a six-digit ODBC state, or an empty string if there has been no errors.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

This function returns meaningful value only if last odbc query failed (i.e. odbc_exec() returned FALSE).

See Also

  • odbc_errormsg() - Get the last error message
  • odbc_exec() - Prepare and execute a SQL statement

odbc_do
odbc_errormsg
ODBC Functions


Get the last error message

odbc_error
odbc_exec
ODBC Functions
PHP Manual

odbc_errormsg

(PHP 4 >= 4.0.5, PHP 5)

odbc_errormsg — Get the last error message

Description

string odbc_errormsg ([ resource $connection_id ] )

Returns a string containing the last ODBC error message, or an empty string if there has been no errors.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

This function returns meaningful value only if last odbc query failed (i.e. odbc_exec() returned FALSE).

See Also

  • odbc_error() - Get the last error code
  • odbc_exec() - Prepare and execute a SQL statement

odbc_error
odbc_exec
ODBC Functions


Prepare and execute a SQL statement

odbc_errormsg
odbc_execute
ODBC Functions
PHP Manual

odbc_exec

(PHP 4, PHP 5)

odbc_exec — Prepare and execute a SQL statement

Description

resource odbc_exec ( resource $connection_id , string $query_string [, int $flags ] )

Sends an SQL statement to the database server.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

query_string

The SQL statement.

flags

This parameter is currently not used.

Return Values

Returns an ODBC result identifier if the SQL command was executed successfully, or FALSE on error.

See Also

  • odbc_prepare() - Prepares a statement for execution
  • odbc_execute() - Execute a prepared statement

odbc_errormsg
odbc_execute
ODBC Functions


Execute a prepared statement

odbc_exec
odbc_fetch_array
ODBC Functions
PHP Manual

odbc_execute

(PHP 4, PHP 5)

odbc_execute — Execute a prepared statement

Description

bool odbc_execute ( resource $result_id [, array $parameters_array ] )

Executes a statement prepared with odbc_prepare().

Parameters

result_id

The result id resource, from odbc_prepare().

parameters_array

Parameters in parameter_array will be substituted for placeholders in the prepared statement in order. Elements of this array will be converted to strings by calling this function.

Any parameters in parameter_array which start and end with single quotes will be taken as the name of a file to read and send to the database server as the data for the appropriate placeholder.

If you wish to store a string which actually begins and ends with single quotes, you must add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter from being taken as a file name. If this is not an option, then you must use another mechanism to store the string, such as executing the query directly with odbc_exec()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 odbc_execute() and odbc_prepare() example

In the following code, $success will only be TRUE if all three parameters to myproc are IN parameters:

<?php
$a = 1;
$b = 2;
$c = 3;
$stmt    = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$success = odbc_execute($stmt, array($a, $b, $c));
?>

If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, mssql for MS SQL Server, or oci8 for Oracle).

Changelog

Version | Description
4.2.0 | File reading is now subject to safe mode and open-basedir restrictions in parameters_array .
4.1.1 | Remote files are no longer supported in parameters_array .

See Also

  • odbc_prepare() - Prepares a statement for execution

odbc_exec
odbc_fetch_array
ODBC Functions


Fetch a result row as an associative array

odbc_execute
odbc_fetch_into
ODBC Functions
PHP Manual

odbc_fetch_array

(PHP 4 >= 4.0.2, PHP 5)

odbc_fetch_array — Fetch a result row as an associative array

Description

array odbc_fetch_array ( resource $result [, int $rownumber ] )

Fetch an associative array from an ODBC query. See the changelog below for when this function is available.

Parameters

result

The result resource from odbc_exec().

rownumber

Optionally choose which row number to retrieve.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Changelog

Version | Description
4.3.3 | This function exists when compiled with IBM DB2 or UnixODBC support.
4.3.2 | This function exists when compiled for Windows.
4.0.2 | This function exists when compiled with DBMaker support.

See Also

  • odbc_fetch_row() - Fetch a row
  • odbc_fetch_object() - Fetch a result row as an object
  • odbc_num_rows() - Number of rows in a result

odbc_execute
odbc_fetch_into
ODBC Functions


Fetch one result row into array

odbc_fetch_array
odbc_fetch_object
ODBC Functions
PHP Manual

odbc_fetch_into

(PHP 4, PHP 5)

odbc_fetch_into — Fetch one result row into array

Description

int odbc_fetch_into ( resource $result_id , array &$result_array [, int $rownumber ] )

Fetch one result row into array.

Parameters

result_id

The result resource.

result_array

The result array that can be of any type since it will be converted to type array. The array will contain the column values starting at array index 0.

rownumber

The row number.

Return Values

Returns the number of columns in the result; FALSE on error.

Changelog

Version | Description
4.2.0 | The result_array and rownumber parameters have been swapped. This allows the rownumber to be a constant again.
4.0.6 | The rownumber can no longer be passed in as a constant, but rather as a variable. This again changed in 4.2.0.
4.0.5 | The result_array parameter no longer needs to be passed in by reference.

Examples

Example #1 odbc_fetch_into() examples

<?php
$rc = odbc_fetch_into($res_id, $my_array);
?>

or

<?php
$rc = odbc_fetch_into($res_id, $my_array, 2);
?>

odbc_fetch_array
odbc_fetch_object
ODBC Functions


Fetch a result row as an object

odbc_fetch_into
odbc_fetch_row
ODBC Functions
PHP Manual

odbc_fetch_object

(PHP 4 >= 4.0.2, PHP 5)

odbc_fetch_object — Fetch a result row as an object

Description

object odbc_fetch_object ( resource $result [, int $rownumber ] )

Fetch an object from an ODBC query. See the changelog below for when this function is available.

Parameters

result

The result resource from odbc_exec().

rownumber

Optionally choose which row number to retrieve.

Return Values

Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.

Changelog

Version | Description
4.3.3 | This function exists when compiled with IBM DB2 or UnixODBC support.
4.3.2 | This function exists when compiled for Windows.
4.0.2 | This function exists when compiled with DBMaker support.

See Also

  • odbc_fetch_row() - Fetch a row
  • odbc_fetch_array() - Fetch a result row as an associative array
  • odbc_num_rows() - Number of rows in a result

odbc_fetch_into
odbc_fetch_row
ODBC Functions


Fetch a row

odbc_fetch_object
odbc_field_len
ODBC Functions
PHP Manual

odbc_fetch_row

(PHP 4, PHP 5)

odbc_fetch_row — Fetch a row

Description

bool odbc_fetch_row ( resource $result_id [, int $row_number ] )

Fetches a row of the data that was returned by odbc_do() or odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().

Parameters

result_id

The result identifier.

row_number

If row_number is not specified, odbc_fetch_row() will try to fetch the next row in the result set. Calls to odbc_fetch_row() with and without row_number can be mixed.

To step through the result more than once, you can call odbc_fetch_row() with row_number 1, and then continue doing odbc_fetch_row() without row_number to review the result. If a driver doesn't support fetching rows by number, the row_number parameter is ignored.

Return Values

Returns TRUE if there was a row, FALSE otherwise.

odbc_fetch_object
odbc_field_len
ODBC Functions


Get the length (precision) of a field

odbc_fetch_row
odbc_field_name
ODBC Functions
PHP Manual

odbc_field_len

(PHP 4, PHP 5)

odbc_field_len — Get the length (precision) of a field

Description

int odbc_field_len ( resource $result_id , int $field_number )

Gets the length of the field referenced by number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field name as a string, or FALSE on error.

See Also

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number

odbc_fetch_row
odbc_field_name
ODBC Functions


Get the columnname

odbc_field_len
odbc_field_num
ODBC Functions
PHP Manual

odbc_field_name

(PHP 4, PHP 5)

odbc_field_name — Get the columnname

Description

string odbc_field_name ( resource $result_id , int $field_number )

Gets the name of the field occupying the given column number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field name as a string, or FALSE on error.

odbc_field_len
odbc_field_num
ODBC Functions


Return column number

odbc_field_name
odbc_field_precision
ODBC Functions
PHP Manual

odbc_field_num

(PHP 4, PHP 5)

odbc_field_num — Return column number

Description

int odbc_field_num ( resource $result_id , string $field_name )

Gets the number of the column slot that corresponds to the named field in the given result identifier.

Parameters

result_id

The result identifier.

field_name

The field name.

Return Values

Returns the field number as a integer, or FALSE on error. Field numbering starts at 1.

odbc_field_name
odbc_field_precision
ODBC Functions


Alias of odbc_field_len

odbc_field_num
odbc_field_scale
ODBC Functions
PHP Manual

odbc_field_precision

(PHP 4, PHP 5)

odbc_field_precision — Alias of odbc_field_len()

Description

This function is an alias of: odbc_field_len().

See Also

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number.

odbc_field_num
odbc_field_scale
ODBC Functions


Get the scale of a field

odbc_field_precision
odbc_field_type
ODBC Functions
PHP Manual

odbc_field_scale

(PHP 4, PHP 5)

odbc_field_scale — Get the scale of a field

Description

int odbc_field_scale ( resource $result_id , int $field_number )

Gets the scale of the field referenced by number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field scale as a integer, or FALSE on error.

odbc_field_precision
odbc_field_type
ODBC Functions


Datatype of a field

odbc_field_scale
odbc_foreignkeys
ODBC Functions
PHP Manual

odbc_field_type

(PHP 4, PHP 5)

odbc_field_type — Datatype of a field

Description

string odbc_field_type ( resource $result_id , int $field_number )

Gets the SQL type of the field referenced by number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field type as a string, or FALSE on error.

odbc_field_scale
odbc_foreignkeys
ODBC Functions


Retrieves a list of foreign keys

odbc_field_type
odbc_free_result
ODBC Functions
PHP Manual

odbc_foreignkeys

(PHP 4, PHP 5)

odbc_foreignkeys — Retrieves a list of foreign keys

Description

resource odbc_foreignkeys ( resource $connection_id , string $pk_qualifier , string $pk_owner , string $pk_table , string $fk_qualifier , string $fk_owner , string $fk_table )

Retrieves a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

pk_qualifier

The primary key qualifier.

pk_owner

The primary key owner.

pk_table

The primary key table.

fk_qualifier

The foreign key qualifier.

fk_owner

The foreign key owner.

fk_table

The foreign key table.

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PKTABLE_QUALIFIER
  • PKTABLE_OWNER
  • PKTABLE_NAME
  • PKCOLUMN_NAME
  • FKTABLE_QUALIFIER
  • FKTABLE_OWNER
  • FKTABLE_NAME
  • FKCOLUMN_NAME
  • KEY_SEQ
  • UPDATE_RULE
  • DELETE_RULE
  • FK_NAME
  • PK_NAME

If pk_table contains a table name, odbc_foreignkeys() returns a result set containing the primary key of the specified table and all of the foreign keys that refer to it.

If fk_table contains a table name, odbc_foreignkeys() returns a result set containing all of the foreign keys in the specified table and the primary keys (in other tables) to which they refer.

If both pk_table and fk_table contain table names, odbc_foreignkeys() returns the foreign keys in the table specified in fk_table that refer to the primary key of the table specified in pk_table . This should be one key at most.

odbc_field_type
odbc_free_result
ODBC Functions


Free resources associated with a result

odbc_foreignkeys
odbc_gettypeinfo
ODBC Functions
PHP Manual

odbc_free_result

(PHP 4, PHP 5)

odbc_free_result — Free resources associated with a result

Description

bool odbc_free_result ( resource $result_id )

Free resources associated with a result.

odbc_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished.

Parameters

result_id

The result identifier.

Return Values

Always returns TRUE.

Notes

Note: If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before committing, all pending transactions are rolled back.

odbc_foreignkeys
odbc_gettypeinfo
ODBC Functions


Retrieves information about data types supported by the data source

odbc_free_result
odbc_longreadlen
ODBC Functions
PHP Manual

odbc_gettypeinfo

(PHP 4, PHP 5)

odbc_gettypeinfo — Retrieves information about data types supported by the data source

Description

resource odbc_gettypeinfo ( resource $connection_id [, int $data_type ] )

Retrieves information about data types supported by the data source.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

data_type

The data type, which can be used to restrict the information to a single data type.

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TYPE_NAME
  • DATA_TYPE
  • PRECISION
  • LITERAL_PREFIX
  • LITERAL_SUFFIX
  • CREATE_PARAMS
  • NULLABLE
  • CASE_SENSITIVE
  • SEARCHABLE
  • UNSIGNED_ATTRIBUTE
  • MONEY
  • AUTO_INCREMENT
  • LOCAL_TYPE_NAME
  • MINIMUM_SCALE
  • MAXIMUM_SCALE

The result set is ordered by DATA_TYPE and TYPE_NAME.

odbc_free_result
odbc_longreadlen
ODBC Functions


Handling of LONG columns

odbc_gettypeinfo
odbc_next_result
ODBC Functions
PHP Manual

odbc_longreadlen

(PHP 4, PHP 5)

odbc_longreadlen — Handling of LONG columns

Description

bool odbc_longreadlen ( resource $result_id , int $length )

Enables handling of LONG and LONGVARBINARY columns.

Parameters

result_id

The result identifier.

length

The number of bytes returned to PHP is controlled by the parameter length. If it is set to 0, Long column data is passed through to the client.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Handling of LONGVARBINARY columns is also affected by odbc_binmode().

odbc_gettypeinfo
odbc_next_result
ODBC Functions


Checks if multiple results are available

odbc_longreadlen
odbc_num_fields
ODBC Functions
PHP Manual

odbc_next_result

(PHP 4 >= 4.0.5, PHP 5)

odbc_next_result — Checks if multiple results are available

Description

bool odbc_next_result ( resource $result_id )

Checks if there are more result sets available as well as allowing access to the next result set via odbc_fetch_array(), odbc_fetch_row(), odbc_result(), etc.

Parameters

result_id

The result identifier.

Return Values

Returns TRUE if there are more result sets, FALSE otherwise.

Examples

Example #1 odbc_next_result()

<?php
$r_Connection = odbc_connect($dsn, $username, $password);

$s_SQL = <<<END_SQL
SELECT 'A'
SELECT 'B'
SELECT 'C'
END_SQL;

$r_Results = odbc_exec($r_Connection, $s_SQL);

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump first result set";
var_dump($a_Row1, $a_Row2);

echo "Get second results set ";
var_dump(odbc_next_result($r_Results));

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump second result set ";
var_dump($a_Row1, $a_Row2);

echo "Get third results set ";
var_dump(odbc_next_result($r_Results));

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump third result set ";
var_dump($a_Row1, $a_Row2);

echo "Try for a fourth result set ";
var_dump(odbc_next_result($r_Results));
?>

The above example will output:

Dump first result set array(1) {
  ["A"]=>
  string(1) "A"
}
bool(false)
Get second results set bool(true)
Dump second result set array(1) {
  ["B"]=>
  string(1) "B"
}
bool(false)
Get third results set bool(true)
Dump third result set array(1) {
  ["C"]=>
  string(1) "C"
}
bool(false)
Try for a fourth result set bool(false)

odbc_longreadlen
odbc_num_fields
ODBC Functions


Number of columns in a result

odbc_next_result
odbc_num_rows
ODBC Functions
PHP Manual

odbc_num_fields

(PHP 4, PHP 5)

odbc_num_fields — Number of columns in a result

Description

int odbc_num_fields ( resource $result_id )

Gets the number of fields (columns) in an ODBC result.

Parameters

result_id

The result identifier returned by odbc_exec().

Return Values

Returns the number of fields, or -1 on error.

odbc_next_result
odbc_num_rows
ODBC Functions


Number of rows in a result

odbc_num_fields
odbc_pconnect
ODBC Functions
PHP Manual

odbc_num_rows

(PHP 4, PHP 5)

odbc_num_rows — Number of rows in a result

Description

int odbc_num_rows ( resource $result_id )

Gets the number of rows in a result. For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. For a SELECT clause this can be the number of rows available.

Parameters

result_id

The result identifier returned by odbc_exec().

Return Values

Returns the number of rows in an ODBC result. This function will return -1 on error.

Notes

Note: Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.

odbc_num_fields
odbc_pconnect
ODBC Functions


Open a persistent database connection

odbc_num_rows
odbc_prepare
ODBC Functions
PHP Manual

odbc_pconnect

(PHP 4, PHP 5)

odbc_pconnect — Open a persistent database connection

Description

resource odbc_pconnect ( string $dsn , string $user , string $password [, int $cursor_type ] )

Opens a persistent database connection.

This function is much like odbc_connect(), except that the connection is not really closed when the script has finished. Future requests for a connection with the same dsn , user , password combination (via odbc_connect() and odbc_pconnect()) can reuse the persistent connection.

Parameters

See odbc_connect() for details.

Return Values

Returns an ODBC connection id or 0 (FALSE) on error.

Notes

Note: Persistent connections have no effect if PHP is used as a CGI program.

See Also

  • odbc_connect() - Connect to a datasource
  • Persistent Database Connections

odbc_num_rows
odbc_prepare
ODBC Functions


Prepares a statement for execution

odbc_pconnect
odbc_primarykeys
ODBC Functions
PHP Manual

odbc_prepare

(PHP 4, PHP 5)

odbc_prepare — Prepares a statement for execution

Description

resource odbc_prepare ( resource $connection_id , string $query_string )

Prepares a statement for execution. The result identifier can be used later to execute the statement with odbc_execute().

Some databases (such as IBM DB2, MS SQL Server, and Oracle) support stored procedures that accept parameters of type IN, INOUT, and OUT as defined by the ODBC specification. However, the Unified ODBC driver currently only supports parameters of type IN to stored procedures.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

query_string

The query string statement being prepared.

Return Values

Returns an ODBC result identifier if the SQL command was prepared successfully. Returns FALSE on error.

Examples

Example #1 odbc_execute() and odbc_prepare() example

In the following code, $success will only be TRUE if all three parameters to myproc are IN parameters:

<?php
$a = 1;
$b = 2;
$c = 3;
$stmt    = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$success = odbc_execute($stmt, array($a, $b, $c));
?>

If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, mssql for MS SQL Server, or oci8 for Oracle).

See Also

  • odbc_execute() - Execute a prepared statement

odbc_pconnect
odbc_primarykeys
ODBC Functions


Gets the primary keys for a table

odbc_prepare
odbc_procedurecolumns
ODBC Functions
PHP Manual

odbc_primarykeys

(PHP 4, PHP 5)

odbc_primarykeys — Gets the primary keys for a table

Description

resource odbc_primarykeys ( resource $connection_id , string $qualifier , string $owner , string $table )

Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

owner

table

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • COLUMN_NAME
  • KEY_SEQ
  • PK_NAME

odbc_prepare
odbc_procedurecolumns
ODBC Functions


Retrieve information about parameters to procedures

odbc_primarykeys
odbc_procedures
ODBC Functions
PHP Manual

odbc_procedurecolumns

(PHP 4, PHP 5)

odbc_procedurecolumns — Retrieve information about parameters to procedures

Description

resource odbc_procedurecolumns ( resource $connection_id )
resource odbc_procedurecolumns ( resource $connection_id , string $qualifier , string $owner , string $proc , string $column )

Retrieve information about parameters to procedures.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

proc

The proc. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

column

The column. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

Return Values

Returns the list of input and output parameters, as well as the columns that make up the result set for the specified procedures. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PROCEDURE_QUALIFIER
  • PROCEDURE_OWNER
  • PROCEDURE_NAME
  • COLUMN_NAME
  • COLUMN_TYPE
  • DATA_TYPE
  • TYPE_NAME
  • PRECISION
  • LENGTH
  • SCALE
  • RADIX
  • NULLABLE
  • REMARKS

The result set is ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME and COLUMN_TYPE.

odbc_primarykeys
odbc_procedures
ODBC Functions


Get the list of procedures stored in a specific data source

odbc_procedurecolumns
odbc_result_all
ODBC Functions
PHP Manual

odbc_procedures

(PHP 4, PHP 5)

odbc_procedures — Get the list of procedures stored in a specific data source

Description

resource odbc_procedures ( resource $connection_id )
resource odbc_procedures ( resource $connection_id , string $qualifier , string $owner , string $name )

Lists all procedures in the requested range.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

name

The name. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

Return Values

Returns an ODBC result identifier containing the information or FALSE on failure.

The result set has the following columns:

  • PROCEDURE_QUALIFIER
  • PROCEDURE_OWNER
  • PROCEDURE_NAME
  • NUM_INPUT_PARAMS
  • NUM_OUTPUT_PARAMS
  • NUM_RESULT_SETS
  • REMARKS
  • PROCEDURE_TYPE

odbc_procedurecolumns
odbc_result_all
ODBC Functions


Get result data

odbc_result_all
odbc_rollback
ODBC Functions
PHP Manual

odbc_result

(PHP 4, PHP 5)

odbc_result — Get result data

Description

mixed odbc_result ( resource $result_id , mixed $field )

Get result data

Parameters

result_id

The ODBC resource.

field

The field name being retrieved. It can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field.

Return Values

Returns the string contents of the field, FALSE on error, NULL for NULL data, or TRUE for binary data.

Examples

The first call to odbc_result() returns the value of the third field in the current record of the query result. The second function call to odbc_result() returns the value of the field whose field name is "val" in the current record of the query result. An error occurs if a column number parameter for a field is less than one or exceeds the number of columns (or fields) in the current record. Similarly, an error occurs if a field with a name that is not one of the fieldnames of the table(s) that is(are) being queried.

Example #1 odbc_result() examples

<?php
$item_3   = odbc_result($Query_ID, 3);
$item_val = odbc_result($Query_ID, "val");
?>

Notes

Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().

odbc_result_all
odbc_rollback
ODBC Functions


Print result as HTML table

odbc_procedures
odbc_result
ODBC Functions
PHP Manual

odbc_result_all

(PHP 4, PHP 5)

odbc_result_all — Print result as HTML table

Description

int odbc_result_all ( resource $result_id [, string $format ] )

Prints all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format.

Parameters

result_id

The result identifier.

format

Additional overall table formatting.

Return Values

Returns the number of rows in the result or FALSE on error.

odbc_procedures
odbc_result
ODBC Functions


Rollback a transaction

odbc_result
odbc_setoption
ODBC Functions
PHP Manual

odbc_rollback

(PHP 4, PHP 5)

odbc_rollback — Rollback a transaction

Description

bool odbc_rollback ( resource $connection_id )

Rolls back all pending statements on the connection.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

Returns TRUE on success or FALSE on failure.

odbc_result
odbc_setoption
ODBC Functions


Adjust ODBC settings

odbc_rollback
odbc_specialcolumns
ODBC Functions
PHP Manual

odbc_setoption

(PHP 4, PHP 5)

odbc_setoption — Adjust ODBC settings

Description

bool odbc_setoption ( resource $id , int $function , int $option , int $param )

This function allows fiddling with the ODBC options for a particular connection or query result. It was written to help find work around to problems in quirky ODBC drivers. You should probably only use this function if you are an ODBC programmer and understand the effects the various options will have. You will certainly need a good ODBC reference to explain all the different options and values that can be used. Different driver versions support different options.

Because the effects may vary depending on the ODBC driver, use of this function in scripts to be made publicly available is strongly discouraged. Also, some ODBC options are not available to this function because they must be set before the connection is established or the query is prepared. However, if on a particular job it can make PHP work so your boss doesn't tell you to use a commercial product, that's all that really matters.

Parameters

id

Is a connection id or result id on which to change the settings. For SQLSetConnectOption(), this is a connection id. For SQLSetStmtOption(), this is a result id.

function

Is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().

option

The option to set.

param

The value for the given option .

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 odbc_setoption() examples

<?php
// 1. Option 102 of SQLSetConnectOption() is SQL_AUTOCOMMIT.
//    Value 1 of SQL_AUTOCOMMIT is SQL_AUTOCOMMIT_ON.
//    This example has the same effect as
//    odbc_autocommit($conn, true);

odbc_setoption($conn, 1, 102, 1);

// 2. Option 0 of SQLSetStmtOption() is SQL_QUERY_TIMEOUT.
//    This example sets the query to timeout after 30 seconds.

$result = odbc_prepare($conn, $sql);
odbc_setoption($result, 2, 0, 30);
odbc_execute($result);
?>

odbc_rollback
odbc_specialcolumns
ODBC Functions


Retrieves special columns

odbc_setoption
odbc_statistics
ODBC Functions
PHP Manual

odbc_specialcolumns

(PHP 4, PHP 5)

odbc_specialcolumns — Retrieves special columns

Description

resource odbc_specialcolumns ( resource $connection_id , int $type , string $qualifier , string $owner , string $table , int $scope , int $nullable )

Retrieves either the optimal set of columns that uniquely identifies a row in the table, or columns that are automatically updated when any value in the row is updated by a transaction.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

type
When the type argument is SQL_BEST_ROWID, odbc_specialcolumns() returns the column or columns that uniquely identify each row in the table. When the type argument is SQL_ROWVER, odbc_specialcolumns() returns the column or columns in the specified table, if any, that are automatically updated by the data source when any value in the row is updated by any transaction.
qualifier

The qualifier.

owner

The owner.

table

The table.

scope

The scope, which orders the result set.

nullable

The nullable option.

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • SCOPE
  • COLUMN_NAME
  • DATA_TYPE
  • TYPE_NAME
  • PRECISION
  • LENGTH
  • SCALE
  • PSEUDO_COLUMN

odbc_setoption
odbc_statistics
ODBC Functions


Retrieve statistics about a table

odbc_specialcolumns
odbc_tableprivileges
ODBC Functions
PHP Manual

odbc_statistics

(PHP 4, PHP 5)

odbc_statistics — Retrieve statistics about a table

Description

resource odbc_statistics ( resource $connection_id , string $qualifier , string $owner , string $table_name , int $unique , int $accuracy )

Get statistics about a table and its indexes.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner.

table_name

The table name.

unique

The unique attribute.

accuracy

The accuracy.

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • NON_UNIQUE
  • INDEX_QUALIFIER
  • INDEX_NAME
  • TYPE
  • SEQ_IN_INDEX
  • COLUMN_NAME
  • COLLATION
  • CARDINALITY
  • PAGES
  • FILTER_CONDITION

The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME and SEQ_IN_INDEX.

odbc_specialcolumns
odbc_tableprivileges
ODBC Functions


Lists tables and the privileges associated with each table

odbc_statistics
odbc_tables
ODBC Functions
PHP Manual

odbc_tableprivileges

(PHP 4, PHP 5)

odbc_tableprivileges — Lists tables and the privileges associated with each table

Description

resource odbc_tableprivileges ( resource $connection_id , string $qualifier , string $owner , string $name )

Lists tables in the requested range and the privileges associated with each table.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. Accepts the following search patterns: ('%' to match zero or more characters and '_' to match a single character)

name

The name. Accepts the following search patterns: ('%' to match zero or more characters and '_' to match a single character)

Return Values

An ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • GRANTOR
  • GRANTEE
  • PRIVILEGE
  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

odbc_statistics
odbc_tables
ODBC Functions


Get the list of table names stored in a specific data source

odbc_tableprivileges
PDO
ODBC Functions
PHP Manual

odbc_tables

(PHP 4, PHP 5)

odbc_tables — Get the list of table names stored in a specific data source

Description

resource odbc_tables ( resource $connection_id [, string $qualifier [, string $owner [, string $name [, string $types ]]]] )

Lists all tables in the requested range.

To support enumeration of qualifiers, owners, and table types, the following special semantics for the qualifier , owner , name , and table_type are available:

  • If qualifier is a single percent character (%) and owner and name are empty strings, then the result set contains a list of valid qualifiers for the data source. (All columns except the TABLE_QUALIFIER column contain NULLs.)
  • If owner is a single percent character (%) and qualifier and name are empty strings, then the result set contains a list of valid owners for the data source. (All columns except the TABLE_OWNER column contain NULLs.)
  • If table_type is a single percent character (%) and qualifier , owner and name are empty strings, then the result set contains a list of valid table types for the data source. (All columns except the TABLE_TYPE column contain NULLs.)

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. Accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

name

The name. Accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

types

If table_type is not an empty string, it must contain a list of comma-separated values for the types of interest; each value may be enclosed in single quotes (') or unquoted. For example, "'TABLE','VIEW'" or "TABLE, VIEW". If the data source does not support a specified table type, odbc_tables() does not return any results for that type.

Return Values

Returns an ODBC result identifier containing the information or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • TABLE_TYPE
  • REMARKS

The result set is ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

See Also

  • odbc_tableprivileges() - Lists tables and the privileges associated with each table

odbc_tableprivileges
PDO
ODBC Functions


Generate OpenAL buffer

OpenAL Functions
openal_buffer_data
OpenAL Functions
PHP Manual

openal_buffer_create

(PECL openal >= 0.1.0)

openal_buffer_create — Generate OpenAL buffer

Description

resource openal_buffer_create ( void )

Return Values

Returns an Open AL(Buffer) resource on success or FALSE on failure.

See Also

  • openal_buffer_loadwav() - Load a .wav file into a buffer
  • openal_buffer_data() - Load a buffer with data

OpenAL Functions
openal_buffer_data
OpenAL Functions


Load a buffer with data

openal_buffer_create
openal_buffer_destroy
OpenAL Functions
PHP Manual

openal_buffer_data

(PECL openal >= 0.1.0)

openal_buffer_data — Load a buffer with data

Description

bool openal_buffer_data ( resource $buffer , int $format , string $data , int $freq )

Parameters

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

format

Format of data , one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 and AL_FORMAT_STEREO16

data

Block of binary audio data in the format and freq specified.

freq

Frequency of data given in Hz.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_buffer_loadwav() - Load a .wav file into a buffer
  • openal_stream() - Begin streaming on a source

openal_buffer_create
openal_buffer_destroy
OpenAL Functions


Destroys an OpenAL buffer

openal_buffer_data
openal_buffer_get
OpenAL Functions
PHP Manual

openal_buffer_destroy

(PECL openal >= 0.1.0)

openal_buffer_destroy — Destroys an OpenAL buffer

Description

bool openal_buffer_destroy ( resource $buffer )

Parameters

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_buffer_create() - Generate OpenAL buffer

openal_buffer_data
openal_buffer_get
OpenAL Functions


Retrieve an OpenAL buffer property

openal_buffer_destroy
openal_buffer_loadwav
OpenAL Functions
PHP Manual

openal_buffer_get

(PECL openal >= 0.1.0)

openal_buffer_get — Retrieve an OpenAL buffer property

Description

int openal_buffer_get ( resource $buffer , int $property )

Parameters

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

property

Specific property, one of: AL_FREQUENCY, AL_BITS, AL_CHANNELS and AL_SIZE.

Return Values

Returns an integer value appropriate to the property requested or FALSE on failure.

See Also

  • openal_buffer_create() - Generate OpenAL buffer

openal_buffer_destroy
openal_buffer_loadwav
OpenAL Functions


Load a .wav file into a buffer

openal_buffer_get
openal_context_create
OpenAL Functions
PHP Manual

openal_buffer_loadwav

(PECL openal >= 0.1.0)

openal_buffer_loadwav — Load a .wav file into a buffer

Description

bool openal_buffer_loadwav ( resource $buffer , string $wavfile )

Parameters

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

wavfile

Path to .wav file on local file system.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_buffer_data() - Load a buffer with data
  • openal_stream() - Begin streaming on a source

openal_buffer_get
openal_context_create
OpenAL Functions


Create an audio processing context

openal_buffer_loadwav
openal_context_current
OpenAL Functions
PHP Manual

openal_context_create

(PECL openal >= 0.1.0)

openal_context_create — Create an audio processing context

Description

resource openal_context_create ( resource $device )

Parameters

device

An Open AL(Device) resource (previously created by openal_device_open()).

Return Values

Returns an Open AL(Context) resource on success or FALSE on failure.

See Also

  • openal_device_open() - Initialize the OpenAL audio layer
  • openal_context_destroy() - Destroys a context

openal_buffer_loadwav
openal_context_current
OpenAL Functions


Make the specified context current

openal_context_create
openal_context_destroy
OpenAL Functions
PHP Manual

openal_context_current

(PECL openal >= 0.1.0)

openal_context_current — Make the specified context current

Description

bool openal_context_current ( resource $context )

Parameters

context

An Open AL(Context) resource (previously created by openal_context_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_context_create() - Create an audio processing context

openal_context_create
openal_context_destroy
OpenAL Functions


Destroys a context

openal_context_current
openal_context_process
OpenAL Functions
PHP Manual

openal_context_destroy

(PECL openal >= 0.1.0)

openal_context_destroy — Destroys a context

Description

bool openal_context_destroy ( resource $context )

Parameters

context

An Open AL(Context) resource (previously created by openal_context_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_context_create() - Create an audio processing context

openal_context_current
openal_context_process
OpenAL Functions


Process the specified context

openal_context_destroy
openal_context_suspend
OpenAL Functions
PHP Manual

openal_context_process

(PECL openal >= 0.1.0)

openal_context_process — Process the specified context

Description

bool openal_context_process ( resource $context )

Parameters

context

An Open AL(Context) resource (previously created by openal_context_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_context_create() - Create an audio processing context
  • openal_context_current() - Make the specified context current
  • openal_context_suspend() - Suspend the specified context

openal_context_destroy
openal_context_suspend
OpenAL Functions


Suspend the specified context

openal_context_process
openal_device_close
OpenAL Functions
PHP Manual

openal_context_suspend

(PECL openal >= 0.1.0)

openal_context_suspend — Suspend the specified context

Description

bool openal_context_suspend ( resource $context )

Parameters

context

An Open AL(Context) resource (previously created by openal_context_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_context_create() - Create an audio processing context
  • openal_context_current() - Make the specified context current
  • openal_context_process() - Process the specified context

openal_context_process
openal_device_close
OpenAL Functions


Close an OpenAL device

openal_context_suspend
openal_device_open
OpenAL Functions
PHP Manual

openal_device_close

(PECL openal >= 0.1.0)

openal_device_close — Close an OpenAL device

Description

bool openal_device_close ( resource $device )

Parameters

device

An Open AL(Device) resource (previously created by openal_device_open()) to be closed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_device_open() - Initialize the OpenAL audio layer

openal_context_suspend
openal_device_open
OpenAL Functions


Initialize the OpenAL audio layer

openal_device_close
openal_listener_get
OpenAL Functions
PHP Manual

openal_device_open

(PECL openal >= 0.1.0)

openal_device_open — Initialize the OpenAL audio layer

Description

resource openal_device_open ([ string $device_desc ] )

Parameters

device_desc

Open an audio device optionally specified by device_desc . If device_desc is not specified the first available audio device will be used.

Return Values

Returns an Open AL(Device) resource on success or FALSE on failure.

See Also

  • openal_device_close() - Close an OpenAL device
  • openal_context_create() - Create an audio processing context

openal_device_close
openal_listener_get
OpenAL Functions


Retrieve a listener property

openal_device_open
openal_listener_set
OpenAL Functions
PHP Manual

openal_listener_get

(PECL openal >= 0.1.0)

openal_listener_get — Retrieve a listener property

Description

mixed openal_listener_get ( int $property )

Parameters

property

Property to retrieve, one of:
AL_GAIN (float),
AL_POSITION (array(float,float,float)),
AL_VELOCITY (array(float,float,float)) and
AL_ORIENTATION (array(float,float,float)).

Return Values

Returns a float or array of floats (as appropriate) or FALSE on failure.

See Also

  • openal_listener_set() - Set a listener property

openal_device_open
openal_listener_set
OpenAL Functions


Set a listener property

openal_listener_get
openal_source_create
OpenAL Functions
PHP Manual

openal_listener_set

(PECL openal >= 0.1.0)

openal_listener_set — Set a listener property

Description

bool openal_listener_set ( int $property , mixed $setting )

Parameters

property

Property to set, one of:
AL_GAIN (float),
AL_POSITION (array(float,float,float)),
AL_VELOCITY (array(float,float,float)) and
AL_ORIENTATION (array(float,float,float)).

setting

Value to set, either float, or an array of floats as appropriate.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_listener_get() - Retrieve a listener property

openal_listener_get
openal_source_create
OpenAL Functions


Generate a source resource

openal_listener_set
openal_source_destroy
OpenAL Functions
PHP Manual

openal_source_create

(PECL openal >= 0.1.0)

openal_source_create — Generate a source resource

Description

resource openal_source_create ( void )

Return Values

Returns an Open AL(Source) resource on success or FALSE on failure.

See Also

  • openal_source_set() - Set source property
  • openal_source_play() - Start playing the source
  • openal_source_destroy() - Destroy a source resource

openal_listener_set
openal_source_destroy
OpenAL Functions


Destroy a source resource

openal_source_create
openal_source_get
OpenAL Functions
PHP Manual

openal_source_destroy

(PECL openal >= 0.1.0)

openal_source_destroy — Destroy a source resource

Description

bool openal_source_destroy ( resource $source )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_source_create() - Generate a source resource

openal_source_create
openal_source_get
OpenAL Functions


Retrieve an OpenAL source property

openal_source_destroy
openal_source_pause
OpenAL Functions
PHP Manual

openal_source_get

(PECL openal >= 0.1.0)

openal_source_get — Retrieve an OpenAL source property

Description

mixed openal_source_get ( resource $source , int $property )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

Property to get, one of: AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).

Return Values

Returns the type associated with the property being retrieved or FALSE on failure.

See Also

  • openal_source_create() - Generate a source resource
  • openal_source_set() - Set source property
  • openal_source_play() - Start playing the source

openal_source_destroy
openal_source_pause
OpenAL Functions


Pause the source

openal_source_get
openal_source_play
OpenAL Functions
PHP Manual

openal_source_pause

(PECL openal >= 0.1.0)

openal_source_pause — Pause the source

Description

bool openal_source_pause ( resource $source )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_source_stop() - Stop playing the source
  • openal_source_play() - Start playing the source
  • openal_source_rewind() - Rewind the source

openal_source_get
openal_source_play
OpenAL Functions


Start playing the source

openal_source_pause
openal_source_rewind
OpenAL Functions
PHP Manual

openal_source_play

(PECL openal >= 0.1.0)

openal_source_play — Start playing the source

Description

bool openal_source_play ( resource $source )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_source_stop() - Stop playing the source
  • openal_source_pause() - Pause the source
  • openal_source_rewind() - Rewind the source

openal_source_pause
openal_source_rewind
OpenAL Functions


Rewind the source

openal_source_play
openal_source_set
OpenAL Functions
PHP Manual

openal_source_rewind

(PECL openal >= 0.1.0)

openal_source_rewind — Rewind the source

Description

bool openal_source_rewind ( resource $source )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_source_stop() - Stop playing the source
  • openal_source_pause() - Pause the source
  • openal_source_play() - Start playing the source

openal_source_play
openal_source_set
OpenAL Functions


Set source property

openal_source_rewind
openal_source_stop
OpenAL Functions
PHP Manual

openal_source_set

(PECL openal >= 0.1.0)

openal_source_set — Set source property

Description

bool openal_source_set ( resource $source , int $property , mixed $setting )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

Property to set, one of: AL_BUFFER (OpenAL(Source)), AL_LOOPING (bool), AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).

setting

Value to assign to specified property . Refer to the description of property for a description of the value(s) expected.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_source_create() - Generate a source resource
  • openal_source_get() - Retrieve an OpenAL source property
  • openal_source_play() - Start playing the source

openal_source_rewind
openal_source_stop
OpenAL Functions


Stop playing the source

openal_source_set
openal_stream
OpenAL Functions
PHP Manual

openal_source_stop

(PECL openal >= 0.1.0)

openal_source_stop — Stop playing the source

Description

bool openal_source_stop ( resource $source )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openal_source_play() - Start playing the source
  • openal_source_pause() - Pause the source
  • openal_source_rewind() - Rewind the source

openal_source_set
openal_stream
OpenAL Functions


Begin streaming on a source

openal_source_stop
Authentication Services
OpenAL Functions
PHP Manual

openal_stream

(PECL openal >= 0.1.0)

openal_stream — Begin streaming on a source

Description

resource openal_stream ( resource $source , int $format , int $rate )

Parameters

source

An Open AL(Source) resource (previously created by openal_source_create()).

format

Format of data , one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 and AL_FORMAT_STEREO16

rate

Frequency of data to stream given in Hz.

Return Values

Returns a stream resource on success or FALSE on failure.

See Also

  • openal_source_create() - Generate a source resource
  • fwrite() - Binary-safe file write

openal_source_stop
Authentication Services
OpenAL Functions


Open directory handle

getcwd
readdir
Directory Functions
PHP Manual

opendir

(PHP 4, PHP 5)

opendir — Open directory handle

Description

resource opendir ( string $path [, resource $context ] )

Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

Parameters

path

The directory path that is to be opened

context

For a description of the context parameter, refer to the streams section of the manual.

Return Values

Returns a directory handle resource on success, or FALSE on failure.

If path is not a valid directory or the directory can not be opened due to permission restrictions or filesystem errors, opendir() returns FALSE and generates a PHP error of level E_WARNING. You can suppress the error output of opendir() by prepending '@' to the front of the function name.

Changelog

Version | Description
5.0.0 | path supports the ftp:// URL wrapper.
4.3.0 | path can also be any URL which supports directory listing, however only the file:// URL wrapper supports this in PHP 4

Examples

Example #1 opendir() example

<?php
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        closedir($dh);
    }
}
?>

The above example will output something similar to:

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir

See Also

  • is_dir() - Tells whether the filename is a directory
  • readdir() - Read entry from directory handle
  • Dir

getcwd
readdir
Directory Functions


Exports a CSR as a string

openssl_csr_export_to_file
openssl_csr_get_public_key
OpenSSL Functions
PHP Manual

openssl_csr_export

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_export — Exports a CSR as a string

Description

bool openssl_csr_export ( resource $csr , string &$out [, bool $notext = true ] )

openssl_csr_export() takes the Certificate Signing Request represented by csr and stores it as ascii-armoured text into out , which is passed by reference.

Parameters

csr

out

notext

The optional parameter notext affects the verbosity of the output; if it is FALSE, then additional human-readable information is included in the output. The default value of notext is TRUE.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_csr_export_to_file() - Exports a CSR to a file
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

openssl_csr_export_to_file
openssl_csr_get_public_key
OpenSSL Functions


Exports a CSR to a file

OpenSSL Functions
openssl_csr_export
OpenSSL Functions
PHP Manual

openssl_csr_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_export_to_file — Exports a CSR to a file

Description

bool openssl_csr_export_to_file ( resource $csr , string $outfilename [, bool $notext = true ] )

openssl_csr_export_to_file() takes the Certificate Signing Request represented by csr and saves it as ascii-armoured text into the file named by outfilename .

Parameters

csr

outfilename

Path to the output file.

notext

The optional parameter notext affects the verbosity of the output; if it is FALSE, then additional human-readable information is included in the output. The default value of notext is TRUE.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_csr_export() - Exports a CSR as a string
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

OpenSSL Functions
openssl_csr_export
OpenSSL Functions


Returns the public key of a CERT

openssl_csr_export
openssl_csr_get_subject
OpenSSL Functions
PHP Manual

openssl_csr_get_public_key

(PHP 5 >= 5.2.0)

openssl_csr_get_public_key — Returns the public key of a CERT

Description

resource openssl_csr_get_public_key ( mixed $csr [, bool $use_shortnames = true ] )
Warning

This function is currently not documented; only its argument list is available.

openssl_csr_export
openssl_csr_get_subject
OpenSSL Functions


Returns the subject of a CERT

openssl_csr_get_public_key
openssl_csr_new
OpenSSL Functions
PHP Manual

openssl_csr_get_subject

(PHP 5 >= 5.2.0)

openssl_csr_get_subject — Returns the subject of a CERT

Description

array openssl_csr_get_subject ( mixed $csr [, bool $use_shortnames = true ] )
Warning

This function is currently not documented; only its argument list is available.

openssl_csr_get_public_key
openssl_csr_new
OpenSSL Functions


Generates a CSR

openssl_csr_get_subject
openssl_csr_sign
OpenSSL Functions
PHP Manual

openssl_csr_new

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_new — Generates a CSR

Description

mixed openssl_csr_new ( array $dn , resource &$privkey [, array $configargs [, array $extraattribs ]] )

openssl_csr_new() generates a new CSR (Certificate Signing Request) based on the information provided by dn , which represents the Distinguished Name to be used in the certificate.

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Parameters

dn

The Distinguished Name to be used in the certificate.

privkey

privkey should be set to a private key that was previously generated by openssl_pkey_new() (or otherwise obtained from the other openssl_pkey family of functions). The corresponding public portion of the key will be used to sign the CSR.

configargs

By default, the information in your system openssl.conf is used to initialize the request; you can specify a configuration file section by setting the config_section_section key of configargs . You can also specify an alternative openssl configuration file by setting the value of the config key to the path of the file you want to use. The following keys, if present in configargs behave as their equivalents in the openssl.conf, as listed in the table below.

Configuration overrides
configargs key | type | openssl.conf equivalent | description
digest_alg | string | default_md | Selects which digest method to use
x509_extensions | string | x509_extensions | Selects which extensions should be used when creating an x509 certificate
req_extensions | string | req_extensions | Selects which extensions should be used when creating a CSR
private_key_bits | integer | default_bits | Specifies how many bits should be used to generate a private key
private_key_type | integer | none | Specifies the type of private key to create. This can be one of OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH or OPENSSL_KEYTYPE_RSA. The default value is OPENSSL_KEYTYPE_RSA which is currently the only supported key type.
encrypt_key | boolean | encrypt_key | Should an exported key (with passphrase) be encrypted?

extraattribs

extraattribs is used to specify additional configuration options for the CSR. Both dn and extraattribs are associative arrays whose keys are converted to OIDs and applied to the relevant part of the request.

Return Values

Returns the CSR.

Examples

Example #1 Creating a self-signed-certificate

<?php
// Fill in data for the distinguished name to be used in the cert
// You must change the values of these keys to match your name and
// company, or more precisely, the name and company of the person/site
// that you are generating the certificate for.
// For SSL certificates, the commonName is usually the domain name of
// that will be using the certificate, but for S/MIME certificates,
// the commonName will be the name of the individual who will use the
// certificate.
$dn = array(
    "countryName" => "UK",
    "stateOrProvinceName" => "Somerset",
    "localityName" => "Glastonbury",
    "organizationName" => "The Brain Room Limited",
    "organizationalUnitName" => "PHP Documentation Team",
    "commonName" => "Wez Furlong",
    "emailAddress" => "wez@example.com"
);

// Generate a new private (and public) key pair
$privkey = openssl_pkey_new();

// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey);

// You will usually want to create a self-signed certificate at this
// point until your CA fulfills your request.
// This creates a self-signed cert that is valid for 365 days
$sscert = openssl_csr_sign($csr, null, $privkey, 365);

// Now you will want to preserve your private key, CSR and self-signed
// cert so that they can be installed into your web server, mail server
// or mail client (depending on the intended use of the certificate).
// This example shows how to get those things into variables, but you
// can also store them directly into files.
// Typically, you will send the CSR on to your CA who will then issue
// you with the "real" certificate.
openssl_csr_export($csr, $csrout) and var_dump($csrout);
openssl_x509_export($sscert, $certout) and var_dump($certout);
openssl_pkey_export($privkey, $pkeyout, "mypassword") and var_dump($pkeyout);

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}
?>

openssl_csr_get_subject
openssl_csr_sign
OpenSSL Functions


Sign a CSR with another certificate (or itself) and generate a certificate

openssl_csr_new
openssl_decrypt
OpenSSL Functions
PHP Manual

openssl_csr_sign

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate

Description

resource openssl_csr_sign ( mixed $csr , mixed $cacert , mixed $priv_key , int $days [, array $configargs [, int $serial = 0 ]] )

openssl_csr_sign() generates an x509 certificate resource from the given CSR.

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Parameters

csr

A CSR previously generated by openssl_csr_new(). It can also be the path to a PEM encoded CSR when specified as file://path/to/csr or an exported string generated by openssl_csr_export().

cacert

The generated certificate will be signed by cacert . If cacert is NULL, the generated certificate will be a self-signed certificate.

priv_key

priv_key is the private key that corresponds to cacert .

days

days specifies the length of time for which the generated certificate will be valid, in days.

configargs

You can finetune the CSR signing by configargs . See openssl_csr_new() for more information about configargs .

serial

An optional the serial number of issued certificate. If not specified it will default to 0.

Return Values

Returns an x509 certificate resource on success, FALSE on failure.

Changelog

Version | Description
4.3.3 | The serial parameter was added.

Examples

Example #1 openssl_csr_sign() example - signing a CSR (how to implement your own CA)

<?php
// Let's assume that this script is set to receive a CSR that has
// been pasted into a textarea from another page
$csrdata = $_POST["CSR"];

// We will sign the request using our own "certificate authority"
// certificate.  You can use any certificate to sign another, but
// the process is worthless unless the signing certificate is trusted
// by the software/users that will deal with the newly signed certificate

// We need our CA cert and its private key
$cacert = "file://path/to/ca.crt";
$privkey = array("file://path/to/ca.key", "your_ca_key_passphrase");

$userscert = openssl_csr_sign($csrdata, $cacert, $privkey, 365);

// Now display the generated certificate so that the user can
// copy and paste it into their local configuration (such as a file
// to hold the certificate for their SSL server)
openssl_x509_export($usercert, $certout);
echo $certout;

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}
?>

openssl_csr_new
openssl_decrypt
OpenSSL Functions


Decrypts data

openssl_csr_sign
openssl_dh_compute_key
OpenSSL Functions
PHP Manual

openssl_decrypt

(PHP 5 >= 5.3.0)

openssl_decrypt — Decrypts data

Description

string openssl_decrypt ( string $data , string $method , string $password [, string $raw_input = false ] )

Takes a raw or base64 encoded string and decrypts it using a given method and key.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

The data.

method

The cipher method.

password

The password.

raw_input

Setting to TRUE will take a raw encoded string, otherwise a base64 string is assumed for the data parameter.

Return Values

The decrypted string on success or FALSE on failure.

Errors/Exceptions

Emits an E_WARNING level error if an unknown cipher algorithm is passed via the method parameter.

See Also

  • openssl_encrypt() - Encrypts data

openssl_csr_sign
openssl_dh_compute_key
OpenSSL Functions


Computes shared secret for public value of remote DH key and local DH key

openssl_decrypt
openssl_digest
OpenSSL Functions
PHP Manual

openssl_dh_compute_key

(No version information available, might only be in SVN)

openssl_dh_compute_key — Computes shared secret for public value of remote DH key and local DH key

Description

string openssl_dh_compute_key ( string $pub_key , resource $dh_key )
Warning

This function is currently not documented; only its argument list is available.

Parameters

pub_key

Public key

dh_key

DH key

Return Values

Returns computed key on success or FALSE on failure.

openssl_decrypt
openssl_digest
OpenSSL Functions


Computes a digest

openssl_dh_compute_key
openssl_encrypt
OpenSSL Functions
PHP Manual

openssl_digest

(PHP 5 >= 5.3.0)

openssl_digest — Computes a digest

Description

string openssl_digest ( string $data , string $method [, bool $raw_output = false ] )

Computes a digest hash value for the given data using a given method, and returns a raw or binhex encoded string.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

The data.

method

The digest method.

raw_output

Setting to TRUE will return as raw output data, otherwise the return value is binhex encoded.

Return Values

Returns the digested hash value on success or FALSE on failure.

Errors/Exceptions

Emits an E_WARNING level error if an unknown signature algorithm is passed via the method parameter.

See Also

  • openssl_get_cipher_methods() - Gets available cipher methods

openssl_dh_compute_key
openssl_encrypt
OpenSSL Functions


Encrypts data

openssl_digest
openssl_error_string
OpenSSL Functions
PHP Manual

openssl_encrypt

(PHP 5 >= 5.3.0)

openssl_encrypt — Encrypts data

Description

string openssl_encrypt ( string $data , string $method , string $password [, bool $raw_output = false ] )

Encrypts given data with given method and key, returns a raw or base64 encoded string

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

The data.

method

The cipher method.

password

The password.

raw_output

Setting to TRUE will return as raw output data, otherwise the return value is base64 encoded.

Return Values

Returns the encrypted string on success or FALSE on failure.

Errors/Exceptions

Emits an E_WARNING level error if an unknown cipher algorithm is passed in via the method parameter.

See Also

  • openssl_decrypt() - Decrypts data

openssl_digest
openssl_error_string
OpenSSL Functions


Return openSSL error message

openssl_encrypt
openssl_free_key
OpenSSL Functions
PHP Manual

openssl_error_string

(PHP 4 >= 4.0.6, PHP 5)

openssl_error_string — Return openSSL error message

Description

string openssl_error_string ( void )

openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information.

Return Values

Returns an error message string, or FALSE if there are no more error messages to return.

Examples

Example #1 openssl_error_string() example

<?php
// lets assume you just called an openssl function that failed
while ($msg = openssl_error_string())
    echo $msg . "<br />\n";
?>

openssl_encrypt
openssl_free_key
OpenSSL Functions


Free key resource

openssl_error_string
openssl_get_cipher_methods
OpenSSL Functions
PHP Manual

openssl_free_key

(PHP 4 >= 4.0.4, PHP 5)

openssl_free_key — Free key resource

Description

void openssl_free_key ( resource $key_identifier )

openssl_free_key() frees the key associated with the specified key_identifier from memory.

Parameters

key_identifier

Return Values

No value is returned.

openssl_error_string
openssl_get_cipher_methods
OpenSSL Functions


Gets available cipher methods

openssl_free_key
openssl_get_md_methods
OpenSSL Functions
PHP Manual

openssl_get_cipher_methods

(PHP 5 >= 5.3.0)

openssl_get_cipher_methods — Gets available cipher methods

Description

array openssl_get_cipher_methods ([ bool $aliases = false ] )

Gets a list of available cipher methods.

Parameters

aliases

Set to TRUE if cipher aliases should be included within the returned array.

Return Values

An array of available cipher methods.

Examples

Example #1 openssl_get_cipher_methods() example

Shows how the available ciphers might look, and also which aliases might be available.

<?php
$ciphers             = openssl_get_cipher_methods();
$ciphers_and_aliases = openssl_get_cipher_methods(true);
$cipher_aliases      = array_diff($ciphers_and_aliases, $ciphers);

print_r($ciphers);

print_r($cipher_aliases);

?>

The above example will output something similar to:

Array
(
    [0] => AES-128-CBC
    [1] => AES-128-CFB
    [2] => AES-128-CFB1
    [3] => AES-128-CFB8
    [4] => AES-128-ECB
    [5] => AES-128-OFB
    [6] => AES-192-CBC
    [7] => AES-192-CFB
    [8] => AES-192-CFB1
    [9] => AES-192-CFB8
    [10] => AES-192-ECB
    [11] => AES-192-OFB
    [12] => AES-256-CBC
    [13] => AES-256-CFB
    [14] => AES-256-CFB1
    [15] => AES-256-CFB8
    [16] => AES-256-ECB
    [17] => AES-256-OFB
    [18] => BF-CBC
    [19] => BF-CFB
    [20] => BF-ECB
    [21] => BF-OFB
    [22] => CAST5-CBC
    [23] => CAST5-CFB
    [24] => CAST5-ECB
    [25] => CAST5-OFB
    [26] => DES-CBC
    [27] => DES-CFB
    [28] => DES-CFB1
    [29] => DES-CFB8
    [30] => DES-ECB
    [31] => DES-EDE
    [32] => DES-EDE-CBC
    [33] => DES-EDE-CFB
    [34] => DES-EDE-OFB
    [35] => DES-EDE3
    [36] => DES-EDE3-CBC
    [37] => DES-EDE3-CFB
    [38] => DES-EDE3-OFB
    [39] => DES-OFB
    [40] => DESX-CBC
    [41] => IDEA-CBC
    [42] => IDEA-CFB
    [43] => IDEA-ECB
    [44] => IDEA-OFB
    [45] => RC2-40-CBC
    [46] => RC2-64-CBC
    [47] => RC2-CBC
    [48] => RC2-CFB
    [49] => RC2-ECB
    [50] => RC2-OFB
    [51] => RC4
    [52] => RC4-40
    [53] => aes-128-cbc
    [54] => aes-128-cfb
    [55] => aes-128-cfb1
    [56] => aes-128-cfb8
    [57] => aes-128-ecb
    [58] => aes-128-ofb
    [59] => aes-192-cbc
    [60] => aes-192-cfb
    [61] => aes-192-cfb1
    [62] => aes-192-cfb8
    [63] => aes-192-ecb
    [64] => aes-192-ofb
    [65] => aes-256-cbc
    [66] => aes-256-cfb
    [67] => aes-256-cfb1
    [68] => aes-256-cfb8
    [69] => aes-256-ecb
    [70] => aes-256-ofb
    [71] => bf-cbc
    [72] => bf-cfb
    [73] => bf-ecb
    [74] => bf-ofb
    [75] => cast5-cbc
    [76] => cast5-cfb
    [77] => cast5-ecb
    [78] => cast5-ofb
    [79] => des-cbc
    [80] => des-cfb
    [81] => des-cfb1
    [82] => des-cfb8
    [83] => des-ecb
    [84] => des-ede
    [85] => des-ede-cbc
    [86] => des-ede-cfb
    [87] => des-ede-ofb
    [88] => des-ede3
    [89] => des-ede3-cbc
    [90] => des-ede3-cfb
    [91] => des-ede3-ofb
    [92] => des-ofb
    [93] => desx-cbc
    [94] => idea-cbc
    [95] => idea-cfb
    [96] => idea-ecb
    [97] => idea-ofb
    [98] => rc2-40-cbc
    [99] => rc2-64-cbc
    [100] => rc2-cbc
    [101] => rc2-cfb
    [102] => rc2-ecb
    [103] => rc2-ofb
    [104] => rc4
    [105] => rc4-40
)
Array
(
    [18] => AES128
    [19] => AES192
    [20] => AES256
    [21] => BF
    [26] => CAST
    [27] => CAST-cbc
    [32] => DES
    [47] => DES3
    [48] => DESX
    [50] => IDEA
    [55] => RC2
    [82] => aes128
    [83] => aes192
    [84] => aes256
    [85] => bf
    [90] => blowfish
    [91] => cast
    [92] => cast-cbc
    [97] => des
    [112] => des3
    [113] => desx
    [115] => idea
    [120] => rc2
)

See Also

  • openssl_get_md_methods() - Gets available digest methods

openssl_free_key
openssl_get_md_methods
OpenSSL Functions


Gets available digest methods

openssl_get_cipher_methods
openssl_get_privatekey
OpenSSL Functions
PHP Manual

openssl_get_md_methods

(PHP 5 >= 5.3.0)

openssl_get_md_methods — Gets available digest methods

Description

array openssl_get_md_methods ([ bool $aliases = false ] )

Gets a list of available digest methods.

Parameters

aliases

Set to TRUE if digest aliases should be included within the returned array.

Return Values

An array of available digest methods.

Examples

Example #1 openssl_get_md_methods() example

Shows how the available digests might look, and also which aliases might be available.

<?php
$digests             = openssl_get_md_methods();
$digests_and_aliases = openssl_get_md_methods(true);
$digest_aliases      = array_diff($digests_and_aliases, $digests);

print_r($digests);

print_r($digest_aliases);

?>

The above example will output something similar to:

Array
(
    [0] => DSA
    [1] => DSA-SHA
    [2] => MD2
    [3] => MD4
    [4] => MD5
    [5] => RIPEMD160
    [6] => SHA
    [7] => SHA1
    [8] => SHA224
    [9] => SHA256
    [10] => SHA384
    [11] => SHA512
    [12] => dsaEncryption
    [13] => dsaWithSHA
    [14] => ecdsa-with-SHA1
    [15] => md2
    [16] => md4
    [17] => md5
    [18] => ripemd160
    [19] => sha
    [20] => sha1
    [21] => sha224
    [22] => sha256
    [23] => sha384
    [24] => sha512
)
Array
(
    [2] => DSA-SHA1
    [3] => DSA-SHA1-old
    [4] => DSS1
    [9] => RSA-MD2
    [10] => RSA-MD4
    [11] => RSA-MD5
    [12] => RSA-RIPEMD160
    [13] => RSA-SHA
    [14] => RSA-SHA1
    [15] => RSA-SHA1-2
    [16] => RSA-SHA224
    [17] => RSA-SHA256
    [18] => RSA-SHA384
    [19] => RSA-SHA512
    [28] => dsaWithSHA1
    [29] => dss1
    [32] => md2WithRSAEncryption
    [34] => md4WithRSAEncryption
    [36] => md5WithRSAEncryption
    [37] => ripemd
    [39] => ripemd160WithRSA
    [40] => rmd160
    [43] => sha1WithRSAEncryption
    [45] => sha224WithRSAEncryption
    [47] => sha256WithRSAEncryption
    [49] => sha384WithRSAEncryption
    [51] => sha512WithRSAEncryption
    [52] => shaWithRSAEncryption
    [53] => ssl2-md5
    [54] => ssl3-md5
    [55] => ssl3-sha1
)

See Also

  • openssl_digest() - Computes a digest
  • openssl_get_cipher_methods() - Gets available cipher methods

openssl_get_cipher_methods
openssl_get_privatekey
OpenSSL Functions


Alias of openssl_pkey_get_private

openssl_get_md_methods
openssl_get_publickey
OpenSSL Functions
PHP Manual

openssl_get_privatekey

(PHP 4 >= 4.0.4, PHP 5)

openssl_get_privatekey — Alias of openssl_pkey_get_private()

Description

This function is an alias of: openssl_pkey_get_private().

openssl_get_md_methods
openssl_get_publickey
OpenSSL Functions


Alias of openssl_pkey_get_public

openssl_get_privatekey
openssl_open
OpenSSL Functions
PHP Manual

openssl_get_publickey

(PHP 4 >= 4.0.4, PHP 5)

openssl_get_publickey — Alias of openssl_pkey_get_public()

Description

This function is an alias of: openssl_pkey_get_public().

openssl_get_privatekey
openssl_open
OpenSSL Functions


Open sealed data

openssl_get_publickey
openssl_pkcs12_export_to_file
OpenSSL Functions
PHP Manual

openssl_open

(PHP 4 >= 4.0.4, PHP 5)

openssl_open — Open sealed data

Description

bool openssl_open ( string $sealed_data , string &$open_data , string $env_key , mixed $priv_key_id )

openssl_open() opens (decrypts) sealed_data using the private key associated with the key identifier priv_key_id and the envelope key env_key , and fills open_data with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See openssl_seal() for more information.

Parameters

sealed_data

open_data

If the call is successful the opened data is returned in this parameter.

env_key

priv_key_id

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 openssl_open() example

<?php
// $sealed and $env_key are assumed to contain the sealed data
// and our envelope key, both given to us by the sealer.

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// decrypt the data and store it in $open
if (openssl_open($sealed, $open, $env_key, $pkeyid)) {
    echo "here is the opened data: ", $open;
} else {
    echo "failed to open data";
}

// free the private key from memory
openssl_free_key($pkeyid);
?>

See Also

  • openssl_seal() - Seal (encrypt) data

openssl_get_publickey
openssl_pkcs12_export_to_file
OpenSSL Functions


Decrypts an S/MIME encrypted message

openssl_pkcs12_read
openssl_pkcs7_encrypt
OpenSSL Functions
PHP Manual

openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message

Description

bool openssl_pkcs7_decrypt ( string $infilename , string $outfilename , mixed $recipcert [, mixed $recipkey ] )

Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and its associated private key specified by recipcert and recipkey .

Parameters

infilename

outfilename

The decrypted message is written to the file specified by outfilename .

recipcert

recipkey

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 openssl_pkcs7_decrypt() example

<?php
// $cert and $key are assumed to contain your personal certificate and private
// key pair, and that you are the recipient of an S/MIME message
$infilename = "encrypted.msg";  // this file holds your encrypted message
$outfilename = "decrypted.msg"; // make sure you can write to this file

if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key)) {
    echo "decrypted!";
} else {
    echo "failed to decrypt!";
}
?>

openssl_pkcs12_read
openssl_pkcs7_encrypt
OpenSSL Functions


Encrypt an S/MIME message

openssl_pkcs7_decrypt
openssl_pkcs7_sign
OpenSSL Functions
PHP Manual

openssl_pkcs7_encrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_encrypt — Encrypt an S/MIME message

Description

bool openssl_pkcs7_encrypt ( string $infile , string $outfile , mixed $recipcerts , array $headers [, int $flags = 0 [, int $cipherid = OPENSSL_CIPHER_RC2_40 ]] )

openssl_pkcs7_encrypt() takes the contents of the file named infile and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by recipcerts .

Parameters

infile

outfile

recipcerts

Either a lone X.509 certificate, or an array of X.509 certificates.

headers

headers is an array of headers that will be prepended to the data after it has been encrypted.

headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line.

flags

flags can be used to specify options that affect the encoding process - see PKCS7 constants.

cipherid

Cipher can be selected with cipherid .

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | The cipherid parameter was added.

Examples

Example #1 openssl_pkcs7_encrypt() example

<?php
// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
$data = <<<EOD
Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = file_get_contents("nighthawk.pem");

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
    array("To" => "nighthawk@example.com", // keyed syntax
          "From: HQ <hq@example.com>", // indexed syntax
          "Subject" => "Eyes only"))) {
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " < enc.txt");
}
?>

openssl_pkcs7_decrypt
openssl_pkcs7_sign
OpenSSL Functions


Sign an S/MIME message

openssl_pkcs7_encrypt
openssl_pkcs7_verify
OpenSSL Functions
PHP Manual

openssl_pkcs7_sign

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_sign — Sign an S/MIME message

Description

bool openssl_pkcs7_sign ( string $infilename , string $outfilename , mixed $signcert , mixed $privkey , array $headers [, int $flags = PKCS7_DETACHED [, string $extracerts ]] )

openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and its matching private key specified by signcert and privkey parameters.

Parameters

infilename

outfilename

signcert

privkey

headers

headers is an array of headers that will be prepended to the data after it has been signed (see openssl_pkcs7_encrypt() for more information about the format of this parameter).

flags

flags can be used to alter the output - see PKCS7 constants.

extracerts

extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 openssl_pkcs7_sign() example

<?php
// the message you want to sign so that recipient can be sure it was you that
// sent it
$data = <<<EOD

You have my authorization to spend $10,000 on dinner expenses.

The CEO
EOD;
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_sign("msg.txt", "signed.txt", "mycert.pem",
    array("file://mycert.pem", "mypassphrase"),
    array("To" => "joes@example.com", // keyed syntax
          "From: HQ <ceo@example.com>", // indexed syntax
          "Subject" => "Eyes only")
    )) {
    // message signed - send it!
    exec(ini_get("sendmail_path") . " < signed.txt");
}
?>

openssl_pkcs7_encrypt
openssl_pkcs7_verify
OpenSSL Functions


Verifies the signature of an S/MIME signed message

openssl_pkcs7_sign
openssl_pkey_export_to_file
OpenSSL Functions
PHP Manual

openssl_pkcs7_verify

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message

Description

mixed openssl_pkcs7_verify ( string $filename , int $flags [, string $outfilename [, array $cainfo [, string $extracerts [, string $content ]]]] )

openssl_pkcs7_verify() reads the S/MIME message contained in the given file and examines the digital signature.

Parameters

filename

Path to the message.

flags

flags can be used to affect how the signature is verified - see PKCS7 constants for more information.

outfilename

If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.

cainfo

If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.

extracerts

If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.

content

You can specify a filename with content that will be filled with the verified data, but with the signature information stripped.

Return Values

Returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.

Changelog

Version | Description
5.1.0 | The content parameter was added.

Notes

Note: As specified in RFC 2045, lines may not be longer than 76 characters in the filename parameter.

openssl_pkcs7_sign
openssl_pkey_export_to_file
OpenSSL Functions


Exports a PKCS#12 Compatible Certificate Store File to variable.

openssl_pkcs12_export_to_file
openssl_pkcs12_read
OpenSSL Functions
PHP Manual

openssl_pkcs12_export

(PHP 5 >= 5.2.2)

openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.

Description

bool openssl_pkcs12_export ( mixed $x509 , string &$out , mixed $priv_key , string $pass [, array $args ] )

openssl_pkcs12_export() stores x509 into a string named by out in a PKCS#12 file format.

Parameters

x509

out

On success, this will hold the PKCS#12.

priv_key

Private key component of PKCS#12 file.

pass

Encryption password for unlocking the PKCS#12 file.

args

Return Values

Returns TRUE on success or FALSE on failure.

openssl_pkcs12_export_to_file
openssl_pkcs12_read
OpenSSL Functions


Exports a PKCS#12 Compatible Certificate Store File

openssl_open
openssl_pkcs12_export
OpenSSL Functions
PHP Manual

openssl_pkcs12_export_to_file

(PHP 5 >= 5.2.2)

openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File

Description

bool openssl_pkcs12_export_to_file ( mixed $x509 , string $filename , mixed $priv_key , string $pass [, array $args ] )

openssl_pkcs12_export_to_file() stores x509 into a file named by filename in a PKCS#12 file format.

Parameters

x509

filename

Path to the output file.

priv_key

Private key component of PKCS#12 file.

pass

Encryption password for unlocking the PKCS#12 file.

args

Return Values

Returns TRUE on success or FALSE on failure.

openssl_open
openssl_pkcs12_export
OpenSSL Functions


Parse a PKCS#12 Certificate Store into an array

openssl_pkcs12_export
openssl_pkcs7_decrypt
OpenSSL Functions
PHP Manual

openssl_pkcs12_read

(PHP 5 >= 5.2.2)

openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array

Description

bool openssl_pkcs12_read ( string $pkcs12 , array &$certs , string $pass )

openssl_pkcs12_read() parses the PKCS#12 certificate store supplied by pkcs12 into a array named certs .

Parameters

pkcs12

certs

On success, this will hold the Certificate Store Data.

pass

Encryption password for unlocking the PKCS#12 file.

Return Values

Returns TRUE on success or FALSE on failure.

openssl_pkcs12_export
openssl_pkcs7_decrypt
OpenSSL Functions


Gets an exportable representation of a key into a string

openssl_pkey_export_to_file
openssl_pkey_free
OpenSSL Functions
PHP Manual

openssl_pkey_export

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_export — Gets an exportable representation of a key into a string

Description

bool openssl_pkey_export ( mixed $key , string &$out [, string $passphrase [, array $configargs ]] )

openssl_pkey_export() exports key as a PEM encoded string and stores it into out (which is passed by reference).

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Parameters

key

out

passphrase

The key is optionally protected by passphrase .

configargs

configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs .

Return Values

Returns TRUE on success or FALSE on failure.

openssl_pkey_export_to_file
openssl_pkey_free
OpenSSL Functions


Gets an exportable representation of a key into a file

openssl_pkcs7_verify
openssl_pkey_export
OpenSSL Functions
PHP Manual

openssl_pkey_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_export_to_file — Gets an exportable representation of a key into a file

Description

bool openssl_pkey_export_to_file ( mixed $key , string $outfilename [, string $passphrase [, array $configargs ]] )

openssl_pkey_export_to_file() saves an ascii-armoured (PEM encoded) rendition of key into the file named by outfilename .

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Parameters

key

outfilename

Path to the output file.

passphrase

The key can be optionally protected by a passphrase .

configargs

configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs .

Return Values

Returns TRUE on success or FALSE on failure.

openssl_pkcs7_verify
openssl_pkey_export
OpenSSL Functions


Frees a private key

openssl_pkey_export
openssl_pkey_get_details
OpenSSL Functions
PHP Manual

openssl_pkey_free

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_free — Frees a private key

Description

void openssl_pkey_free ( resource $key )

This function frees a private key created by openssl_pkey_new().

Parameters

key

Resource holding the key.

Return Values

No value is returned.

openssl_pkey_export
openssl_pkey_get_details
OpenSSL Functions


Returns an array with the key details

openssl_pkey_free
openssl_pkey_get_private
OpenSSL Functions
PHP Manual

openssl_pkey_get_details

(PHP 5 >= 5.2.0)

openssl_pkey_get_details — Returns an array with the key details

Description

array openssl_pkey_get_details ( resource $key )

This function returns the key details (bits, key, type).

Parameters

key

Resource holding the key.

Return Values

Returns an array with the key details in success or FALSE in failure. Returned array has indexes bits (number of bits), key (string representation of the public key) and type (type of the key which is one of OPENSSL_KEYTYPE_RSA, OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH, OPENSSL_KEYTYPE_EC or -1 meaning unknown).

openssl_pkey_free
openssl_pkey_get_private
OpenSSL Functions


Get a private key

openssl_pkey_get_details
openssl_pkey_get_public
OpenSSL Functions
PHP Manual

openssl_pkey_get_private

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_get_private — Get a private key

Description

resource openssl_pkey_get_private ( mixed $key [, string $passphrase = "" ] )

openssl_get_privatekey() parses key and prepares it for use by other functions.

Parameters

key

key can be one of the following:

  1. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).
  2. A PEM formatted private key.

passphrase

The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).

Return Values

Returns a positive key resource identifier on success, or FALSE on error.

openssl_pkey_get_details
openssl_pkey_get_public
OpenSSL Functions


Extract public key from certificate and prepare it for use

openssl_pkey_get_private
openssl_pkey_new
OpenSSL Functions
PHP Manual

openssl_pkey_get_public

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_get_public — Extract public key from certificate and prepare it for use

Description

resource openssl_pkey_get_public ( mixed $certificate )

openssl_get_publickey() extracts the public key from certificate and prepares it for use by other functions.

Parameters

certificate

certificate can be one of the following:

  1. an X.509 certificate resource
  2. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).
  3. A PEM formatted private key.

Return Values

Returns a positive key resource identifier on success, or FALSE on error.

openssl_pkey_get_private
openssl_pkey_new
OpenSSL Functions


Generates a new private key

openssl_pkey_get_public
openssl_private_decrypt
OpenSSL Functions
PHP Manual

openssl_pkey_new

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_new — Generates a new private key

Description

resource openssl_pkey_new ([ array $configargs ] )

openssl_pkey_new() generates a new private and public key pair. The public component of the key can be obtained using openssl_pkey_get_public().

Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Parameters

configargs

You can finetune the key generation (such as specifying the number of bits) using configargs . See openssl_csr_new() for more information about configargs .

Return Values

Returns a resource identifier for the pkey on success, or FALSE on error.

openssl_pkey_get_public
openssl_private_decrypt
OpenSSL Functions


Decrypts data with private key

openssl_pkey_new
openssl_private_encrypt
OpenSSL Functions
PHP Manual

openssl_private_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_private_decrypt — Decrypts data with private key

Description

bool openssl_private_decrypt ( string $data , string &$decrypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] )

openssl_private_decrypt() decrypts data that was previous encrypted via openssl_public_encrypt() and stores the result into decrypted .

You can use this function e.g. to decrypt data which were supposed only to you.

Parameters

data

decrypted

key

key must be the private key corresponding that was used to encrypt the data.

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_public_encrypt() - Encrypts data with public key
  • openssl_public_decrypt() - Decrypts data with public key

openssl_pkey_new
openssl_private_encrypt
OpenSSL Functions


Encrypts data with private key

openssl_private_decrypt
openssl_public_decrypt
OpenSSL Functions
PHP Manual

openssl_private_encrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_private_encrypt — Encrypts data with private key

Description

bool openssl_private_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] )

openssl_private_encrypt() encrypts data with private key and stores the result into crypted . Encrypted data can be decrypted via openssl_public_decrypt().

This function can be used e.g. to sign data (or its hash) to prove that it is not written by someone else.

Parameters

data

crypted

key

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_public_encrypt() - Encrypts data with public key
  • openssl_public_decrypt() - Decrypts data with public key

openssl_private_decrypt
openssl_public_decrypt
OpenSSL Functions


Decrypts data with public key

openssl_private_encrypt
openssl_public_encrypt
OpenSSL Functions
PHP Manual

openssl_public_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_public_decrypt — Decrypts data with public key

Description

bool openssl_public_decrypt ( string $data , string &$decrypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] )

openssl_public_decrypt() decrypts data that was previous encrypted via openssl_private_encrypt() and stores the result into decrypted .

You can use this function e.g. to check if the message was written by the owner of the private key.

Parameters

data

decrypted

key

key must be the public key corresponding that was used to encrypt the data.

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_private_encrypt() - Encrypts data with private key
  • openssl_private_decrypt() - Decrypts data with private key

openssl_private_encrypt
openssl_public_encrypt
OpenSSL Functions


Encrypts data with public key

openssl_public_decrypt
openssl_random_pseudo_bytes
OpenSSL Functions
PHP Manual

openssl_public_encrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_public_encrypt — Encrypts data with public key

Description

bool openssl_public_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] )

openssl_public_encrypt() encrypts data with public key and stores the result into crypted . Encrypted data can be decrypted via openssl_private_decrypt().

This function can be used e.g. to encrypt message which can be then read only by owner of the private key. It can be also used to store secure data in database.

Parameters

data

crypted

This will hold the result of the encryption.

key

The public key.

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_private_encrypt() - Encrypts data with private key
  • openssl_private_decrypt() - Decrypts data with private key

openssl_public_decrypt
openssl_random_pseudo_bytes
OpenSSL Functions


Generate a pseudo-random string

openssl_public_encrypt
openssl_seal
OpenSSL Functions
PHP Manual

openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0)

openssl_random_pseudo_bytes — Generate a pseudo-random string

Description

string openssl_random_pseudo_bytes ( string $length , string $strong )

openssl_random_pseudo_bytes() returns a string with length caracters. It also indicates if it has used a strong algorithm to produce those pseudo-random bytes in the second argument.

Parameters

length

The length of the desired string. Must be a positive integer. PHP will try to cast this parameter to a non-null integer to use it.

strong

If a strong algorithm was used, or not, as a boolean. This parameter will be NULL if an error occurrs.

Return Values

Returns the generated string in case of success, or FALSE on failure.

Examples

Example #1 openssl_random_pseudo_bytes() example

<?php
for ($i = -1; $i < 5; $i++) {
    var_dump(bin2hex(openssl_random_pseudo_bytes($i, $strong)));
    var_dump($strong);
}

?>

The above example will output something similar to:

string(0) ""
NULL
string(0) ""
NULL
string(2) "f6"
bool(true)
string(4) "8999"
bool(true)
string(6) "c202c9"
bool(true)
string(8) "45261b8f"
bool(true)

openssl_public_encrypt
openssl_seal
OpenSSL Functions


Seal (encrypt) data

openssl_random_pseudo_bytes
openssl_sign
OpenSSL Functions
PHP Manual

openssl_seal

(PHP 4 >= 4.0.4, PHP 5)

openssl_seal — Seal (encrypt) data

Description

int openssl_seal ( string $data , string &$sealed_data , array &$env_keys , array $pub_key_ids )

openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys . This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.

Parameters

data

sealed_data

env_keys

pub_key_ids

Return Values

Returns the length of the sealed data on success, or FALSE on error. If successful the sealed data is returned in sealed_data , and the envelope keys in env_keys .

Examples

Example #1 openssl_seal() example

<?php
// $data is assumed to contain the data to be sealed

// fetch public keys for our recipients, and ready them
$fp = fopen("/src/openssl-0.9.6/demos/maurice/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk1 = openssl_get_publickey($cert);
// Repeat for second recipient
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk2 = openssl_get_publickey($cert);

// seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys
// $ekeys[0] and $ekeys[1] respectively.
openssl_seal($data, $sealed, $ekeys, array($pk1, $pk2));

// free the keys from memory
openssl_free_key($pk1);
openssl_free_key($pk2);
?>

See Also

  • openssl_open() - Open sealed data

openssl_random_pseudo_bytes
openssl_sign
OpenSSL Functions


Generate signature

openssl_seal
openssl_verify
OpenSSL Functions
PHP Manual

openssl_sign

(PHP 4 >= 4.0.4, PHP 5)

openssl_sign — Generate signature

Description

bool openssl_sign ( string $data , string &$signature , mixed $priv_key_id [, int $signature_alg = OPENSSL_ALGO_SHA1 ] )

openssl_sign() computes a signature for the specified data by using SHA1 for hashing followed by encryption using the private key associated with priv_key_id . Note that the data itself is not encrypted.

Parameters

data

signature

If the call was successful the signature is returned in signature .

priv_key_id

signature_alg

For more information see the list of Signature Algorithms.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | The signature_alg parameter was added.

Examples

Example #1 openssl_sign() example

<?php
// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);
?>

See Also

  • openssl_verify() - Verify signature

openssl_seal
openssl_verify
OpenSSL Functions


Verify signature

openssl_sign
openssl_x509_check_private_key
OpenSSL Functions
PHP Manual

openssl_verify

(PHP 4 >= 4.0.4, PHP 5)

openssl_verify — Verify signature

Description

int openssl_verify ( string $data , string $signature , mixed $pub_key_id [, int $signature_alg = OPENSSL_ALGO_SHA1 ] )

openssl_verify() verifies that the signature is correct for the specified data using the public key associated with pub_key_id . This must be the public key corresponding to the private key used for signing.

Parameters

data

signature

pub_key_id

signature_alg

For more information see the list of Signature Algorithms.

Return Values

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

Changelog

Version | Description
5.0.0 | The signature_alg parameter was added.

Examples

Example #1 openssl_verify() example

<?php
// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>

See Also

  • openssl_sign() - Generate signature

openssl_sign
openssl_x509_check_private_key
OpenSSL Functions


Checks if a private key corresponds to a certificate

openssl_verify
openssl_x509_checkpurpose
OpenSSL Functions
PHP Manual

openssl_x509_check_private_key

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_check_private_key — Checks if a private key corresponds to a certificate

Description

bool openssl_x509_check_private_key ( mixed $cert , mixed $key )

Checks whether the given key is the private key that corresponds to cert .

Parameters

cert

The certificate.

key

The private key.

Return Values

Returns TRUE if key is the private key that corresponds to cert , or FALSE otherwise.

openssl_verify
openssl_x509_checkpurpose
OpenSSL Functions


Verifies if a certificate can be used for a particular purpose

openssl_x509_check_private_key
openssl_x509_export_to_file
OpenSSL Functions
PHP Manual

openssl_x509_checkpurpose

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose

Description

int openssl_x509_checkpurpose ( mixed $x509cert , int $purpose [, array $cainfo = array() [, string $untrustedfile ]] )

openssl_x509_checkpurpose() examines a certificate to see if it can be used for the specified purpose .

Parameters

x509cert

The examined certificate.

purpose

openssl_x509_checkpurpose() purposes
Constant | Description
X509_PURPOSE_SSL_CLIENT | Can the certificate be used for the client side of an SSL connection?
X509_PURPOSE_SSL_SERVER | Can the certificate be used for the server side of an SSL connection?
X509_PURPOSE_NS_SSL_SERVER | Can the cert be used for Netscape SSL server?
X509_PURPOSE_SMIME_SIGN | Can the cert be used to sign S/MIME email?
X509_PURPOSE_SMIME_ENCRYPT | Can the cert be used to encrypt S/MIME email?
X509_PURPOSE_CRL_SIGN | Can the cert be used to sign a certificate revocation list (CRL)?
X509_PURPOSE_ANY | Can the cert be used for Any/All purposes?

These options are not bitfields - you may specify one only!

cainfo

cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.

untrustedfile

If specified, this should be the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust is placed in the certificates that come from that file.

Return Values

Returns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.

openssl_x509_check_private_key
openssl_x509_export_to_file
OpenSSL Functions


Exports a certificate as a string

openssl_x509_export_to_file
openssl_x509_free
OpenSSL Functions
PHP Manual

openssl_x509_export

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_export — Exports a certificate as a string

Description

bool openssl_x509_export ( mixed $x509 , string &$output [, bool $notext ] )

openssl_x509_export() stores x509 into a string named by output in a PEM encoded format.

Parameters

x509

output

On success, this will hold the PEM.

notext

The optional parameter notext affects the verbosity of the output; if it is FALSE, then additional human-readable information is included in the output. The default value of notext is TRUE.

Return Values

Returns TRUE on success or FALSE on failure.

openssl_x509_export_to_file
openssl_x509_free
OpenSSL Functions


Exports a certificate to file

openssl_x509_checkpurpose
openssl_x509_export
OpenSSL Functions
PHP Manual

openssl_x509_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_export_to_file — Exports a certificate to file

Description

bool openssl_x509_export_to_file ( mixed $x509 , string $outfilename [, bool $notext ] )

openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format.

Parameters

x509

outfilename

Path to the output file.

notext

The optional parameter notext affects the verbosity of the output; if it is FALSE, then additional human-readable information is included in the output. The default value of notext is TRUE.

Return Values

Returns TRUE on success or FALSE on failure.

openssl_x509_checkpurpose
openssl_x509_export
OpenSSL Functions


Free certificate resource

openssl_x509_export
openssl_x509_parse
OpenSSL Functions
PHP Manual

openssl_x509_free

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_free — Free certificate resource

Description

void openssl_x509_free ( resource $x509cert )

openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.

Parameters

x509cert

Return Values

No value is returned.

openssl_x509_export
openssl_x509_parse
OpenSSL Functions


Parse an X509 certificate and return the information as an array

openssl_x509_free
openssl_x509_read
OpenSSL Functions
PHP Manual

openssl_x509_parse

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_parse — Parse an X509 certificate and return the information as an array

Description

array openssl_x509_parse ( mixed $x509cert [, bool $shortnames = true ] )

openssl_x509_parse() returns information about the supplied x509cert , including fields such as subject name, issuer name, purposes, valid from and valid to dates etc.

Parameters

x509cert

shortnames

shortnames controls how the data is indexed in the array - if shortnames is TRUE (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName.

Return Values

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.

openssl_x509_free
openssl_x509_read
OpenSSL Functions


Parse an X.509 certificate and return a resource identifier for it

openssl_x509_parse
Database Extensions
OpenSSL Functions
PHP Manual

openssl_x509_read

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it

Description

resource openssl_x509_read ( mixed $x509certdata )

openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource identifier for it.

Parameters

x509certdata

Return Values

Returns a resource identifier on success or FALSE on failure.

openssl_x509_parse
Database Extensions
OpenSSL Functions


Add URL rewriter values

ob_start
output_reset_rewrite_vars
Output Control Functions
PHP Manual

output_add_rewrite_var

(PHP 4 >= 4.3.0, PHP 5)

output_add_rewrite_var — Add URL rewriter values

Description

bool output_add_rewrite_var ( string $name , string $value )

This function adds another name/value pair to the URL rewrite mechanism. The name and value will be added to URLs (as GET parameter) and forms (as hidden input fields) the same way as the session ID when transparent URL rewriting is enabled with session.use_trans_sid. Please note that absolute URLs (http://example.com/..) aren't rewritten.

This function's behavior is controlled by the url_rewriter.tags php.ini parameter.

Note: Calling this function will implicitly start output buffering if it is not active already.

Parameters

name

The variable name.

value

The variable value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 output_add_rewrite_var() example

<?php
output_add_rewrite_var('var', 'value');

// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>';

// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';

print_r(ob_list_handlers());
?>

The above example will output:

<a href="file.php?var=value">link</a>
<a href="http://example.com">link2</a>

<form action="script.php" method="post">
<input type="hidden" name="var" value="value" />
<input type="text" name="var2" />
</form>

Array
(
    [0] => URL-Rewriter
)

See Also

  • output_reset_rewrite_vars() - Reset URL rewriter values
  • ob_flush() - Flush (send) the output buffer
  • ob_list_handlers() - List all output handlers in use

ob_start
output_reset_rewrite_vars
Output Control Functions


Reset URL rewriter values

output_add_rewrite_var
runkit
Output Control Functions
PHP Manual

output_reset_rewrite_vars

(PHP 4 >= 4.3.0, PHP 5)

output_reset_rewrite_vars — Reset URL rewriter values

Description

bool output_reset_rewrite_vars ( void )

This function resets the URL rewriter and removes all rewrite variables previously set by the output_add_rewrite_var() function or the session mechanism (if session.use_trans_sid was set on session_start()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 output_reset_rewrite_vars() example

<?php
session_start();
output_add_rewrite_var('var', 'value');

echo '<a href="file.php">link</a>';
ob_flush();

output_reset_rewrite_vars();
echo '<a href="file.php">link</a>';
?>

The above example will output:

<a href="file.php?PHPSESSID=xxx&var=value">link</a>
<a href="file.php">link</a>

See Also

  • output_add_rewrite_var() - Add URL rewriter values
  • ob_flush() - Flush (send) the output buffer
  • ob_list_handlers() - List all output handlers in use
  • session_start() - Initialize session data

output_add_rewrite_var
runkit
Output Control Functions


Enable property and method call overloading for a class

Object overloading Functions
Output Control
Object overloading Functions
PHP Manual

overload

(PHP 4 >= 4.3.0)

overload — Enable property and method call overloading for a class

Description

void overload ( string $class_name )

The overload() function will enable property and method call overloading for a class identified by class_name .

Parameters

class_name

The overloaded class name, as a string

Return Values

No value is returned.

Examples

See an example in the introductory section of this part.

Object overloading Functions
Output Control
Object overloading Functions


Overrides built-in functions

apd_set_session
rename_function
APD Functions
PHP Manual

override_function

(PECL apd >= 0.2)

override_function — Overrides built-in functions

Description

bool override_function ( string $function_name , string $function_args , string $function_code )

Overrides built-in functions by replacing them in the symbol table.

Parameters

function_name

The function to override.

function_args

The function arguments, as a comma separated string.

Usually you will want to pass this parameter, as well as the function_code parameter, as a single quote delimited string. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$your_var.

function_code

The new code for the function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 override_function() example

<?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?>

apd_set_session
rename_function
APD Functions


Closes the connection to ovrimos

Ovrimos SQL Functions
ovrimos_commit
Ovrimos SQL Functions
PHP Manual

ovrimos_close

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_close — Closes the connection to ovrimos

Description

void ovrimos_close ( int $connection )

Closes the specified connection to Ovrimos. This has the effect of rolling back uncommitted transactions.

Parameters

connection

The Ovrimos connection identifier, returned by ovrimos_connect().

Return Values

No value is returned.

See Also

  • ovrimos_connect() - Connect to the specified database

Ovrimos SQL Functions
ovrimos_commit
Ovrimos SQL Functions


Commits the transaction

ovrimos_close
ovrimos_connect
Ovrimos SQL Functions
PHP Manual

ovrimos_commit

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_commit — Commits the transaction

Description

bool ovrimos_commit ( int $connection_id )

Commits the transaction.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ovrimos_rollback() - Rolls back the transaction

ovrimos_close
ovrimos_connect
Ovrimos SQL Functions


Connect to the specified database

ovrimos_commit
ovrimos_cursor
Ovrimos SQL Functions
PHP Manual

ovrimos_connect

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_connect — Connect to the specified database

Description

int ovrimos_connect ( string $host , string $dborport , string $user , string $password )

Connects to the specified database.

Parameters

host

A host name or IP address.

dborport

Either a database name, or the port number to connect to.

user

The user name.

password

Password associated with user .

Return Values

Returns a connection identifier (greater than 0) on success, or 0 on failure.

Examples

Example #1 ovrimos_connect() Example

<?php
$conn = ovrimos_connect("server.example.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

See Also

  • ovrimos_close() - Closes the connection to ovrimos

ovrimos_commit
ovrimos_cursor
Ovrimos SQL Functions


Returns the name of the cursor

ovrimos_connect
ovrimos_exec
Ovrimos SQL Functions
PHP Manual

ovrimos_cursor

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_cursor — Returns the name of the cursor

Description

string ovrimos_cursor ( int $result_id )

Gets the name of the cursor. Useful when wishing to perform positioned updates or deletes.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns the name as a string, or FALSE on error.

ovrimos_connect
ovrimos_exec
Ovrimos SQL Functions


Executes an SQL statement

ovrimos_cursor
ovrimos_execute
Ovrimos SQL Functions
PHP Manual

ovrimos_exec

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_exec — Executes an SQL statement

Description

int ovrimos_exec ( int $connection_id , string $query )

Executes an SQL statement (query or update) and returns a result identifier.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

query

The SQL statement. Evidently, it should not contain parameters. Use ovrimos_prepare() for prepared statements.

Return Values

Returns the result identifier as an integer, or FALSE on error.

See Also

  • ovrimos_execute() - Executes a prepared SQL statement
  • ovrimos_prepare() - Prepares an SQL statement

ovrimos_cursor
ovrimos_execute
Ovrimos SQL Functions


Executes a prepared SQL statement

ovrimos_exec
ovrimos_fetch_into
Ovrimos SQL Functions
PHP Manual

ovrimos_execute

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_execute — Executes a prepared SQL statement

Description

bool ovrimos_execute ( int $result_id [, array $parameters_array ] )

Executes a prepared statement.

Parameters

result_id

An Ovrimos result identifier prepared with ovrimos_prepare().

parameters_array

If the prepared statement contained parameters (question marks in the statement), the correct number of parameters should be passed in an array.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ovrimos_prepare() - Prepares an SQL statement

ovrimos_exec
ovrimos_fetch_into
Ovrimos SQL Functions


Fetches a row from the result set

ovrimos_execute
ovrimos_fetch_row
Ovrimos SQL Functions
PHP Manual

ovrimos_fetch_into

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_fetch_into — Fetches a row from the result set

Description

bool ovrimos_fetch_into ( int $result_id , array &$result_array [, string $how [, int $rownumber ]] )

Fetches a row from the given result set, into result_array .

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

result_array

You must provide an array by reference. It will be filled with the fetched values.

how

Determines how the rows are fetched. This can be one of the following strings (case is not significant):

Option | Notes
Next | Forward direction from current position. This is the default value.
Prev | Backward direction from current position.
First | Forward direction from the start.
Last | Backward direction from the end.
Absolute | Absolute position from the start. Requires rownumber .

rownumber

The row number, first one is 0. Only needed when how is set to Absolute.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A fetch into example

<?php
$conn=ovrimos_connect("neptune", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_into($res, $row)) {
            list($table_id, $table_name) = $row;
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_into($res, $row)) {
                list($table_id, $table_name) = $row;
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

See Also

  • ovrimos_fetch_row() - Fetches a row from the result set

ovrimos_execute
ovrimos_fetch_row
Ovrimos SQL Functions


Fetches a row from the result set

ovrimos_fetch_into
ovrimos_field_len
Ovrimos SQL Functions
PHP Manual

ovrimos_fetch_row

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_fetch_row — Fetches a row from the result set

Description

bool ovrimos_fetch_row ( int $result_id [, int $how [, int $row_number ]] )

Fetches a row from the result set. Column values should be retrieved with other calls.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

how

Determines how the rows are fetched. This can be one of the following strings (case is not significant):

Option | Notes
Next | Forward direction from current position. This is the default value.
Prev | Backward direction from current position.
First | Forward direction from the start.
Last | Backward direction from the end.
Absolute | Absolute position from the start. Requires rownumber .

rownumber

The row number, first one is 0. Only needed when how is set to Absolute.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A fetch row example

<?php
$conn = ovrimos_connect("remote.host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_row($res, "First")) {
            $table_id = ovrimos_result($res, 1);
            $table_name = ovrimos_result($res, 2);
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_row($res, "Next")) {
                $table_id = ovrimos_result($res, "table_id");
                $table_name = ovrimos_result($res, "table_name");
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

This will fetch a row and print the result.

See Also

  • ovrimos_fetch_into() - Fetches a row from the result set

ovrimos_fetch_into
ovrimos_field_len
Ovrimos SQL Functions


Returns the length of the output column

ovrimos_fetch_row
ovrimos_field_name
Ovrimos SQL Functions
PHP Manual

ovrimos_field_len

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_len — Returns the length of the output column

Description

int ovrimos_field_len ( int $result_id , int $field_number )

Gets the length of the specified output column.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_number

The field number. Starts at 1.

Return Values

Returns the length as an integer, or FALSE on error.

See Also

  • ovrimos_field_name() - Returns the output column name
  • ovrimos_field_num() - Returns the (1-based) index of the output column
  • ovrimos_field_type() - Returns the type of the output column

ovrimos_fetch_row
ovrimos_field_name
Ovrimos SQL Functions


Returns the output column name

ovrimos_field_len
ovrimos_field_num
Ovrimos SQL Functions
PHP Manual

ovrimos_field_name

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_name — Returns the output column name

Description

string ovrimos_field_name ( int $result_id , int $field_number )

Returns the output column name at the index specified.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_number

The field number. Starts at 1.

Return Values

Returns the field name as a string, or FALSE on error.

See Also

  • ovrimos_field_len() - Returns the length of the output column
  • ovrimos_field_num() - Returns the (1-based) index of the output column
  • ovrimos_field_type() - Returns the type of the output column

ovrimos_field_len
ovrimos_field_num
Ovrimos SQL Functions


Returns the (1-based) index of the output column

ovrimos_field_name
ovrimos_field_type
Ovrimos SQL Functions
PHP Manual

ovrimos_field_num

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_num — Returns the (1-based) index of the output column

Description

int ovrimos_field_num ( int $result_id , string $field_name )

Returns the 1-based index of the specified output column.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_name

The field name.

Return Values

Returns the index, starting at 1, or FALSE on error.

See Also

  • ovrimos_field_len() - Returns the length of the output column
  • ovrimos_field_name() - Returns the output column name
  • ovrimos_field_type() - Returns the type of the output column

ovrimos_field_name
ovrimos_field_type
Ovrimos SQL Functions


Returns the type of the output column

ovrimos_field_num
ovrimos_free_result
Ovrimos SQL Functions
PHP Manual

ovrimos_field_type

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_type — Returns the type of the output column

Description

int ovrimos_field_type ( int $result_id , int $field_number )

Returns the type of the output column

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_number

A 1-based index.

Return Values

Returns the field type as an integer, or FALSE on error.

See Also

  • ovrimos_field_len() - Returns the length of the output column
  • ovrimos_field_name() - Returns the output column name
  • ovrimos_field_num() - Returns the (1-based) index of the output column

ovrimos_field_num
ovrimos_free_result
Ovrimos SQL Functions


Frees the specified result_id

ovrimos_field_type
ovrimos_longreadlen
Ovrimos SQL Functions
PHP Manual

ovrimos_free_result

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_free_result — Frees the specified result_id

Description

bool ovrimos_free_result ( int $result_id )

Frees the specified result identifier.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns TRUE.

ovrimos_field_type
ovrimos_longreadlen
Ovrimos SQL Functions


Specifies how many bytes are to be retrieved from long datatypes

ovrimos_free_result
ovrimos_num_fields
Ovrimos SQL Functions
PHP Manual

ovrimos_longreadlen

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_longreadlen — Specifies how many bytes are to be retrieved from long datatypes

Description

bool ovrimos_longreadlen ( int $result_id , int $length )

Specifies how many bytes are to be retrieved from long datatypes (long varchar and long varbinary).

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

length

The number of bytes to retrieve. Default is zero.

Return Values

Returns TRUE.

ovrimos_free_result
ovrimos_num_fields
Ovrimos SQL Functions


Returns the number of columns

ovrimos_longreadlen
ovrimos_num_rows
Ovrimos SQL Functions
PHP Manual

ovrimos_num_fields

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_num_fields — Returns the number of columns

Description

int ovrimos_num_fields ( int $result_id )

Returns the number of columns in the specified result identifier.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns the number of columns as an integer, or FALSE on error.

See Also

  • ovrimos_num_rows() - Returns the number of rows affected by update operations

ovrimos_longreadlen
ovrimos_num_rows
Ovrimos SQL Functions


Returns the number of rows affected by update operations

ovrimos_num_fields
ovrimos_prepare
Ovrimos SQL Functions
PHP Manual

ovrimos_num_rows

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_num_rows — Returns the number of rows affected by update operations

Description

int ovrimos_num_rows ( int $result_id )

Gets the number of rows affected by update operations.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns the number of rows as an integer, or FALSE on error.

See Also

  • ovrimos_num_fields() - Returns the number of columns

ovrimos_num_fields
ovrimos_prepare
Ovrimos SQL Functions


Prepares an SQL statement

ovrimos_num_rows
ovrimos_result_all
Ovrimos SQL Functions
PHP Manual

ovrimos_prepare

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_prepare — Prepares an SQL statement

Description

int ovrimos_prepare ( int $connection_id , string $query )

Prepares an SQL statement.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

query

The SQL statement.

Return Values

Returns a result identifier on success, or FALSE on error.

Examples

Example #1 ovrimos_prepare() Example

<?php
$conn=ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";

    // Prepare the statement
    $res=ovrimos_prepare($conn, "select table_id, table_name
                                  from sys.tables where table_id=1");
    if ($res != 0) {
        echo "Prepare ok!";
        // Execute the prepared statement
        if (ovrimos_execute($res)) {
            echo "Execute ok!\n";
            ovrimos_result_all($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>

ovrimos_num_rows
ovrimos_result_all
Ovrimos SQL Functions


Retrieves the output column

ovrimos_result_all
ovrimos_rollback
Ovrimos SQL Functions
PHP Manual

ovrimos_result

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_result — Retrieves the output column

Description

string ovrimos_result ( int $result_id , mixed $field )

Retrieves the output column specified by field .

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field

Either as a string with the field name or as an 1-based index.

Return Values

Returns the column as a string, FALSE on failure.

ovrimos_result_all
ovrimos_rollback
Ovrimos SQL Functions


Prints the whole result set as an HTML table

ovrimos_prepare
ovrimos_result
Ovrimos SQL Functions
PHP Manual

ovrimos_result_all

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_result_all — Prints the whole result set as an HTML table

Description

int ovrimos_result_all ( int $result_id [, string $format ] )

Prints the whole result set as an HTML table.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

format

Optional HTML attributes for the generated table element.

Return Values

Returns the number of rows in the generated table.

Examples

This will execute an SQL statement and print the result in an HTML table.

Example #1 Prepare a statement, execute, and view the result

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_prepare($conn, "select table_id, table_name
                                    from sys.tables where table_id = 7");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute($res, array(3))) {
            echo "Execute ok!\n";
            ovrimos_result_all($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>

Example #2 ovrimos_result_all() with meta-information

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name
                                 from sys.tables where table_id = 1");
    if ($res != 0) {
        echo "Statement ok! cursor=" . ovrimos_cursor($res) . "\n";
        $colnb = ovrimos_num_fields($res);
        echo "Output columns=" . $colnb . "\n";
        for ($i=1; $i <= $colnb; $i++) {
            $name = ovrimos_field_name($res, $i);
            $type = ovrimos_field_type($res, $i);
            $len = ovrimos_field_len($res, $i);
            echo "Column " . $i . " name=" . $name . " type=" . $type . " len=" . $len . "\n";
        }
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

ovrimos_prepare
ovrimos_result
Ovrimos SQL Functions


Rolls back the transaction

ovrimos_result
Paradox
Ovrimos SQL Functions
PHP Manual

ovrimos_rollback

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_rollback — Rolls back the transaction

Description

bool ovrimos_rollback ( int $connection_id )

Rolls back the transaction.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ovrimos_commit() - Commits the transaction

ovrimos_result
Paradox
Ovrimos SQL Functions


Pack data into binary string

ignore_user_abort
php_check_syntax
Misc. Functions
PHP Manual

pack

(PHP 4, PHP 5)

pack — Pack data into binary string

Description

string pack ( string $format [, mixed $args [, mixed $... ]] )

Pack given arguments into binary string according to format .

The idea for this function was taken from Perl and all formatting codes work the same as in Perl. However, there are some formatting codes that are missing such as Perl's "u" format code.

Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.

Also note that PHP internally stores integer values as signed values of a machine-dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to a float which often yields an undesired result.

Parameters

format

The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string.

Currently implemented formats are:

pack() format characters
Code | Description
a | NUL-padded string
A | SPACE-padded string
h | Hex string, low nibble first
H | Hex string, high nibble first
c | signed char
C | unsigned char
s | signed short (always 16 bit, machine byte order)
S | unsigned short (always 16 bit, machine byte order)
n | unsigned short (always 16 bit, big endian byte order)
v | unsigned short (always 16 bit, little endian byte order)
i | signed integer (machine dependent size and byte order)
I | unsigned integer (machine dependent size and byte order)
l | signed long (always 32 bit, machine byte order)
L | unsigned long (always 32 bit, machine byte order)
N | unsigned long (always 32 bit, big endian byte order)
V | unsigned long (always 32 bit, little endian byte order)
f | float (machine dependent size and representation)
d | double (machine dependent size and representation)
x | NUL byte
X | Back up one byte
@ NUL-fill to absolute position

args

Return Values

Returns a binary string containing data.

Examples

Example #1 pack() example

<?php
$binarydata = pack("nvc*", 0x1234, 0x5678, 65, 66);
?>

The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

See Also

  • unpack() - Unpack data from binary string

ignore_user_abort
php_check_syntax
Misc. Functions


Parse a configuration file

move_uploaded_file
parse_ini_string
Filesystem Functions
PHP Manual

parse_ini_file

(PHP 4, PHP 5)

parse_ini_file — Parse a configuration file

Description

array parse_ini_file ( string $filename [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] )

parse_ini_file() loads in the ini file specified in filename , and returns the settings in it in an associative array.

The structure of the ini file is the same as the php.ini's.

Parameters

filename

The filename of the ini file being parsed.

process_sections

By setting the process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

scanner_mode

Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed.

Return Values

The settings are returned as an associative array on success, and FALSE on failure.

Changelog

Version | Description
5.3.0 | Added optional scanner_mode parameter. Single quotes may now be used around variable assignments. Hash marks (#) may no longer be used as comments and will throw a deprecation warning if used.
5.2.7 | On syntax error this function will return FALSE rather then an empty array.
5.2.4 | Keys and section names consisting of numbers are now evaluated as PHP integers thus numbers starting by 0 are evaluated as octals and numbers starting by 0x are evaluated as hexadecimals.
5.0.0 | Values enclosed in double quotes can contain new lines.
4.2.1 | This function is now affected by safe mode and open_basedir.

Examples

Example #1 Contents of sample.ini

; This is a sample configuration file
; Comments start with ';', as in php.ini

[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"

[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"

Example #2 parse_ini_file() example

Constants may also be parsed in the ini file so if you define a constant as an ini value before running parse_ini_file(), it will be integrated into the results. Only ini values are evaluated. For example:

<?php

define('BIRD', 'Dodo bird');

// Parse without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

// Parse with sections
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);

?>

The above example will output something similar to:

Array
(
    [one] => 1
    [five] => 5
    [animal] => Dodo bird
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
    [phpversion] => Array
        (
            [0] => 5.0
            [1] => 5.1
            [2] => 5.2
            [3] => 5.3
        )

)
Array
(
    [first_section] => Array
        (
            [one] => 1
            [five] => 5
            [animal] => Dodo bird
        )

    [second_section] => Array
        (
            [path] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

    [third_section] => Array
        (
            [phpversion] => Array
                (
                    [0] => 5.0
                    [1] => 5.1
                    [2] => 5.2
                    [3] => 5.3
                )

        )

)

Example #3 parse_ini_file() parsing a php.ini file

<?php
// A simple function used for comparing the results below
function yesno($expression)
{
    return($expression ? 'Yes' : 'No');
}

// Get the path to php.ini using the php_ini_loaded_file()
// function available as of PHP 5.2.4
$ini_path = php_ini_loaded_file();

// Parse php.ini
$ini = parse_ini_file($ini_path);

// Print and compare the values, note that using get_cfg_var()
// will give the same results for parsed and loaded here
echo '(parsed) magic_quotes_gpc = ' . yesno($ini['magic_quotes_gpc']) . PHP_EOL;
echo '(loaded) magic_quotes_gpc = ' . yesno(get_cfg_var('magic_quotes_gpc')) . PHP_EOL;
?>

The above example will output something similar to:

(parsed) magic_quotes_gpc = Yes
(loaded) magic_quotes_gpc = Yes

Notes

Note: This function has nothing to do with the php.ini file. It is already processed by the time you run your script. This function can be used to read in your own application's configuration files.

Note: If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes (").

Note: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none. Values null, no and false results in "", yes and true results in "1". Characters {}|&~![()^" must not be used anywhere in the key and have a special meaning in the value.

See Also

  • parse_ini_string() - Parse a configuration string

move_uploaded_file
parse_ini_string
Filesystem Functions


Parse a configuration string

parse_ini_file
pathinfo
Filesystem Functions
PHP Manual

parse_ini_string

(PHP 5 >= 5.3.0)

parse_ini_string — Parse a configuration string

Description

array parse_ini_string ( string $ini [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] )

parse_ini_string() returns the settings in string ini in an associative array.

The structure of the ini string is the same as the php.ini's.

Parameters

ini

The contents of the ini file being parsed.

process_sections

By setting the process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

scanner_mode

Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed.

Return Values

The settings are returned as an associative array on success, and FALSE on failure.

Notes

Note: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none. Values null, no and false results in "", yes and true results in "1". Characters {}|&~![()^" must not be used anywhere in the key and have a special meaning in the value.

See Also

  • parse_ini_file() - Parse a configuration file

parse_ini_file
pathinfo
Filesystem Functions


Compile a string of PHP code and return the resulting op array

Parsekit Functions
parsekit_compile_string
Parsekit Functions
PHP Manual

parsekit_compile_file

(PECL parsekit >= 0.2.0)

parsekit_compile_file — Compile a string of PHP code and return the resulting op array

Description

array parsekit_compile_file ( string $filename [, array &$errors [, int $options = PARSEKIT_QUIET ]] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

filename

A string containing the name of the file to compile. Similar to the argument to include().

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Return Values

Returns a complex multi-layer array structure as detailed below.

Examples

Example #1 parsekit_compile_file() example

<?php
var_dump(parsekit_compile_file('hello_world.php', $errors, PARSEKIT_SIMPLE));
?>

The above example will output:

array(5) {
  [0]=>
  string(37) "ZEND_ECHO UNUSED 'Hello World' UNUSED"
  [1]=>
  string(30) "ZEND_RETURN UNUSED NULL UNUSED"
  [2]=>
  string(42) "ZEND_HANDLE_EXCEPTION UNUSED UNUSED UNUSED"
  ["function_table"]=>
  NULL
  ["class_table"]=>
  NULL
}

See Also

  • parsekit_compile_string() - Compile a string of PHP code and return the resulting op array

Parsekit Functions
parsekit_compile_string
Parsekit Functions


Compile a string of PHP code and return the resulting op array

parsekit_compile_file
parsekit_func_arginfo
Parsekit Functions
PHP Manual

parsekit_compile_string

(PECL parsekit >= 0.2.0)

parsekit_compile_string — Compile a string of PHP code and return the resulting op array

Description

array parsekit_compile_string ( string $phpcode [, array &$errors [, int $options = PARSEKIT_QUIET ]] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

phpcode

A string containing phpcode. Similar to the argument to eval().

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Return Values

Returns a complex multi-layer array structure as detailed below.

Examples

Example #1 parsekit_compile_string() example

<?php
  $ops = parsekit_compile_string('
echo "Foo\n";
', $errors, PARSEKIT_QUIET);

  var_dump($ops);
?>

The above example will output:

array(20) {
  ["type"]=>
  int(4)
  ["type_name"]=>
  string(14) "ZEND_EVAL_CODE"
  ["fn_flags"]=>
  int(0)
  ["num_args"]=>
  int(0)
  ["required_num_args"]=>
  int(0)
  ["pass_rest_by_reference"]=>
  bool(false)
  ["uses_this"]=>
  bool(false)
  ["line_start"]=>
  int(0)
  ["line_end"]=>
  int(0)
  ["return_reference"]=>
  bool(false)
  ["refcount"]=>
  int(1)
  ["last"]=>
  int(3)
  ["size"]=>
  int(3)
  ["T"]=>
  int(0)
  ["last_brk_cont"]=>
  int(0)
  ["current_brk_cont"]=>
  int(-1)
  ["backpatch_count"]=>
  int(0)
  ["done_pass_two"]=>
  bool(true)
  ["filename"]=>
  string(17) "Parsekit Compiler"
  ["opcodes"]=>
  array(3) {
    [8594800]=>
    array(5) {
      ["opcode"]=>
      int(40)
      ["opcode_name"]=>
      string(9) "ZEND_ECHO"
      ["flags"]=>
      int(768)
      ["op1"]=>
      array(3) {
        ["type"]=>
        int(1)
        ["type_name"]=>
        string(8) "IS_CONST"
        ["constant"]=>
        &string(4) "Foo
"
      }
      ["lineno"]=>
      int(2)
    }
    ["859484C"]=>
    array(6) {
      ["opcode"]=>
      int(62)
      ["opcode_name"]=>
      string(11) "ZEND_RETURN"
      ["flags"]=>
      int(16777984)
      ["op1"]=>
      array(3) {
        ["type"]=>
        int(1)
        ["type_name"]=>
        string(8) "IS_CONST"
        ["constant"]=>
        &NULL
      }
      ["extended_value"]=>
      int(0)
      ["lineno"]=>
      int(3)
    }
    [8594898]=>
    array(4) {
      ["opcode"]=>
      int(149)
      ["opcode_name"]=>
      string(21) "ZEND_HANDLE_EXCEPTION"
      ["flags"]=>
      int(0)
      ["lineno"]=>
      int(3)
    }
  }
}

See Also

  • parsekit_compile_file() - Compile a string of PHP code and return the resulting op array

parsekit_compile_file
parsekit_func_arginfo
Parsekit Functions


Return information regarding function argument(s)

parsekit_compile_string
SPL
Parsekit Functions
PHP Manual

parsekit_func_arginfo

(PECL parsekit >= 0.3.0)

parsekit_func_arginfo — Return information regarding function argument(s)

Description

array parsekit_func_arginfo ( mixed $function )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

function

A string describing a function, or an array describing a class/method.

Return Values

Returns an array containing argument information.

Examples

Example #1 parsekit_func_arginfo() example

<?php
function foo($bar, stdClass $baz, &$bomb, $bling = false) {
}

var_dump(parsekit_func_arginfo('foo'));
?>

The above example will output:

array(4) {
  [0]=>
  array(3) {
    ["name"]=>
    string(3) "bar"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(false)
  }
  [1]=>
  array(4) {
    ["name"]=>
    string(3) "baz"
    ["class_name"]=>
    string(8) "stdClass"
    ["allow_null"]=>
    bool(false)
    ["pass_by_reference"]=>
    bool(false)
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(4) "bomb"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(true)
  }
  [3]=>
  array(3) {
    ["name"]=>
    string(5) "bling"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(false)
  }
}

parsekit_compile_string
SPL
Parsekit Functions


Execute an external program and display raw output

exec
proc_close
Program execution Functions
PHP Manual

passthru

(PHP 4, PHP 5)

passthru — Execute an external program and display raw output

Description

void passthru ( string $command [, int &$return_var ] )

The passthru() function is similar to the exec() function in that it executes a command . This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the Content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.

Parameters

command

The command that will be executed.

return_var

If the return_var argument is present, the return status of the Unix command will be placed here.

Return Values

No value is returned.

Notes

Warning

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note: If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.

Warning

With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x.

See Also

  • exec() - Execute an external program
  • system() - Execute an external program and display the output
  • popen() - Opens process file pointer
  • escapeshellcmd() - Escape shell metacharacters
  • backtick operator

exec
proc_close
Program execution Functions


Returns information about a file path

parse_ini_string
pclose
Filesystem Functions
PHP Manual

pathinfo

(PHP 4 >= 4.0.3, PHP 5)

pathinfo — Returns information about a file path

Description

mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

pathinfo() returns an associative array containing information about path .

Parameters

path

The path being checked.

options

You can specify which elements are returned with optional parameter options . It composes from PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION and PATHINFO_FILENAME. It defaults to return all elements.

Return Values

The following associative array elements are returned: dirname, basename, extension (if any), and filename.

If options is used, this function will return a string if not all elements are requested.

Changelog

Version | Description
5.2.0 | The PATHINFO_FILENAME constant was added.

Examples

Example #1 pathinfo() Example

<?php
$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

The above example will output:

/www/htdocs
index.html
html
index

Notes

Note: For information on retrieving the current path info, read the section on predefined reserved variables.

See Also

  • dirname() - Returns directory name component of path
  • basename() - Returns filename component of path
  • parse_url() - Parse a URL and return its components
  • realpath() - Returns canonicalized absolute pathname

parse_ini_string
pclose
Filesystem Functions


Closes process file pointer

pathinfo
popen
Filesystem Functions
PHP Manual

pclose

(PHP 4, PHP 5)

pclose — Closes process file pointer

Description

int pclose ( resource $handle )

Closes a file pointer to a pipe opened by popen().

Parameters

handle

The file pointer must be valid, and must have been returned by a successful call to popen().

Return Values

Returns the termination status of the process that was run.

Examples

Example #1 pclose() example

<?php
$handle = popen('/bin/ls', 'r');
pclose($handle);
?>

See Also

  • popen() - Opens process file pointer

pathinfo
popen
Filesystem Functions


Set an alarm clock for delivery of a signal

PCNTL Functions
pcntl_exec
PCNTL Functions
PHP Manual

pcntl_alarm

(PHP 4 >= 4.3.0, PHP 5)

pcntl_alarm — Set an alarm clock for delivery of a signal

Description

int pcntl_alarm ( int $seconds )

Creates a timer that will send a SIGALRM signal to the process after the given number of seconds. Any call to pcntl_alarm() will cancel any previously set alarm.

Parameters

seconds

The number of seconds to wait. If seconds is zero, no new alarm is created.

Return Values

Returns the time in seconds that any previously scheduled alarm had remaining before it was to be delivered, or 0 if there was no previously scheduled alarm.

PCNTL Functions
pcntl_exec
PCNTL Functions


Executes specified program in current process space

pcntl_alarm
pcntl_fork
PCNTL Functions
PHP Manual

pcntl_exec

(PHP 4 >= 4.2.0, PHP 5)

pcntl_exec — Executes specified program in current process space

Description

void pcntl_exec ( string $path [, array $args [, array $envs ]] )

Executes the program with the given arguments.

Parameters

path

path must be the path to a binary executable or a script with a valid path pointing to an executable in the shebang ( #!/usr/local/bin/perl for example) as the first line. See your system's man execve(2) page for additional information.

args

args is an array of argument strings passed to the program.

envs

envs is an array of strings which are passed as environment to the program. The array is in the format of name => value, the key being the name of the environmental variable and the value being the value of that variable.

Return Values

Returns FALSE on error and does not return on success.

pcntl_alarm
pcntl_fork
PCNTL Functions


Forks the currently running process

pcntl_exec
pcntl_getpriority
PCNTL Functions
PHP Manual

pcntl_fork

(PHP 4 >= 4.1.0, PHP 5)

pcntl_fork — Forks the currently running process

Description

int pcntl_fork ( void )

The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.

Return Values

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.

Examples

Example #1 pcntl_fork() example

<?php

$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent
     pcntl_wait($status); //Protect against Zombie children
} else {
     // we are the child
}

?>

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler

pcntl_exec
pcntl_getpriority
PCNTL Functions


Get the priority of any process

pcntl_fork
pcntl_setpriority
PCNTL Functions
PHP Manual

pcntl_getpriority

(PHP 5)

pcntl_getpriority — Get the priority of any process

Description

int pcntl_getpriority ([ int $pid = getmypid() [, int $process_identifier = PRIO_PROCESS ]] )

pcntl_getpriority() gets the priority of pid . Because priority levels can differ between system types and kernel versions, please see your system's getpriority(2) man page for specific details.

Parameters

pid

If not specified, the pid of the current process is used.

process_identifier

One of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.

Return Values

pcntl_getpriority() returns the priority of the process or FALSE on error. A lower numerical value causes more favorable scheduling.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See Also

  • pcntl_setpriority() - Change the priority of any process

pcntl_fork
pcntl_setpriority
PCNTL Functions


Change the priority of any process

pcntl_getpriority
pcntl_signal_dispatch
PCNTL Functions
PHP Manual

pcntl_setpriority

(PHP 5)

pcntl_setpriority — Change the priority of any process

Description

bool pcntl_setpriority ( int $priority [, int $pid = getmypid() [, int $process_identifier = PRIO_PROCESS ]] )

pcntl_setpriority() sets the priority of pid .

Parameters

priority

priority is generally a value in the range -20 to 20. The default priority is 0 while a lower numerical value causes more favorable scheduling. Because priority levels can differ between system types and kernel versions, please see your system's setpriority(2) man page for specific details.

pid

If not specified, the pid of the current process is used.

process_identifier

One of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • pcntl_getpriority() - Get the priority of any process

pcntl_getpriority
pcntl_signal_dispatch
PCNTL Functions


Installs a signal handler

pcntl_signal_dispatch
pcntl_sigprocmask
PCNTL Functions
PHP Manual

pcntl_signal

(PHP 4 >= 4.1.0, PHP 5)

pcntl_signal — Installs a signal handler

Description

bool pcntl_signal ( int $signo , callback $handler [, bool $restart_syscalls = true ] )

The pcntl_signal() function installs a new signal handler for the signal indicated by signo .

Parameters

signo

The signal number.

handler

The signal handler which may be the name of a user created function, or method, or either of the two global constants SIG_IGN or SIG_DFL.

Note: Note that when you set a handler to an object method, that object's reference count is increased which makes it persist until you either change the handler to something else, or your script ends.

restart_syscalls

Specifies whether system call restarting should be used when this signal arrives.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
4.3.0 | The restart_syscalls parameter was added.
4.3.0 | The ability to use an object method as a callback became available.
4.3.0 | As of PHP 4.3.0 PCNTL uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You must use the declare() statement to specify the locations in your program where callbacks are allowed to occur for the signal handler to function properly (as used in the above example).

Examples

Example #1 pcntl_signal() example

<?php
// tick use required as of PHP 4.3.0
declare(ticks = 1);

// signal handler function
function sig_handler($signo)
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         case SIGUSR1:
             echo "Caught SIGUSR1...\n";
             break;
         default:
             // handle all other signals
     }

}

echo "Installing signal handler...\n";

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP,  "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

// or use an object, available as of PHP 4.3.0
// pcntl_signal(SIGUSR1, array($obj, "do_something");

echo"Generating signal SIGTERM to self...\n";

// send SIGUSR1 to current process id
posix_kill(posix_getpid(), SIGUSR1);

echo "Done\n"

?>

See Also

  • pcntl_fork() - Forks the currently running process
  • pcntl_waitpid() - Waits on or returns the status of a forked child

pcntl_signal_dispatch
pcntl_sigprocmask
PCNTL Functions


Calls signal handlers for pending signals

pcntl_setpriority
pcntl_signal
PCNTL Functions
PHP Manual

pcntl_signal_dispatch

(PHP 5 >= 5.3.0)

pcntl_signal_dispatch — Calls signal handlers for pending signals

Description

bool pcntl_signal_dispatch ( void )

The pcntl_signal_dispatch() function calls the signal handlers installed by pcntl_signal() for each pending signal.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pcntl_signal_dispatch() example

<?php
echo "Installing signal handler...\n";
pcntl_signal(SIGHUP,  function($signo) {
     echo "signal handler called\n";
});

echo "Generating signal SIGHUP to self...\n";
posix_kill(posix_getpid(), SIGHUP);

echo "Dispatching...\n";
pcntl_signal_dispatch();

echo "Done\n";

?>

The above example will output something similar to:

Installing signal handler...
Generating signal SIGHUP to self...
Dispatching...
signal handler called
Done

See Also

  • pcntl_signal() - Installs a signal handler
  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigwaitinfo() - Waits for signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

pcntl_setpriority
pcntl_signal
PCNTL Functions


Sets and retrieves blocked signals

pcntl_signal
pcntl_sigtimedwait
PCNTL Functions
PHP Manual

pcntl_sigprocmask

(PHP 5 >= 5.3.0)

pcntl_sigprocmask — Sets and retrieves blocked signals

Description

bool pcntl_sigprocmask ( int $how , array $set [, array &$oldset ] )

The pcntl_sigprocmask() function adds, removes or sets blocked signals, depending on the how parameter.

Parameters

how

Sets the behavior of pcntl_sigprocmask(). Possible values:

  • SIG_BLOCK: Add the signals to the currently blocked signals.
  • SIG_UNBLOCK: Remove the signals from the currently blocked signals.
  • SIG_SETMASK: Replace the currently blocked signals by the given list of signals.

set

List of signals.

oldset

The oldset parameter is set to an array containing the list of the previously blocked signals.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pcntl_sigprocmask() example

<?php
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));
$oldset = array();
pcntl_sigprocmask(SIG_UNBLOCK, array(SIGHUP), $oldset);
?>

See Also

  • pcntl_sigwaitinfo() - Waits for signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

pcntl_signal
pcntl_sigtimedwait
PCNTL Functions


Waits for signals, with a timeout

pcntl_sigprocmask
pcntl_sigwaitinfo
PCNTL Functions
PHP Manual

pcntl_sigtimedwait

(PHP 5 >= 5.3.0)

pcntl_sigtimedwait — Waits for signals, with a timeout

Description

int pcntl_sigtimedwait ( array $set [, array &$siginfo [, int $seconds = 0 [, int $nanoseconds = 0 ]]] )

The pcntl_sigtimedwait() function operates in exactly the same way as pcntl_sigwaitinfo() except that it takes two additional parameters, seconds and nanoseconds , which enable an upper bound to be placed on the time for which the script is suspended.

Parameters

set

Array of signals to wait for.

siginfo

The siginfo is set to an array containing informations about the signal. See pcntl_sigwaitinfo().

seconds

Timeout in seconds.

nanoseconds

Timeout in nanoseconds.

Return Values

On success, pcntl_sigtimedwait() returns a signal number.

See Also

  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigwaitinfo() - Waits for signals

pcntl_sigprocmask
pcntl_sigwaitinfo
PCNTL Functions


Waits for signals

pcntl_sigtimedwait
pcntl_wait
PCNTL Functions
PHP Manual

pcntl_sigwaitinfo

(PHP 5 >= 5.3.0)

pcntl_sigwaitinfo — Waits for signals

Description

int pcntl_sigwaitinfo ( array $set [, array &$siginfo ] )

The pcntl_sigwaitinfo() function suspends execution of the calling script until one of the signals given in set are delivered. If one of the signal is already pending (e.g. blocked by pcntl_sigprocmask()), pcntl_sigwaitinfo() will return immediately.

Parameters

set

Array of signals to wait for.

siginfo

The siginfo parameter is set to an array containing informations about the signal.

The following elements are set for all signals:

  • signo: Signal number
  • errno: An error number
  • code: Signal code

The following elements may be set for the SIGCHLD signal:

  • status: Exit value or signal
  • utime: User time consumed
  • stime: System time consumed
  • pid: Sending process ID
  • uid: Real user ID of sending process

The following elements may be set for the SIGILL, SIGFPE, SIGSEGV and SIGBUS signals:

  • addr: Memory location which caused fault

The following element may be set for the SIGPOLL signal:

  • band: Band event
  • fd: File descriptor number

Return Values

On success, pcntl_sigwaitinfo() returns a signal number.

Examples

Example #1 pcntl_sigwaitinfo() example

<?php
echo "Blocking SIGHUP signal\n";
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));

echo "Sending SIGHUP to self\n";
posix_kill(posix_getpid(), SIGHUP);

echo "Waiting for signals\n";
$info = array();
pcntl_sigwaitinfo(array(SIGHUP), $info);
?>

See Also

  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

pcntl_sigtimedwait
pcntl_wait
PCNTL Functions


Waits on or returns the status of a forked child

pcntl_sigwaitinfo
pcntl_waitpid
PCNTL Functions
PHP Manual

pcntl_wait

(PHP 5)

pcntl_wait — Waits on or returns the status of a forked child

Description

int pcntl_wait ( int &$status [, int $options = 0 ] )

The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's wait(2) man page for specific details as to how wait works on your system.

Note: This function is equivalent to calling pcntl_waitpid() with a -1 pid and no options .

Parameters

status

      pcntl_wait() will store status information
      in the status
parameter which can be
      evaluated using the following functions:
      pcntl_wifexited(),
      pcntl_wifstopped(),
      pcntl_wifsignaled(),
      pcntl_wexitstatus(),
      pcntl_wtermsig() and
      pcntl_wstopsig().

options

If wait3 is available on your system (mostly BSD-style systems), you can provide the optional options parameter. If this parameter is not provided, wait will be used for the system call. If wait3 is not available, providing a value for options will have no effect. The value of options is the value of zero or more of the following two constants OR'ed together:

Possible values for options
WNOHANG | Return immediately if no child has exited.
WUNTRACED | Return for children which are stopped, and whose status has not been reported.

Return Values

pcntl_wait() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was provided as an option (on wait3-available systems) and no child was available.

See Also

  • pcntl_fork() - Forks the currently running process
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifexited() - Checks if status code represents a normal exit
  • pcntl_wifstopped() - Checks whether the child process is currently stopped
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal
  • pcntl_wexitstatus() - Returns the return code of a terminated child
  • pcntl_wtermsig() - Returns the signal which caused the child to terminate
  • pcntl_wstopsig() - Returns the signal which caused the child to stop
  • pcntl_waitpid() - Waits on or returns the status of a forked child

pcntl_sigwaitinfo
pcntl_waitpid
PCNTL Functions


Waits on or returns the status of a forked child

pcntl_wait
pcntl_wexitstatus
PCNTL Functions
PHP Manual

pcntl_waitpid

(PHP 4 >= 4.1.0, PHP 5)

pcntl_waitpid — Waits on or returns the status of a forked child

Description

int pcntl_waitpid ( int $pid , int &$status [, int $options = 0 ] )

Suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function.

If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system.

Parameters

pid

The value of pid can be one of the following:

possible values for pid
< -1 | wait for any child process whose process group ID is equal to the absolute value of pid .
-1 | wait for any child process; this is the same behaviour that the wait function exhibits.
0 | wait for any child process whose process group ID is equal to that of the calling process.
> 0 | wait for the child whose process ID is equal to the value of pid .

Note: Specifying -1 as the pid is equivalent to the functionality pcntl_wait() provides (minus options ).

status

      pcntl_waitpid() will store status information
      in the status
parameter which can be
      evaluated using the following functions:
      pcntl_wifexited(),
      pcntl_wifstopped(),
      pcntl_wifsignaled(),
      pcntl_wexitstatus(),
      pcntl_wtermsig() and
      pcntl_wstopsig().

options

The value of options is the value of zero or more of the following two global constants OR'ed together:

possible values for options
WNOHANG | return immediately if no child has exited.
WUNTRACED | return for children which are stopped, and whose status has not been reported.

Return Values

pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was used and no child was available

See Also

  • pcntl_fork() - Forks the currently running process
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifexited() - Checks if status code represents a normal exit
  • pcntl_wifstopped() - Checks whether the child process is currently stopped
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal
  • pcntl_wexitstatus() - Returns the return code of a terminated child
  • pcntl_wtermsig() - Returns the signal which caused the child to terminate
  • pcntl_wstopsig() - Returns the signal which caused the child to stop

pcntl_wait
pcntl_wexitstatus
PCNTL Functions


Returns the return code of a terminated child

pcntl_waitpid
pcntl_wifexited
PCNTL Functions
PHP Manual

pcntl_wexitstatus

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wexitstatus — Returns the return code of a terminated child

Description

int pcntl_wexitstatus ( int $status )

Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns the return code, as an integer.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wifexited() - Checks if status code represents a normal exit

pcntl_waitpid
pcntl_wifexited
PCNTL Functions


Checks if status code represents a normal exit

pcntl_wexitstatus
pcntl_wifsignaled
PCNTL Functions
PHP Manual

pcntl_wifexited

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifexited — Checks if status code represents a normal exit

Description

bool pcntl_wifexited ( int $status )

Checks whether the child status code represents a normal exit.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns TRUE if the child status code represents a normal exit, FALSE otherwise.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wexitstatus() - Returns the return code of a terminated child

pcntl_wexitstatus
pcntl_wifsignaled
PCNTL Functions


Checks whether the status code represents a termination due to a signal

pcntl_wifexited
pcntl_wifstopped
PCNTL Functions
PHP Manual

pcntl_wifsignaled

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal

Description

bool pcntl_wifsignaled ( int $status )

Checks whether the child process exited because of a signal which was not caught.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns TRUE if the child process exited because of a signal which was not caught, FALSE otherwise.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler

pcntl_wifexited
pcntl_wifstopped
PCNTL Functions


Checks whether the child process is currently stopped

pcntl_wifsignaled
pcntl_wstopsig
PCNTL Functions
PHP Manual

pcntl_wifstopped

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifstopped — Checks whether the child process is currently stopped

Description

bool pcntl_wifstopped ( int $status )

Checks whether the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns TRUE if the child process which caused the return is currently stopped, FALSE otherwise.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child

pcntl_wifsignaled
pcntl_wstopsig
PCNTL Functions


Returns the signal which caused the child to stop

pcntl_wifstopped
pcntl_wtermsig
PCNTL Functions
PHP Manual

pcntl_wstopsig

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wstopsig — Returns the signal which caused the child to stop

Description

int pcntl_wstopsig ( int $status )

Returns the number of the signal which caused the child to stop. This function is only useful if pcntl_wifstopped() returned TRUE.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns the signal number.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wifstopped() - Checks whether the child process is currently stopped

pcntl_wifstopped
pcntl_wtermsig
PCNTL Functions


Returns the signal which caused the child to terminate

pcntl_wstopsig
POSIX
PCNTL Functions
PHP Manual

pcntl_wtermsig

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wtermsig — Returns the signal which caused the child to terminate

Description

int pcntl_wtermsig ( int $status )

Returns the number of the signal that caused the child process to terminate. This function is only useful if pcntl_wifsignaled() returned TRUE.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns the signal number, as an integer.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal

pcntl_wstopsig
POSIX
PCNTL Functions


Activate structure element or other content item

PDF Functions
PDF_add_annotation
PDF Functions
PHP Manual

PDF_activate_item

(PECL pdflib >= 2.0.0)

PDF_activate_item — Activate structure element or other content item

Description

bool PDF_activate_item ( resource $pdfdoc , int $id )

Activates a previously created structure element or other content item. Returns TRUE on success or FALSE on failure.

PDF Functions
PDF_add_annotation
PDF Functions


Add annotation [deprecated]

PDF_activate_item
PDF_add_bookmark
PDF Functions
PHP Manual

PDF_add_annotation

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_annotation — Add annotation [deprecated]

Description

This function is deprecated, use PDF_create_annotation() with type=Text instead.

PDF_activate_item
PDF_add_bookmark
PDF Functions


Add bookmark for current page [deprecated]

PDF_add_annotation
PDF_add_launchlink
PDF Functions
PHP Manual

PDF_add_bookmark

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_add_bookmark — Add bookmark for current page [deprecated]

Description

This function is deprecated since PDFlib version 6, use PDF_create_bookmark() instead.

PDF_add_annotation
PDF_add_launchlink
PDF Functions


Add launch annotation for current page [deprecated]

PDF_add_bookmark
PDF_add_locallink
PDF Functions
PHP Manual

PDF_add_launchlink

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_launchlink — Add launch annotation for current page [deprecated]

Description

bool PDF_add_launchlink ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $filename )

Adds a link to a web resource.

This function is deprecated since PDFlib version 6, use PDF_create_action() with type=Launch and PDF_create_annotation() with type=Link instead.

PDF_add_bookmark
PDF_add_locallink
PDF Functions


Add link annotation for current page [deprecated]

PDF_add_launchlink
PDF_add_nameddest
PDF Functions
PHP Manual

PDF_add_locallink

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_locallink — Add link annotation for current page [deprecated]

Description

bool PDF_add_locallink ( resource $pdfdoc , float $lowerleftx , float $lowerlefty , float $upperrightx , float $upperrighty , int $page , string $dest )

Add a link annotation to a target within the current PDF file. Returns TRUE on success or FALSE on failure.

  This function is deprecated since PDFlib version 6, use
  PDF_create_action() with type=GoTo

  and PDF_create_annotation() with
  type=Link
instead.

PDF_add_launchlink
PDF_add_nameddest
PDF Functions


Create named destination

PDF_add_locallink
PDF_add_note
PDF Functions
PHP Manual

PDF_add_nameddest

(PECL pdflib >= 2.0.0)

PDF_add_nameddest — Create named destination

Description

bool PDF_add_nameddest ( resource $pdfdoc , string $name , string $optlist )

Creates a named destination on an arbitrary page in the current document. Returns TRUE on success or FALSE on failure.

PDF_add_locallink
PDF_add_note
PDF Functions


Set annotation for current page [deprecated]

PDF_add_nameddest
PDF_add_outline
PDF Functions
PHP Manual

PDF_add_note

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_note — Set annotation for current page [deprecated]

Description

bool PDF_add_note ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $contents , string $title , string $icon , int $open )

Sets an annotation for the current page. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_create_annotation() with type=Text instead.

PDF_add_nameddest
PDF_add_outline
PDF Functions


Add bookmark for current page [deprecated]

PDF_add_note
PDF_add_pdflink
PDF Functions
PHP Manual

PDF_add_outline

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_outline — Add bookmark for current page [deprecated]

Description

This function is deprecated, use PDF_create_bookmark() instead.

PDF_add_note
PDF_add_pdflink
PDF Functions


Add file link annotation for current page [deprecated]

PDF_add_outline
PDF_add_table_cell
PDF Functions
PHP Manual

PDF_add_pdflink

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_pdflink — Add file link annotation for current page [deprecated]

Description

bool PDF_add_pdflink ( resource $pdfdoc , float $bottom_left_x , float $bottom_left_y , float $up_right_x , float $up_right_y , string $filename , int $page , string $dest )

Add a file link annotation to a PDF target. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_create_action() with type=GoToR and PDF_create_annotation() with type=Link instead.

PDF_add_outline
PDF_add_table_cell
PDF Functions


Add a cell to a new or existing table

PDF_add_pdflink
PDF_add_textflow
PDF Functions
PHP Manual

PDF_add_table_cell

(PECL pdflib >= 2.1.0)

PDF_add_table_cell — Add a cell to a new or existing table

Description

int PDF_add_table_cell ( resource $pdfdoc , int $table , int $column , int $row , string $text , string $optlist )

Adds a cell to a new or existing table.

PDF_add_pdflink
PDF_add_textflow
PDF Functions


Create Textflow or add text to existing Textflow

PDF_add_table_cell
PDF_add_thumbnail
PDF Functions
PHP Manual

PDF_add_textflow

(PECL pdflib >= 2.1.0)

PDF_add_textflow — Create Textflow or add text to existing Textflow

Description

int PDF_add_textflow ( resource $pdfdoc , int $textflow , string $text , string $optlist )

Creates a Textflow object, or adds text and explicit options to an existing Textflow.

PDF_add_table_cell
PDF_add_thumbnail
PDF Functions


Add thumbnail for current page

PDF_add_textflow
PDF_add_weblink
PDF Functions
PHP Manual

PDF_add_thumbnail

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_thumbnail — Add thumbnail for current page

Description

bool PDF_add_thumbnail ( resource $pdfdoc , int $image )

Adds an existing image as thumbnail for the current page. Returns TRUE on success or FALSE on failure.

PDF_add_textflow
PDF_add_weblink
PDF Functions


Add weblink for current page [deprecated]

PDF_add_thumbnail
PDF_arc
PDF Functions
PHP Manual

PDF_add_weblink

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_weblink — Add weblink for current page [deprecated]

Description

bool PDF_add_weblink ( resource $pdfdoc , float $lowerleftx , float $lowerlefty , float $upperrightx , float $upperrighty , string $url )

Adds a weblink annotation to a target url on the Web. Returns TRUE on success or FALSE on failure.

  This function is deprecated since PDFlib version 6, use
  PDF_create_action() with type=URI

  and PDF_create_annotation() with
  type=Link
instead.

PDF_add_thumbnail
PDF_arc
PDF Functions


Draw a counterclockwise circular arc segment

PDF_add_weblink
PDF_arcn
PDF Functions
PHP Manual

PDF_arc

(PHP 4, PECL pdflib >= 1.0.0)

PDF_arc — Draw a counterclockwise circular arc segment

Description

bool PDF_arc ( resource $p , float $x , float $y , float $r , float $alpha , float $beta )

Adds a counterclockwise circular arc.

PDF_add_weblink
PDF_arcn
PDF Functions


Draw a clockwise circular arc segment

PDF_arc
PDF_attach_file
PDF Functions
PHP Manual

PDF_arcn

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_arcn — Draw a clockwise circular arc segment

Description

bool PDF_arcn ( resource $p , float $x , float $y , float $r , float $alpha , float $beta )

Except for the drawing direction, this function behaves exactly like PDF_arc().

PDF_arc
PDF_attach_file
PDF Functions


Add file attachment for current page [deprecated]

PDF_arcn
PDF_begin_document
PDF Functions
PHP Manual

PDF_attach_file

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_attach_file — Add file attachment for current page [deprecated]

Description

bool PDF_attach_file ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $filename , string $description , string $author , string $mimetype , string $icon )

Adds a file attachment annotation. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_create_annotation() with type=FileAttachment instead.

PDF_arcn
PDF_begin_document
PDF Functions


Create new PDF file

PDF_attach_file
PDF_begin_font
PDF Functions
PHP Manual

PDF_begin_document

(PECL pdflib >= 2.0.0)

PDF_begin_document — Create new PDF file

Description

int PDF_begin_document ( resource $pdfdoc , string $filename , string $optlist )

Creates a new PDF file subject to various options.

PDF_attach_file
PDF_begin_font
PDF Functions


Start a Type 3 font definition

PDF_begin_document
PDF_begin_glyph
PDF Functions
PHP Manual

PDF_begin_font

(PECL pdflib >= 2.0.0)

PDF_begin_font — Start a Type 3 font definition

Description

bool PDF_begin_font ( resource $pdfdoc , string $filename , float $a , float $b , float $c , float $d , float $e , float $f , string $optlist )

Starts a Type 3 font definition.

PDF_begin_document
PDF_begin_glyph
PDF Functions


Start glyph definition for Type 3 font

PDF_begin_font
PDF_begin_item
PDF Functions
PHP Manual

PDF_begin_glyph

(PECL pdflib >= 2.0.0)

PDF_begin_glyph — Start glyph definition for Type 3 font

Description

bool PDF_begin_glyph ( resource $pdfdoc , string $glyphname , float $wx , float $llx , float $lly , float $urx , float $ury )

Starts a glyph definition for a Type 3 font.

PDF_begin_font
PDF_begin_item
PDF Functions


Open structure element or other content item

PDF_begin_glyph
PDF_begin_layer
PDF Functions
PHP Manual

PDF_begin_item

(PECL pdflib >= 2.0.0)

PDF_begin_item — Open structure element or other content item

Description

int PDF_begin_item ( resource $pdfdoc , string $tag , string $optlist )

Opens a structure element or other content item with attributes supplied as options.

PDF_begin_glyph
PDF_begin_layer
PDF Functions


Start layer

PDF_begin_item
PDF_begin_page_ext
PDF Functions
PHP Manual

PDF_begin_layer

(PECL pdflib >= 2.0.0)

PDF_begin_layer — Start layer

Description

bool PDF_begin_layer ( resource $pdfdoc , int $layer )

Starts a layer for subsequent output on the page. Returns TRUE on success or FALSE on failure.

This function requires PDF 1.5.

PDF_begin_item
PDF_begin_page_ext
PDF Functions


Start new page [deprecated]

PDF_begin_page_ext
PDF_begin_pattern
PDF Functions
PHP Manual

PDF_begin_page

(PHP 4, PECL pdflib >= 1.0.0)

PDF_begin_page — Start new page [deprecated]

Description

bool PDF_begin_page ( resource $pdfdoc , float $width , float $height )

Adds a new page to the document. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_begin_page_ext() instead.

PDF_begin_page_ext
PDF_begin_pattern
PDF Functions


Start new page

PDF_begin_layer
PDF_begin_page
PDF Functions
PHP Manual

PDF_begin_page_ext

(PECL pdflib >= 2.0.0)

PDF_begin_page_ext — Start new page

Description

bool PDF_begin_page_ext ( resource $pdfdoc , float $width , float $height , string $optlist )

Adds a new page to the document, and specifies various options. The parameters width and height are the dimensions of the new page in points. Returns TRUE on success or FALSE on failure.

Common Page Sizes in Points
name | size
A0 | 2380 x 3368
A1 | 1684 x 2380
A2 | 1190 x 1684
A3 | 842 x 1190
A4 | 595 x 842
A5 | 421 x 595
A6 | 297 x 421
B5 | 501 x 709
letter (8.5" x 11") | 612 x 792
legal (8.5" x 14") | 612 x 1008
ledger (17" x 11") | 1224 x 792
11" x 17" | 792 x 1224

PDF_begin_layer
PDF_begin_page
PDF Functions


Start pattern definition

PDF_begin_page
PDF_begin_template_ext
PDF Functions
PHP Manual

PDF_begin_pattern

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_begin_pattern — Start pattern definition

Description

int PDF_begin_pattern ( resource $pdfdoc , float $width , float $height , float $xstep , float $ystep , int $painttype )

Starts a new pattern definition.

PDF_begin_page
PDF_begin_template_ext
PDF Functions


Start template definition [deprecated]

PDF_begin_template_ext
PDF_circle
PDF Functions
PHP Manual

PDF_begin_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_begin_template — Start template definition [deprecated]

Description

int PDF_begin_template ( resource $pdfdoc , float $width , float $height )

Starts a new template definition.

This function is deprecated since PDFlib version 7, use PDF_begin_template_ext() instead.

PDF_begin_template_ext
PDF_circle
PDF Functions


Start template definition

PDF_begin_pattern
PDF_begin_template
PDF Functions
PHP Manual

PDF_begin_template_ext

(PECL pdflib >= 2.1.0)

PDF_begin_template_ext — Start template definition

Description

int PDF_begin_template_ext ( resource $pdfdoc , float $width , float $height , string $optlist )

Starts a new template definition.

PDF_begin_pattern
PDF_begin_template
PDF Functions


Draw a circle

PDF_begin_template
PDF_clip
PDF Functions
PHP Manual

PDF_circle

(PHP 4, PECL pdflib >= 1.0.0)

PDF_circle — Draw a circle

Description

bool PDF_circle ( resource $pdfdoc , float $x , float $y , float $r )

Adds a circle. Returns TRUE on success or FALSE on failure.

PDF_begin_template
PDF_clip
PDF Functions


Clip to current path

PDF_circle
PDF_close_image
PDF Functions
PHP Manual

PDF_clip

(PHP 4, PECL pdflib >= 1.0.0)

PDF_clip — Clip to current path

Description

bool PDF_clip ( resource $p )

Uses the current path as clipping path, and terminate the path. Returns TRUE on success or FALSE on failure.

PDF_circle
PDF_close_image
PDF Functions


Close pdf resource [deprecated]

PDF_close_pdi
PDF_closepath_fill_stroke
PDF Functions
PHP Manual

PDF_close

(PHP 4, PECL pdflib >= 1.0.0)

PDF_close — Close pdf resource [deprecated]

Description

bool PDF_close ( resource $p )

Closes the generated PDF file, and frees all document-related resources. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_end_document() instead.

PDF_close_pdi
PDF_closepath_fill_stroke
PDF Functions


Close image

PDF_clip
PDF_close_pdi_page
PDF Functions
PHP Manual

PDF_close_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_close_image — Close image

Description

bool PDF_close_image ( resource $p , int $image )

Closes an image retrieved with the PDF_open_image() function.

PDF_clip
PDF_close_pdi_page
PDF Functions


Close the input PDF document [deprecated]

PDF_close_pdi_page
PDF_close
PDF Functions
PHP Manual

PDF_close_pdi

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_close_pdi — Close the input PDF document [deprecated]

Description

bool PDF_close_pdi ( resource $p , int $doc )

Closes all open page handles, and closes the input PDF document. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 7, use PDF_close_pdi_document() instead.

PDF_close_pdi_page
PDF_close
PDF Functions


Close the page handle

PDF_close_image
PDF_close_pdi
PDF Functions
PHP Manual

PDF_close_pdi_page

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_close_pdi_page — Close the page handle

Description

bool PDF_close_pdi_page ( resource $p , int $page )

Closes the page handle, and frees all page-related resources. Returns TRUE on success or FALSE on failure.

PDF_close_image
PDF_close_pdi
PDF Functions


Close current path

PDF_closepath_stroke
PDF_concat
PDF Functions
PHP Manual

PDF_closepath

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath — Close current path

Description

bool PDF_closepath ( resource $p )

Closes the current path. Returns TRUE on success or FALSE on failure.

PDF_closepath_stroke
PDF_concat
PDF Functions


Close, fill and stroke current path

PDF_close
PDF_closepath_stroke
PDF Functions
PHP Manual

PDF_closepath_fill_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath_fill_stroke — Close, fill and stroke current path

Description

bool PDF_closepath_fill_stroke ( resource $p )

Closes the path, fills, and strokes it. Returns TRUE on success or FALSE on failure.

PDF_close
PDF_closepath_stroke
PDF Functions


Close and stroke path

PDF_closepath_fill_stroke
PDF_closepath
PDF Functions
PHP Manual

PDF_closepath_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath_stroke — Close and stroke path

Description

bool PDF_closepath_stroke ( resource $p )

Closes the path, and strokes it. Returns TRUE on success or FALSE on failure.

PDF_closepath_fill_stroke
PDF_closepath
PDF Functions


Concatenate a matrix to the CTM

PDF_closepath
PDF_continue_text
PDF Functions
PHP Manual

PDF_concat

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_concat — Concatenate a matrix to the CTM

Description

bool PDF_concat ( resource $p , float $a , float $b , float $c , float $d , float $e , float $f )

Concatenates a matrix to the current transformation matrix (CTM). Returns TRUE on success or FALSE on failure.

PDF_closepath
PDF_continue_text
PDF Functions


Output text in next line

PDF_concat
PDF_create_3dview
PDF Functions
PHP Manual

PDF_continue_text

(PHP 4, PECL pdflib >= 1.0.0)

PDF_continue_text — Output text in next line

Description

bool PDF_continue_text ( resource $p , string $text )

Prints text at the next line. Returns TRUE on success or FALSE on failure.

PDF_concat
PDF_create_3dview
PDF Functions


Create 3D view

PDF_continue_text
PDF_create_action
PDF Functions
PHP Manual

PDF_create_3dview

(PECL pdflib >= 2.1.0)

PDF_create_3dview — Create 3D view

Description

int PDF_create_3dview ( resource $pdfdoc , string $username , string $optlist )

Creates a 3D view.

This function requires PDF 1.6.

PDF_continue_text
PDF_create_action
PDF Functions


Create action for objects or events

PDF_create_3dview
PDF_create_annotation
PDF Functions
PHP Manual

PDF_create_action

(PECL pdflib >= 2.0.0)

PDF_create_action — Create action for objects or events

Description

int PDF_create_action ( resource $pdfdoc , string $type , string $optlist )

Creates an action which can be applied to various objects and events.

PDF_create_3dview
PDF_create_annotation
PDF Functions


Create rectangular annotation

PDF_create_action
PDF_create_bookmark
PDF Functions
PHP Manual

PDF_create_annotation

(PECL pdflib >= 2.0.0)

PDF_create_annotation — Create rectangular annotation

Description

bool PDF_create_annotation ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $type , string $optlist )

Creates a rectangular annotation on the current page.

PDF_create_action
PDF_create_bookmark
PDF Functions


Create bookmark

PDF_create_annotation
PDF_create_field
PDF Functions
PHP Manual

PDF_create_bookmark

(PECL pdflib >= 2.0.0)

PDF_create_bookmark — Create bookmark

Description

int PDF_create_bookmark ( resource $pdfdoc , string $text , string $optlist )

Creates a bookmark subject to various options.

PDF_create_annotation
PDF_create_field
PDF Functions


Create form field

PDF_create_bookmark
PDF_create_fieldgroup
PDF Functions
PHP Manual

PDF_create_field

(PECL pdflib >= 2.0.0)

PDF_create_field — Create form field

Description

bool PDF_create_field ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $name , string $type , string $optlist )

Creates a form field on the current page subject to various options.

PDF_create_bookmark
PDF_create_fieldgroup
PDF Functions


Create form field group

PDF_create_field
PDF_create_gstate
PDF Functions
PHP Manual

PDF_create_fieldgroup

(PECL pdflib >= 2.0.0)

PDF_create_fieldgroup — Create form field group

Description

bool PDF_create_fieldgroup ( resource $pdfdoc , string $name , string $optlist )

Creates a form field group subject to various options.

PDF_create_field
PDF_create_gstate
PDF Functions


Create graphics state object

PDF_create_fieldgroup
PDF_create_pvf
PDF Functions
PHP Manual

PDF_create_gstate

(PECL pdflib >= 2.0.0)

PDF_create_gstate — Create graphics state object

Description

int PDF_create_gstate ( resource $pdfdoc , string $optlist )

Creates a graphics state object subject to various options.

PDF_create_fieldgroup
PDF_create_pvf
PDF Functions


Create PDFlib virtual file

PDF_create_gstate
PDF_create_textflow
PDF Functions
PHP Manual

PDF_create_pvf

(PECL pdflib >= 2.0.0)

PDF_create_pvf — Create PDFlib virtual file

Description

bool PDF_create_pvf ( resource $pdfdoc , string $filename , string $data , string $optlist )

Creates a named virtual read-only file from data provided in memory.

PDF_create_gstate
PDF_create_textflow
PDF Functions


Create textflow object

PDF_create_pvf
PDF_curveto
PDF Functions
PHP Manual

PDF_create_textflow

(PECL pdflib >= 2.0.0)

PDF_create_textflow — Create textflow object

Description

int PDF_create_textflow ( resource $pdfdoc , string $text , string $optlist )

Preprocesses text for later formatting and creates a textflow object.

PDF_create_pvf
PDF_curveto
PDF Functions


Draw Bezier curve

PDF_create_textflow
PDF_define_layer
PDF Functions
PHP Manual

PDF_curveto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_curveto — Draw Bezier curve

Description

bool PDF_curveto ( resource $p , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Draws a Bezier curve from the current point, using 3 more control points. Returns TRUE on success or FALSE on failure.

PDF_create_textflow
PDF_define_layer
PDF Functions


Create layer definition

PDF_curveto
PDF_delete_pvf
PDF Functions
PHP Manual

PDF_define_layer

(PECL pdflib >= 2.0.0)

PDF_define_layer — Create layer definition

Description

int PDF_define_layer ( resource $pdfdoc , string $name , string $optlist )

Creates a new layer definition.

This function requires PDF 1.5.

PDF_curveto
PDF_delete_pvf
PDF Functions


Delete PDFlib object

PDF_delete_textflow
PDF_encoding_set_char
PDF Functions
PHP Manual

PDF_delete

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_delete — Delete PDFlib object

Description

bool PDF_delete ( resource $pdfdoc )

Deletes a PDFlib object, and frees all internal resources. Returns TRUE on success or FALSE on failure.

PDF_delete_textflow
PDF_encoding_set_char
PDF Functions


Delete PDFlib virtual file

PDF_define_layer
PDF_delete_table
PDF Functions
PHP Manual

PDF_delete_pvf

(PECL pdflib >= 2.0.0)

PDF_delete_pvf — Delete PDFlib virtual file

Description

int PDF_delete_pvf ( resource $pdfdoc , string $filename )

Deletes a named virtual file and frees its data structures (but not the contents).

PDF_define_layer
PDF_delete_table
PDF Functions


Delete table object

PDF_delete_pvf
PDF_delete_textflow
PDF Functions
PHP Manual

PDF_delete_table

(PECL pdflib >= 2.1.0)

PDF_delete_table — Delete table object

Description

bool PDF_delete_table ( resource $pdfdoc , int $table , string $optlist )

Deletes a table and all associated data structures.

PDF_delete_pvf
PDF_delete_textflow
PDF Functions


Delete textflow object

PDF_delete_table
PDF_delete
PDF Functions
PHP Manual

PDF_delete_textflow

(PECL pdflib >= 2.0.0)

PDF_delete_textflow — Delete textflow object

Description

bool PDF_delete_textflow ( resource $pdfdoc , int $textflow )

Deletes a textflow and the associated data structures.

PDF_delete_table
PDF_delete
PDF Functions


Add glyph name and/or Unicode value

PDF_delete
PDF_end_document
PDF Functions
PHP Manual

PDF_encoding_set_char

(PECL pdflib >= 2.0.0)

PDF_encoding_set_char — Add glyph name and/or Unicode value

Description

bool PDF_encoding_set_char ( resource $pdfdoc , string $encoding , int $slot , string $glyphname , int $uv )

Adds a glyph name and/or Unicode value to a custom encoding.

PDF_delete
PDF_end_document
PDF Functions


Close PDF file

PDF_encoding_set_char
PDF_end_font
PDF Functions
PHP Manual

PDF_end_document

(PECL pdflib >= 2.0.0)

PDF_end_document — Close PDF file

Description

bool PDF_end_document ( resource $pdfdoc , string $optlist )

Closes the generated PDF file and applies various options.

PDF_encoding_set_char
PDF_end_font
PDF Functions


Terminate Type 3 font definition

PDF_end_document
PDF_end_glyph
PDF Functions
PHP Manual

PDF_end_font

(PECL pdflib >= 2.0.0)

PDF_end_font — Terminate Type 3 font definition

Description

bool PDF_end_font ( resource $pdfdoc )

Terminates a Type 3 font definition.

PDF_end_document
PDF_end_glyph
PDF Functions


Terminate glyph definition for Type 3 font

PDF_end_font
PDF_end_item
PDF Functions
PHP Manual

PDF_end_glyph

(PECL pdflib >= 2.0.0)

PDF_end_glyph — Terminate glyph definition for Type 3 font

Description

bool PDF_end_glyph ( resource $pdfdoc )

Terminates a glyph definition for a Type 3 font.

PDF_end_font
PDF_end_item
PDF Functions


Close structure element or other content item

PDF_end_glyph
PDF_end_layer
PDF Functions
PHP Manual

PDF_end_item

(PECL pdflib >= 2.0.0)

PDF_end_item — Close structure element or other content item

Description

bool PDF_end_item ( resource $pdfdoc , int $id )

Closes a structure element or other content item.

PDF_end_glyph
PDF_end_layer
PDF Functions


Deactivate all active layers

PDF_end_item
PDF_end_page_ext
PDF Functions
PHP Manual

PDF_end_layer

(PECL pdflib >= 2.0.0)

PDF_end_layer — Deactivate all active layers

Description

bool PDF_end_layer ( resource $pdfdoc )

Deactivates all active layers. Returns TRUE on success or FALSE on failure.

This function requires PDF 1.5.

PDF_end_item
PDF_end_page_ext
PDF Functions


Finish page

PDF_end_page_ext
PDF_end_pattern
PDF Functions
PHP Manual

PDF_end_page

(PHP 4, PECL pdflib >= 1.0.0)

PDF_end_page — Finish page

Description

bool PDF_end_page ( resource $p )

Finishes the page. Returns TRUE on success or FALSE on failure.

PDF_end_page_ext
PDF_end_pattern
PDF Functions


Finish page

PDF_end_layer
PDF_end_page
PDF Functions
PHP Manual

PDF_end_page_ext

(PECL pdflib >= 2.0.0)

PDF_end_page_ext — Finish page

Description

bool PDF_end_page_ext ( resource $pdfdoc , string $optlist )

Finishes a page, and applies various options. Returns TRUE on success or FALSE on failure.

PDF_end_layer
PDF_end_page
PDF Functions


Finish pattern

PDF_end_page
PDF_end_template
PDF Functions
PHP Manual

PDF_end_pattern

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_end_pattern — Finish pattern

Description

bool PDF_end_pattern ( resource $p )

Finishes the pattern definition. Returns TRUE on success or FALSE on failure.

PDF_end_page
PDF_end_template
PDF Functions


Finish template

PDF_end_pattern
PDF_endpath
PDF Functions
PHP Manual

PDF_end_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_end_template — Finish template

Description

bool PDF_end_template ( resource $p )

Finishes a template definition. Returns TRUE on success or FALSE on failure.

PDF_end_pattern
PDF_endpath
PDF Functions


End current path

PDF_end_template
PDF_fill_imageblock
PDF Functions
PHP Manual

PDF_endpath

(PHP 4, PECL pdflib >= 1.0.0)

PDF_endpath — End current path

Description

bool PDF_endpath ( resource $p )

Ends the current path without filling or stroking it.

PDF_end_template
PDF_fill_imageblock
PDF Functions


Fill current path

PDF_fill_textblock
PDF_findfont
PDF Functions
PHP Manual

PDF_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_fill — Fill current path

Description

bool PDF_fill ( resource $p )

Fills the interior of the current path with the current fill color. Returns TRUE on success or FALSE on failure.

PDF_fill_textblock
PDF_findfont
PDF Functions


Fill image block with variable data

PDF_endpath
PDF_fill_pdfblock
PDF Functions
PHP Manual

PDF_fill_imageblock

(PECL pdflib >= 2.0.0)

PDF_fill_imageblock — Fill image block with variable data

Description

int PDF_fill_imageblock ( resource $pdfdoc , int $page , string $blockname , int $image , string $optlist )

Fills an image block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).

PDF_endpath
PDF_fill_pdfblock
PDF Functions


Fill PDF block with variable data

PDF_fill_imageblock
PDF_fill_stroke
PDF Functions
PHP Manual

PDF_fill_pdfblock

(PECL pdflib >= 2.0.0)

PDF_fill_pdfblock — Fill PDF block with variable data

Description

int PDF_fill_pdfblock ( resource $pdfdoc , int $page , string $blockname , int $contents , string $optlist )

Fills a PDF block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).

PDF_fill_imageblock
PDF_fill_stroke
PDF Functions


Fill and stroke path

PDF_fill_pdfblock
PDF_fill_textblock
PDF Functions
PHP Manual

PDF_fill_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_fill_stroke — Fill and stroke path

Description

bool PDF_fill_stroke ( resource $p )

Fills and strokes the current path with the current fill and stroke color. Returns TRUE on success or FALSE on failure.

PDF_fill_pdfblock
PDF_fill_textblock
PDF Functions


Fill text block with variable data

PDF_fill_stroke
PDF_fill
PDF Functions
PHP Manual

PDF_fill_textblock

(PECL pdflib >= 2.0.0)

PDF_fill_textblock — Fill text block with variable data

Description

int PDF_fill_textblock ( resource $pdfdoc , int $page , string $blockname , string $text , string $optlist )

Fills a text block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).

PDF_fill_stroke
PDF_fill
PDF Functions


Prepare font for later use [deprecated]

PDF_fill
PDF_fit_image
PDF Functions
PHP Manual

PDF_findfont

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_findfont — Prepare font for later use [deprecated]

Description

int PDF_findfont ( resource $p , string $fontname , string $encoding , int $embed )

Search for a font and prepare it for later use with PDF_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of builtin, macroman, winansi, host, a user-defined encoding name or the name of a CMap. Parameter embed is optional before PHP 4.3.5 or with PDFlib less than 5.

This function is deprecated since PDFlib version 5, use PDF_load_font() instead.

PDF_fill
PDF_fit_image
PDF Functions


Place image or template

PDF_findfont
PDF_fit_pdi_page
PDF Functions
PHP Manual

PDF_fit_image

(PECL pdflib >= 2.0.0)

PDF_fit_image — Place image or template

Description

bool PDF_fit_image ( resource $pdfdoc , int $image , float $x , float $y , string $optlist )

Places an image or template on the page, subject to various options. Returns TRUE on success or FALSE on failure.

PDF_findfont
PDF_fit_pdi_page
PDF Functions


Place imported PDF page

PDF_fit_image
PDF_fit_table
PDF Functions
PHP Manual

PDF_fit_pdi_page

(PECL pdflib >= 2.0.0)

PDF_fit_pdi_page — Place imported PDF page

Description

bool PDF_fit_pdi_page ( resource $pdfdoc , int $page , float $x , float $y , string $optlist )

Places an imported PDF page on the page, subject to various options. Returns TRUE on success or FALSE on failure.

PDF_fit_image
PDF_fit_table
PDF Functions


Place table on page

PDF_fit_pdi_page
PDF_fit_textflow
PDF Functions
PHP Manual

PDF_fit_table

(PECL pdflib >= 2.1.0)

PDF_fit_table — Place table on page

Description

string PDF_fit_table ( resource $pdfdoc , int $table , float $llx , float $lly , float $urx , float $ury , string $optlist )

Places a table on the page fully or partially.

PDF_fit_pdi_page
PDF_fit_textflow
PDF Functions


Format textflow in rectangular area

PDF_fit_table
PDF_fit_textline
PDF Functions
PHP Manual

PDF_fit_textflow

(PECL pdflib >= 2.0.0)

PDF_fit_textflow — Format textflow in rectangular area

Description

string PDF_fit_textflow ( resource $pdfdoc , int $textflow , float $llx , float $lly , float $urx , float $ury , string $optlist )

Formats the next portion of a textflow into a rectangular area.

PDF_fit_table
PDF_fit_textline
PDF Functions


Place single line of text

PDF_fit_textflow
PDF_get_apiname
PDF Functions
PHP Manual

PDF_fit_textline

(PECL pdflib >= 2.0.0)

PDF_fit_textline — Place single line of text

Description

bool PDF_fit_textline ( resource $pdfdoc , string $text , float $x , float $y , string $optlist )

Places a single line of text on the page, subject to various options. Returns TRUE on success or FALSE on failure.

PDF_fit_textflow
PDF_get_apiname
PDF Functions


Get name of unsuccessfull API function

PDF_fit_textline
PDF_get_buffer
PDF Functions
PHP Manual

PDF_get_apiname

(PECL pdflib >= 2.0.0)

PDF_get_apiname — Get name of unsuccessfull API function

Description

string PDF_get_apiname ( resource $pdfdoc )

Gets the name of the API function which threw the last exception or failed.

PDF_fit_textline
PDF_get_buffer
PDF Functions


Get PDF output buffer

PDF_get_apiname
PDF_get_errmsg
PDF Functions
PHP Manual

PDF_get_buffer

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_buffer — Get PDF output buffer

Description

string PDF_get_buffer ( resource $p )

Fetches the buffer containing the generated PDF data.

PDF_get_apiname
PDF_get_errmsg
PDF Functions


Get error text

PDF_get_buffer
PDF_get_errnum
PDF Functions
PHP Manual

PDF_get_errmsg

(PECL pdflib >= 2.0.0)

PDF_get_errmsg — Get error text

Description

string PDF_get_errmsg ( resource $pdfdoc )

Gets the text of the last thrown exception or the reason for a failed function call.

PDF_get_buffer
PDF_get_errnum
PDF Functions


Get error number

PDF_get_errmsg
PDF_get_font
PDF Functions
PHP Manual

PDF_get_errnum

(PECL pdflib >= 2.0.0)

PDF_get_errnum — Get error number

Description

int PDF_get_errnum ( resource $pdfdoc )

Gets the number of the last thrown exception or the reason for a failed function call.

PDF_get_errmsg
PDF_get_font
PDF Functions


Get font [deprecated]

PDF_get_errnum
PDF_get_fontname
PDF Functions
PHP Manual

PDF_get_font

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_font — Get font [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter font instead.

PDF_get_errnum
PDF_get_fontname
PDF Functions


Get font name [deprecated]

PDF_get_font
PDF_get_fontsize
PDF Functions
PHP Manual

PDF_get_fontname

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_fontname — Get font name [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_parameter() with the parameter fontname instead.

PDF_get_font
PDF_get_fontsize
PDF Functions


Font handling [deprecated]

PDF_get_fontname
PDF_get_image_height
PDF Functions
PHP Manual

PDF_get_fontsize

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_fontsize — Font handling [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter fontsize instead.

PDF_get_fontname
PDF_get_image_height
PDF Functions


Get image height [deprecated]

PDF_get_fontsize
PDF_get_image_width
PDF Functions
PHP Manual

PDF_get_image_height

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_image_height — Get image height [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter imageheight instead.

PDF_get_fontsize
PDF_get_image_width
PDF Functions


Get image width [deprecated]

PDF_get_image_height
PDF_get_majorversion
PDF Functions
PHP Manual

PDF_get_image_width

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_image_width — Get image width [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter imagewidth instead.

PDF_get_image_height
PDF_get_majorversion
PDF Functions


Get major version number [deprecated]

PDF_get_image_width
PDF_get_minorversion
PDF Functions
PHP Manual

PDF_get_majorversion

(PHP 4 >= 4.2.0, PECL pdflib >= 1.0.0)

PDF_get_majorversion — Get major version number [deprecated]

Description

int PDF_get_majorversion ( void )

This function is deprecated since PDFlib version 5, use PDF_get_value() with the parameter major instead.

PDF_get_image_width
PDF_get_minorversion
PDF Functions


Get minor version number [deprecated]

PDF_get_majorversion
PDF_get_parameter
PDF Functions
PHP Manual

PDF_get_minorversion

(PHP 4 >= 4.2.0, PECL pdflib >= 1.0.0)

PDF_get_minorversion — Get minor version number [deprecated]

Description

int PDF_get_minorversion ( void )

Returns the minor version number of the PDFlib version.

This function is deprecated since PDFlib version 5, use PDF_get_value() with the parameter minor instead.

PDF_get_majorversion
PDF_get_parameter
PDF Functions


Get string parameter

PDF_get_minorversion
PDF_get_pdi_parameter
PDF Functions
PHP Manual

PDF_get_parameter

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_get_parameter — Get string parameter

Description

string PDF_get_parameter ( resource $p , string $key , float $modifier )

Gets the contents of some PDFlib parameter with string type.

PDF_get_minorversion
PDF_get_pdi_parameter
PDF Functions


Get PDI string parameter [deprecated]

PDF_get_parameter
PDF_get_pdi_value
PDF Functions
PHP Manual

PDF_get_pdi_parameter

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_pdi_parameter — Get PDI string parameter [deprecated]

Description

string PDF_get_pdi_parameter ( resource $p , string $key , int $doc , int $page , int $reserved )

Gets the contents of a PDI document parameter with string type.

This function is deprecated since PDFlib version 7, use PDF_pcos_get_string() instead.

PDF_get_parameter
PDF_get_pdi_value
PDF Functions


Get PDI numerical parameter [deprecated]

PDF_get_pdi_parameter
PDF_get_value
PDF Functions
PHP Manual

PDF_get_pdi_value

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_pdi_value — Get PDI numerical parameter [deprecated]

Description

float PDF_get_pdi_value ( resource $p , string $key , int $doc , int $page , int $reserved )

Gets the contents of a PDI document parameter with numerical type.

This function is deprecated since PDFlib version 7, use PDF_pcos_get_number() instead.

PDF_get_pdi_parameter
PDF_get_value
PDF Functions


Get numerical parameter

PDF_get_pdi_value
PDF_info_font
PDF Functions
PHP Manual

PDF_get_value

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_get_value — Get numerical parameter

Description

float PDF_get_value ( resource $p , string $key , float $modifier )

Gets the value of some PDFlib parameter with numerical type.

PDF_get_pdi_value
PDF_info_font
PDF Functions


Query detailed information about a loaded font

PDF_get_value
PDF_info_matchbox
PDF Functions
PHP Manual

PDF_info_font

(PECL pdflib >= 2.1.0)

PDF_info_font — Query detailed information about a loaded font

Description

float PDF_info_font ( resource $pdfdoc , int $font , string $keyword , string $optlist )

Queries detailed information about a loaded font.

PDF_get_value
PDF_info_matchbox
PDF Functions


Query matchbox information

PDF_info_font
PDF_info_table
PDF Functions
PHP Manual

PDF_info_matchbox

(PECL pdflib >= 2.1.0)

PDF_info_matchbox — Query matchbox information

Description

float PDF_info_matchbox ( resource $pdfdoc , string $boxname , int $num , string $keyword )

Queries information about a matchbox on the current page.

PDF_info_font
PDF_info_table
PDF Functions


Retrieve table information

PDF_info_matchbox
PDF_info_textflow
PDF Functions
PHP Manual

PDF_info_table

(PECL pdflib >= 2.1.0)

PDF_info_table — Retrieve table information

Description

float PDF_info_table ( resource $pdfdoc , int $table , string $keyword )

Retrieves table information related to the most recently placed table instance.

PDF_info_matchbox
PDF_info_textflow
PDF Functions


Query textflow state

PDF_info_table
PDF_info_textline
PDF Functions
PHP Manual

PDF_info_textflow

(PECL pdflib >= 2.0.0)

PDF_info_textflow — Query textflow state

Description

float PDF_info_textflow ( resource $pdfdoc , int $textflow , string $keyword )

Queries the current state of a textflow.

PDF_info_table
PDF_info_textline
PDF Functions


Perform textline formatting and query metrics

PDF_info_textflow
PDF_initgraphics
PDF Functions
PHP Manual

PDF_info_textline

(PECL pdflib >= 2.1.0)

PDF_info_textline — Perform textline formatting and query metrics

Description

float PDF_info_textline ( resource $pdfdoc , string $text , string $keyword , string $optlist )

Performs textline formatting and queries the resulting metrics.

PDF_info_textflow
PDF_initgraphics
PDF Functions


Reset graphic state

PDF_info_textline
PDF_lineto
PDF Functions
PHP Manual

PDF_initgraphics

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_initgraphics — Reset graphic state

Description

bool PDF_initgraphics ( resource $p )

Reset all color and graphics state parameters to their defaults. Returns TRUE on success or FALSE on failure.

PDF_info_textline
PDF_lineto
PDF Functions


Draw a line

PDF_initgraphics
PDF_load_3ddata
PDF Functions
PHP Manual

PDF_lineto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_lineto — Draw a line

Description

bool PDF_lineto ( resource $p , float $x , float $y )

Draws a line from the current point to another point. Returns TRUE on success or FALSE on failure.

PDF_initgraphics
PDF_load_3ddata
PDF Functions


Load 3D model

PDF_lineto
PDF_load_font
PDF Functions
PHP Manual

PDF_load_3ddata

(PECL pdflib >= 2.1.0)

PDF_load_3ddata — Load 3D model

Description

int PDF_load_3ddata ( resource $pdfdoc , string $filename , string $optlist )

Loads a 3D model from a disk-based or virtual file.

This function requires PDF 1.6.

PDF_lineto
PDF_load_font
PDF Functions


Search and prepare font

PDF_load_3ddata
PDF_load_iccprofile
PDF Functions
PHP Manual

PDF_load_font

(PECL pdflib >= 2.0.0)

PDF_load_font — Search and prepare font

Description

int PDF_load_font ( resource $pdfdoc , string $fontname , string $encoding , string $optlist )

Searches for a font and prepares it for later use.

PDF_load_3ddata
PDF_load_iccprofile
PDF Functions


Search and prepare ICC profile

PDF_load_font
PDF_load_image
PDF Functions
PHP Manual

PDF_load_iccprofile

(PECL pdflib >= 2.0.0)

PDF_load_iccprofile — Search and prepare ICC profile

Description

int PDF_load_iccprofile ( resource $pdfdoc , string $profilename , string $optlist )

Searches for an ICC profile, and prepares it for later use.

PDF_load_font
PDF_load_image
PDF Functions


Open image file

PDF_load_iccprofile
PDF_makespotcolor
PDF Functions
PHP Manual

PDF_load_image

(PECL pdflib >= 2.0.0)

PDF_load_image — Open image file

Description

int PDF_load_image ( resource $pdfdoc , string $imagetype , string $filename , string $optlist )

Opens a disk-based or virtual image file subject to various options.

PDF_load_iccprofile
PDF_makespotcolor
PDF Functions


Make spot color

PDF_load_image
PDF_moveto
PDF Functions
PHP Manual

PDF_makespotcolor

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_makespotcolor — Make spot color

Description

int PDF_makespotcolor ( resource $p , string $spotname )

Finds a built-in spot color name, or makes a named spot color from the current fill color. Returns TRUE on success or FALSE on failure.

PDF_load_image
PDF_moveto
PDF Functions


Set current point

PDF_makespotcolor
PDF_new
PDF Functions
PHP Manual

PDF_moveto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_moveto — Set current point

Description

bool PDF_moveto ( resource $p , float $x , float $y )

Sets the current point for graphics output. Returns TRUE on success or FALSE on failure.

PDF_makespotcolor
PDF_new
PDF Functions


Create PDFlib object

PDF_moveto
PDF_open_ccitt
PDF Functions
PHP Manual

PDF_new

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_new — Create PDFlib object

Description

resource PDF_new ( void )

Creates a new PDFlib object with default settings.

PDF_moveto
PDF_open_ccitt
PDF Functions


Open raw CCITT image [deprecated]

PDF_new
PDF_open_file
PDF Functions
PHP Manual

PDF_open_ccitt

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_ccitt — Open raw CCITT image [deprecated]

Description

int PDF_open_ccitt ( resource $pdfdoc , string $filename , int $width , int $height , int $BitReverse , int $k , int $Blackls1 )

Opens a raw CCITT image.

This function is deprecated since PDFlib version 5, use PDF_load_image() instead.

PDF_new
PDF_open_file
PDF Functions


Create PDF file [deprecated]

PDF_open_ccitt
PDF_open_gif
PDF Functions
PHP Manual

PDF_open_file

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_file — Create PDF file [deprecated]

Description

bool PDF_open_file ( resource $p , string $filename )

Creates a new PDF file using the supplied file name. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_begin_document() instead.

PDF_open_ccitt
PDF_open_gif
PDF Functions


Open GIF image [deprecated]

PDF_open_file
PDF_open_image_file
PDF Functions
PHP Manual

PDF_open_gif

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_gif — Open GIF image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

PDF_open_file
PDF_open_image_file
PDF Functions


Use image data [deprecated]

PDF_open_image_file
PDF_open_jpeg
PDF Functions
PHP Manual

PDF_open_image

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_image — Use image data [deprecated]

Description

int PDF_open_image ( resource $p , string $imagetype , string $source , string $data , int $length , int $width , int $height , int $components , int $bpc , string $params )

Uses image data from a variety of data sources.

This function is deprecated since PDFlib version 5, use virtual files and PDF_load_image() instead.

PDF_open_image_file
PDF_open_jpeg
PDF Functions


Read image from file [deprecated]

PDF_open_gif
PDF_open_image
PDF Functions
PHP Manual

PDF_open_image_file

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_image_file — Read image from file [deprecated]

Description

int PDF_open_image_file ( resource $p , string $imagetype , string $filename , string $stringparam , int $intparam )

Opens an image file.

This function is deprecated since PDFlib version 5, use PDF_load_image() with the colorize, ignoremask, invert, mask, masked, and page options instead.

PDF_open_gif
PDF_open_image
PDF Functions


Open JPEG image [deprecated]

PDF_open_image
PDF_open_memory_image
PDF Functions
PHP Manual

PDF_open_jpeg

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_jpeg — Open JPEG image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

PDF_open_image
PDF_open_memory_image
PDF Functions


Open image created with PHP's image functions [not supported]

PDF_open_jpeg
PDF_open_pdi_page
PDF Functions
PHP Manual

PDF_open_memory_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_memory_image — Open image created with PHP's image functions [not supported]

Description

int PDF_open_memory_image ( resource $p , resource $image )

This function is not supported by PDFlib GmbH.

PDF_open_jpeg
PDF_open_pdi_page
PDF Functions


Open PDF file [deprecated]

PDF_open_pdi_page
PDF_open_tiff
PDF Functions
PHP Manual

PDF_open_pdi

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_pdi — Open PDF file [deprecated]

Description

int PDF_open_pdi ( resource $pdfdoc , string $filename , string $optlist , int $len )

Opens a disk-based or virtual PDF document and prepares it for later use.

This function is deprecated since PDFlib version 7, use PDF_open_pdi_document() instead.

PDF_open_pdi_page
PDF_open_tiff
PDF Functions


Prepare a page

PDF_open_memory_image
PDF_open_pdi
PDF Functions
PHP Manual

PDF_open_pdi_page

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_pdi_page — Prepare a page

Description

int PDF_open_pdi_page ( resource $p , int $doc , int $pagenumber , string $optlist )

Prepares a page for later use with PDF_fit_pdi_page().

PDF_open_memory_image
PDF_open_pdi
PDF Functions


Open TIFF image [deprecated]

PDF_open_pdi
PDF_pcos_get_number
PDF Functions
PHP Manual

PDF_open_tiff

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_tiff — Open TIFF image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

PDF_open_pdi
PDF_pcos_get_number
PDF Functions


Get value of pCOS path with type number or boolean

PDF_open_tiff
PDF_pcos_get_stream
PDF Functions
PHP Manual

PDF_pcos_get_number

(PECL pdflib >= 2.1.0)

PDF_pcos_get_number — Get value of pCOS path with type number or boolean

Description

float PDF_pcos_get_number ( resource $p , int $doc , string $path )

Gets the value of a pCOS path with type number or boolean.

PDF_open_tiff
PDF_pcos_get_stream
PDF Functions


Get contents of pCOS path with type stream, fstream, or string

PDF_pcos_get_number
PDF_pcos_get_string
PDF Functions
PHP Manual

PDF_pcos_get_stream

(PECL pdflib >= 2.1.0)

PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string

Description

string PDF_pcos_get_stream ( resource $p , int $doc , string $optlist , string $path )

Gets the contents of a pCOS path with type stream, fstream, or string.

PDF_pcos_get_number
PDF_pcos_get_string
PDF Functions


Get value of pCOS path with type name, string, or boolean

PDF_pcos_get_stream
PDF_place_image
PDF Functions
PHP Manual

PDF_pcos_get_string

(PECL pdflib >= 2.1.0)

PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean

Description

string PDF_pcos_get_string ( resource $p , int $doc , string $path )

Gets the value of a pCOS path with type name, string, or boolean.

PDF_pcos_get_stream
PDF_place_image
PDF Functions


Place image on the page [deprecated]

PDF_pcos_get_string
PDF_place_pdi_page
PDF Functions
PHP Manual

PDF_place_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_place_image — Place image on the page [deprecated]

Description

bool PDF_place_image ( resource $pdfdoc , int $image , float $x , float $y , float $scale )

Places an image and scales it. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 5, use PDF_fit_image() instead.

PDF_pcos_get_string
PDF_place_pdi_page
PDF Functions


Place PDF page [deprecated]

PDF_place_image
PDF_process_pdi
PDF Functions
PHP Manual

PDF_place_pdi_page

(PHP 4 >= 4.0.6, PECL pdflib >= 1.0.0)

PDF_place_pdi_page — Place PDF page [deprecated]

Description

bool PDF_place_pdi_page ( resource $pdfdoc , int $page , float $x , float $y , float $sx , float $sy )

Places a PDF page and scales it. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 5, use PDF_fit_pdi_page() instead.

PDF_place_image
PDF_process_pdi
PDF Functions


Process imported PDF document

PDF_place_pdi_page
PDF_rect
PDF Functions
PHP Manual

PDF_process_pdi

(PECL pdflib >= 2.0.0)

PDF_process_pdi — Process imported PDF document

Description

int PDF_process_pdi ( resource $pdfdoc , int $doc , int $page , string $optlist )

Processes certain elements of an imported PDF document.

PDF_place_pdi_page
PDF_rect
PDF Functions


Draw rectangle

PDF_process_pdi
PDF_restore
PDF Functions
PHP Manual

PDF_rect

(PHP 4, PECL pdflib >= 1.0.0)

PDF_rect — Draw rectangle

Description

bool PDF_rect ( resource $p , float $x , float $y , float $width , float $height )

Draws a rectangle. Returns TRUE on success or FALSE on failure.

PDF_process_pdi
PDF_restore
PDF Functions


Restore graphics state

PDF_rect
PDF_resume_page
PDF Functions
PHP Manual

PDF_restore

(PHP 4, PECL pdflib >= 1.0.0)

PDF_restore — Restore graphics state

Description

bool PDF_restore ( resource $p )

Restores the most recently saved graphics state. Returns TRUE on success or FALSE on failure.

PDF_rect
PDF_resume_page
PDF Functions


Resume page

PDF_restore
PDF_rotate
PDF Functions
PHP Manual

PDF_resume_page

(PECL pdflib >= 2.0.0)

PDF_resume_page — Resume page

Description

bool PDF_resume_page ( resource $pdfdoc , string $optlist )

Resumes a page to add more content to it.

PDF_restore
PDF_rotate
PDF Functions


Rotate coordinate system

PDF_resume_page
PDF_save
PDF Functions
PHP Manual

PDF_rotate

(PHP 4, PECL pdflib >= 1.0.0)

PDF_rotate — Rotate coordinate system

Description

bool PDF_rotate ( resource $p , float $phi )

Rotates the coordinate system. Returns TRUE on success or FALSE on failure.

PDF_resume_page
PDF_save
PDF Functions


Save graphics state

PDF_rotate
PDF_scale
PDF Functions
PHP Manual

PDF_save

(PHP 4, PECL pdflib >= 1.0.0)

PDF_save — Save graphics state

Description

bool PDF_save ( resource $p )

Saves the current graphics state. Returns TRUE on success or FALSE on failure.

PDF_rotate
PDF_scale
PDF Functions


Scale coordinate system

PDF_save
PDF_set_border_color
PDF Functions
PHP Manual

PDF_scale

(PHP 4, PECL pdflib >= 1.0.0)

PDF_scale — Scale coordinate system

Description

bool PDF_scale ( resource $p , float $sx , float $sy )

Scales the coordinate system. Returns TRUE on success or FALSE on failure.

PDF_save
PDF_set_border_color
PDF Functions


Set border color of annotations [deprecated]

PDF_scale
PDF_set_border_dash
PDF Functions
PHP Manual

PDF_set_border_color

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_border_color — Set border color of annotations [deprecated]

Description

bool PDF_set_border_color ( resource $p , float $red , float $green , float $blue )

Sets the border color for all kinds of annotations. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use the option annotcolor in PDF_create_annotation() instead.

PDF_scale
PDF_set_border_dash
PDF Functions


Set border dash style of annotations [deprecated]

PDF_set_border_color
PDF_set_border_style
PDF Functions
PHP Manual

PDF_set_border_dash

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_border_dash — Set border dash style of annotations [deprecated]

Description

bool PDF_set_border_dash ( resource $pdfdoc , float $black , float $white )

Sets the border dash style for all kinds of annotations. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use the option dasharray in PDF_create_annotation() instead.

PDF_set_border_color
PDF_set_border_style
PDF Functions


Set border style of annotations [deprecated]

PDF_set_border_dash
PDF_set_char_spacing
PDF Functions
PHP Manual

PDF_set_border_style

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_border_style — Set border style of annotations [deprecated]

Description

bool PDF_set_border_style ( resource $pdfdoc , string $style , float $width )

Sets the border style for all kinds of annotations. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use the options borderstyle and linewidth in PDF_create_annotation() instead.

PDF_set_border_dash
PDF_set_char_spacing
PDF Functions


Set character spacing [deprecated]

PDF_set_border_style
PDF_set_duration
PDF Functions
PHP Manual

PDF_set_char_spacing

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_char_spacing — Set character spacing [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with parameter charspacing instead.

PDF_set_border_style
PDF_set_duration
PDF Functions


Set duration between pages [deprecated]

PDF_set_char_spacing
PDF_set_gstate
PDF Functions
PHP Manual

PDF_set_duration

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_duration — Set duration between pages [deprecated]

Description

This function is deprecated since PDFlib version 3, use the duration option in PDF_begin_page_ext() or PDF_end_page_ext() instead.

PDF_set_char_spacing
PDF_set_gstate
PDF Functions


Activate graphics state object

PDF_set_duration
PDF_set_horiz_scaling
PDF Functions
PHP Manual

PDF_set_gstate

(PECL pdflib >= 2.0.0)

PDF_set_gstate — Activate graphics state object

Description

bool PDF_set_gstate ( resource $pdfdoc , int $gstate )

Activates a graphics state object.

PDF_set_duration
PDF_set_horiz_scaling
PDF Functions


Set horizontal text scaling [deprecated]

PDF_set_gstate
PDF_set_info_author
PDF Functions
PHP Manual

PDF_set_horiz_scaling

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_horiz_scaling — Set horizontal text scaling [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with parameter horizscaling instead.

PDF_set_gstate
PDF_set_info_author
PDF Functions


Fill document info field

PDF_set_info_title
PDF_set_layer_dependency
PDF Functions
PHP Manual

PDF_set_info

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_info — Fill document info field

Description

bool PDF_set_info ( resource $p , string $key , string $value )

Fill document information field key with value . Returns TRUE on success or FALSE on failure.

PDF_set_info_title
PDF_set_layer_dependency
PDF Functions


Fill the author document info field [deprecated]

PDF_set_horiz_scaling
PDF_set_info_creator
PDF Functions
PHP Manual

PDF_set_info_author

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_author — Fill the author document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

PDF_set_horiz_scaling
PDF_set_info_creator
PDF Functions


Fill the creator document info field [deprecated]

PDF_set_info_author
PDF_set_info_keywords
PDF Functions
PHP Manual

PDF_set_info_creator

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_creator — Fill the creator document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

PDF_set_info_author
PDF_set_info_keywords
PDF Functions


Fill the keywords document info field [deprecated]

PDF_set_info_creator
PDF_set_info_subject
PDF Functions
PHP Manual

PDF_set_info_keywords

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_keywords — Fill the keywords document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

PDF_set_info_creator
PDF_set_info_subject
PDF Functions


Fill the subject document info field [deprecated]

PDF_set_info_keywords
PDF_set_info_title
PDF Functions
PHP Manual

PDF_set_info_subject

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_subject — Fill the subject document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

PDF_set_info_keywords
PDF_set_info_title
PDF Functions


Fill the title document info field [deprecated]

PDF_set_info_subject
PDF_set_info
PDF Functions
PHP Manual

PDF_set_info_title

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_title — Fill the title document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

PDF_set_info_subject
PDF_set_info
PDF Functions


Define relationships among layers

PDF_set_info
PDF_set_leading
PDF Functions
PHP Manual

PDF_set_layer_dependency

(PECL pdflib >= 2.0.0)

PDF_set_layer_dependency — Define relationships among layers

Description

bool PDF_set_layer_dependency ( resource $pdfdoc , string $type , string $optlist )

Defines hierarchical and group relationships among layers. Returns TRUE on success or FALSE on failure.

This function requires PDF 1.5.

PDF_set_info
PDF_set_leading
PDF Functions


Set distance between text lines [deprecated]

PDF_set_layer_dependency
PDF_set_parameter
PDF Functions
PHP Manual

PDF_set_leading

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_leading — Set distance between text lines [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the parameter leading instead.

PDF_set_layer_dependency
PDF_set_parameter
PDF Functions


Set string parameter

PDF_set_leading
PDF_set_text_matrix
PDF Functions
PHP Manual

PDF_set_parameter

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_parameter — Set string parameter

Description

bool PDF_set_parameter ( resource $p , string $key , string $value )

Sets some PDFlib parameter with string type. Returns TRUE on success or FALSE on failure.

PDF_set_leading
PDF_set_text_matrix
PDF Functions


Set text matrix [deprecated]

PDF_set_parameter
PDF_set_text_pos
PDF Functions
PHP Manual

PDF_set_text_matrix

(PHP 4 <= 4.0.4)

PDF_set_text_matrix — Set text matrix [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_scale(), PDF_translate(), PDF_rotate(), or PDF_skew() instead.

PDF_set_parameter
PDF_set_text_pos
PDF Functions


Set text position

PDF_set_text_matrix
PDF_set_text_rendering
PDF Functions
PHP Manual

PDF_set_text_pos

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_pos — Set text position

Description

bool PDF_set_text_pos ( resource $p , float $x , float $y )

Sets the position for text output on the page. Returns TRUE on success or FALSE on failure.

PDF_set_text_matrix
PDF_set_text_rendering
PDF Functions


Determine text rendering [deprecated]

PDF_set_text_pos
PDF_set_text_rise
PDF Functions
PHP Manual

PDF_set_text_rendering

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_rendering — Determine text rendering [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the textrendering parameter instead.

PDF_set_text_pos
PDF_set_text_rise
PDF Functions


Set text rise [deprecated]

PDF_set_text_rendering
PDF_set_value
PDF Functions
PHP Manual

PDF_set_text_rise

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_rise — Set text rise [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the textrise parameter instead.

PDF_set_text_rendering
PDF_set_value
PDF Functions


Set numerical parameter

PDF_set_text_rise
PDF_set_word_spacing
PDF Functions
PHP Manual

PDF_set_value

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_value — Set numerical parameter

Description

bool PDF_set_value ( resource $p , string $key , float $value )

Sets the value of some PDFlib parameter with numerical type. Returns TRUE on success or FALSE on failure.

PDF_set_text_rise
PDF_set_word_spacing
PDF Functions


Set spacing between words [deprecated]

PDF_set_value
PDF_setcolor
PDF Functions
PHP Manual

PDF_set_word_spacing

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_word_spacing — Set spacing between words [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the wordspacing parameter instead.

PDF_set_value
PDF_setcolor
PDF Functions


Set fill and stroke color

PDF_set_word_spacing
PDF_setdash
PDF Functions
PHP Manual

PDF_setcolor

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setcolor — Set fill and stroke color

Description

bool PDF_setcolor ( resource $p , string $fstype , string $colorspace , float $c1 , float $c2 , float $c3 , float $c4 )

Sets the current color space and color. Returns TRUE on success or FALSE on failure.

PDF_set_word_spacing
PDF_setdash
PDF Functions


Set simple dash pattern

PDF_setcolor
PDF_setdashpattern
PDF Functions
PHP Manual

PDF_setdash

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setdash — Set simple dash pattern

Description

bool PDF_setdash ( resource $pdfdoc , float $b , float $w )

Sets the current dash pattern to b black and w white units. Returns TRUE on success or FALSE on failure.

PDF_setcolor
PDF_setdashpattern
PDF Functions


Set dash pattern

PDF_setdash
PDF_setflat
PDF Functions
PHP Manual

PDF_setdashpattern

(PECL pdflib >= 2.0.0)

PDF_setdashpattern — Set dash pattern

Description

bool PDF_setdashpattern ( resource $pdfdoc , string $optlist )

Sets a dash pattern defined by an option list. Returns TRUE on success or FALSE on failure.

PDF_setdash
PDF_setflat
PDF Functions


Set flatness

PDF_setdashpattern
PDF_setfont
PDF Functions
PHP Manual

PDF_setflat

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setflat — Set flatness

Description

bool PDF_setflat ( resource $pdfdoc , float $flatness )

Sets the flatness parameter. Returns TRUE on success or FALSE on failure.

PDF_setdashpattern
PDF_setfont
PDF Functions


Set font

PDF_setflat
PDF_setgray_fill
PDF Functions
PHP Manual

PDF_setfont

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setfont — Set font

Description

bool PDF_setfont ( resource $pdfdoc , int $font , float $fontsize )

Sets the current font in the specified size , using a font handle returned by PDF_load_font(). Returns TRUE on success or FALSE on failure.

PDF_setflat
PDF_setgray_fill
PDF Functions


Set color to gray [deprecated]

PDF_setgray_stroke
PDF_setlinecap
PDF Functions
PHP Manual

PDF_setgray

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray — Set color to gray [deprecated]

Description

bool PDF_setgray ( resource $p , float $g )

Sets the current fill and stroke color to a gray value between 0 and 1 inclusive. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setgray_stroke
PDF_setlinecap
PDF Functions


Set fill color to gray [deprecated]

PDF_setfont
PDF_setgray_stroke
PDF Functions
PHP Manual

PDF_setgray_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray_fill — Set fill color to gray [deprecated]

Description

bool PDF_setgray_fill ( resource $p , float $g )

Sets the current fill color to a gray value between 0 and 1 inclusive. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setfont
PDF_setgray_stroke
PDF Functions


Set stroke color to gray [deprecated]

PDF_setgray_fill
PDF_setgray
PDF Functions
PHP Manual

PDF_setgray_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray_stroke — Set stroke color to gray [deprecated]

Description

bool PDF_setgray_stroke ( resource $p , float $g )

Sets the current stroke color to a gray value between 0 and 1 inclusive. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setgray_fill
PDF_setgray
PDF Functions


Set linecap parameter

PDF_setgray
PDF_setlinejoin
PDF Functions
PHP Manual

PDF_setlinecap

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinecap — Set linecap parameter

Description

bool PDF_setlinecap ( resource $p , int $linecap )

Sets the linecap parameter to control the shape at the end of a path with respect to stroking.

PDF_setgray
PDF_setlinejoin
PDF Functions


Set linejoin parameter

PDF_setlinecap
PDF_setlinewidth
PDF Functions
PHP Manual

PDF_setlinejoin

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinejoin — Set linejoin parameter

Description

bool PDF_setlinejoin ( resource $p , int $value )

Sets the linejoin parameter to specify the shape at the corners of paths that are stroked. Returns TRUE on success or FALSE on failure.

PDF_setlinecap
PDF_setlinewidth
PDF Functions


Set line width

PDF_setlinejoin
PDF_setmatrix
PDF Functions
PHP Manual

PDF_setlinewidth

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinewidth — Set line width

Description

bool PDF_setlinewidth ( resource $p , float $width )

Sets the current line width. Returns TRUE on success or FALSE on failure.

PDF_setlinejoin
PDF_setmatrix
PDF Functions


Set current transformation matrix

PDF_setlinewidth
PDF_setmiterlimit
PDF Functions
PHP Manual

PDF_setmatrix

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setmatrix — Set current transformation matrix

Description

bool PDF_setmatrix ( resource $p , float $a , float $b , float $c , float $d , float $e , float $f )

Explicitly sets the current transformation matrix. Returns TRUE on success or FALSE on failure.

PDF_setlinewidth
PDF_setmiterlimit
PDF Functions


Set miter limit

PDF_setmatrix
PDF_setpolydash
PDF Functions
PHP Manual

PDF_setmiterlimit

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setmiterlimit — Set miter limit

Description

bool PDF_setmiterlimit ( resource $pdfdoc , float $miter )

Sets the miter limit.Returns TRUE on success or FALSE on failure.

PDF_setmatrix
PDF_setpolydash
PDF Functions


Set complicated dash pattern [deprecated]

PDF_setmiterlimit
PDF_setrgbcolor_fill
PDF Functions
PHP Manual

PDF_setpolydash

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setpolydash — Set complicated dash pattern [deprecated]

Description

This function is deprecated since PDFlib version 5, use PDF_setdashpattern() instead.

PDF_setmiterlimit
PDF_setrgbcolor_fill
PDF Functions


Set fill and stroke rgb color values [deprecated]

PDF_setrgbcolor_stroke
PDF_shading_pattern
PDF Functions
PHP Manual

PDF_setrgbcolor

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor — Set fill and stroke rgb color values [deprecated]

Description

bool PDF_setrgbcolor ( resource $p , float $red , float $green , float $blue )

Sets the current fill and stroke color to the supplied RGB values. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setrgbcolor_stroke
PDF_shading_pattern
PDF Functions


Set fill rgb color values [deprecated]

PDF_setpolydash
PDF_setrgbcolor_stroke
PDF Functions
PHP Manual

PDF_setrgbcolor_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor_fill — Set fill rgb color values [deprecated]

Description

bool PDF_setrgbcolor_fill ( resource $p , float $red , float $green , float $blue )

Sets the current fill color to the supplied RGB values. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setpolydash
PDF_setrgbcolor_stroke
PDF Functions


Set stroke rgb color values [deprecated]

PDF_setrgbcolor_fill
PDF_setrgbcolor
PDF Functions
PHP Manual

PDF_setrgbcolor_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor_stroke — Set stroke rgb color values [deprecated]

Description

bool PDF_setrgbcolor_stroke ( resource $p , float $red , float $green , float $blue )

Sets the current stroke color to the supplied RGB values. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setrgbcolor_fill
PDF_setrgbcolor
PDF Functions


Define blend

PDF_shading_pattern
PDF_shfill
PDF Functions
PHP Manual

PDF_shading

(PECL pdflib >= 2.0.0)

PDF_shading — Define blend

Description

int PDF_shading ( resource $pdfdoc , string $shtype , float $x0 , float $y0 , float $x1 , float $y1 , float $c1 , float $c2 , float $c3 , float $c4 , string $optlist )

Defines a blend from the current fill color to another color.

This function requires PDF 1.4 or above.

PDF_shading_pattern
PDF_shfill
PDF Functions


Define shading pattern

PDF_setrgbcolor
PDF_shading
PDF Functions
PHP Manual

PDF_shading_pattern

(PECL pdflib >= 2.0.0)

PDF_shading_pattern — Define shading pattern

Description

int PDF_shading_pattern ( resource $pdfdoc , int $shading , string $optlist )

Defines a shading pattern using a shading object.

This function requires PDF 1.4 or above.

PDF_setrgbcolor
PDF_shading
PDF Functions


Fill area with shading

PDF_shading
PDF_show_boxed
PDF Functions
PHP Manual

PDF_shfill

(PECL pdflib >= 2.0.0)

PDF_shfill — Fill area with shading

Description

bool PDF_shfill ( resource $pdfdoc , int $shading )

Fills an area with a shading, based on a shading object.

This function requires PDF 1.4 or above.

PDF_shading
PDF_show_boxed
PDF Functions


Output text at current position

PDF_show_xy
PDF_skew
PDF Functions
PHP Manual

PDF_show

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show — Output text at current position

Description

bool PDF_show ( resource $pdfdoc , string $text )

Prints text in the current font and size at the current position. Returns TRUE on success or FALSE on failure.

PDF_show_xy
PDF_skew
PDF Functions


Output text in a box [deprecated]

PDF_shfill
PDF_show_xy
PDF Functions
PHP Manual

PDF_show_boxed

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show_boxed — Output text in a box [deprecated]

Description

int PDF_show_boxed ( resource $p , string $text , float $left , float $top , float $width , float $height , string $mode , string $feature )

This function is deprecated since PDFlib version 6, use PDF_fit_textline() for single lines, or the PDF_*_textflow() functions for multi-line formatting instead.

PDF_shfill
PDF_show_xy
PDF Functions


Output text at given position

PDF_show_boxed
PDF_show
PDF Functions
PHP Manual

PDF_show_xy

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show_xy — Output text at given position

Description

bool PDF_show_xy ( resource $p , string $text , float $x , float $y )

Prints text in the current font. Returns TRUE on success or FALSE on failure.

PDF_show_boxed
PDF_show
PDF Functions


Skew the coordinate system

PDF_show
PDF_stringwidth
PDF Functions
PHP Manual

PDF_skew

(PHP 4, PECL pdflib >= 1.0.0)

PDF_skew — Skew the coordinate system

Description

bool PDF_skew ( resource $p , float $alpha , float $beta )

Skews the coordinate system in x and y direction by alpha and beta degrees. Returns TRUE on success or FALSE on failure.

PDF_show
PDF_stringwidth
PDF Functions


Return width of text

PDF_skew
PDF_stroke
PDF Functions
PHP Manual

PDF_stringwidth

(PHP 4, PECL pdflib >= 1.0.0)

PDF_stringwidth — Return width of text

Description

float PDF_stringwidth ( resource $p , string $text , int $font , float $fontsize )

Returns the width of text in an arbitrary font.

PDF_skew
PDF_stroke
PDF Functions


Stroke path

PDF_stringwidth
PDF_suspend_page
PDF Functions
PHP Manual

PDF_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_stroke — Stroke path

Description

bool PDF_stroke ( resource $p )

Strokes the path with the current color and line width, and clear it. Returns TRUE on success or FALSE on failure.

PDF_stringwidth
PDF_suspend_page
PDF Functions


Suspend page

PDF_stroke
PDF_translate
PDF Functions
PHP Manual

PDF_suspend_page

(PECL pdflib >= 2.0.0)

PDF_suspend_page — Suspend page

Description

bool PDF_suspend_page ( resource $pdfdoc , string $optlist )

Suspends the current page so that it can later be resumed with PDF_resume_page().

PDF_stroke
PDF_translate
PDF Functions


Set origin of coordinate system

PDF_suspend_page
PDF_utf16_to_utf8
PDF Functions
PHP Manual

PDF_translate

(PHP 4, PECL pdflib >= 1.0.0)

PDF_translate — Set origin of coordinate system

Description

bool PDF_translate ( resource $p , float $tx , float $ty )

Translates the origin of the coordinate system.

PDF_suspend_page
PDF_utf16_to_utf8
PDF Functions


Convert string from UTF-8 to UTF-16

PDF_utf32_to_utf16
PS
PDF Functions
PHP Manual

PDF_utf8_to_utf16

(PECL pdflib >= 2.0.3)

PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16

Description

string PDF_utf8_to_utf16 ( resource $pdfdoc , string $utf8string , string $ordering )

Converts a string from UTF-8 format to UTF-16.

PDF_utf32_to_utf16
PS
PDF Functions


Convert string from UTF-16 to UTF-8

PDF_translate
PDF_utf32_to_utf16
PDF Functions
PHP Manual

PDF_utf16_to_utf8

(PECL pdflib >= 2.0.3)

PDF_utf16_to_utf8 — Convert string from UTF-16 to UTF-8

Description

string PDF_utf16_to_utf8 ( resource $pdfdoc , string $utf16string )

Converts a string from UTF-16 format to UTF-8.

PDF_translate
PDF_utf32_to_utf16
PDF Functions


Convert string from UTF-32 to UTF-16

PDF_utf16_to_utf8
PDF_utf8_to_utf16
PDF Functions
PHP Manual

PDF_utf32_to_utf16

(PECL pdflib >= Unknown future)

PDF_utf32_to_utf16 — Convert string from UTF-32 to UTF-16

Description

string PDF_utf32_to_utf16 ( resource $pdfdoc , string $utf32string , string $ordering )

Converts a string from UTF-32 format to UTF-16.

PDF_utf16_to_utf8
PDF_utf8_to_utf16
PDF Functions


Creates a new large object

PDO_PGSQL DSN
PDO::pgsqlLOBOpen
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlLOBCreate

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBCreate — Creates a new large object

Description

string PDO::pgsqlLOBCreate ( void )

PDO::pgsqlLOBCreate() creates a large object and returns the OID of that object. You may then open a stream on the object using PDO::pgsqlLOBOpen() to read or write data to it. The OID can be stored in columns of type OID and be used to reference the large object, without causing the row to grow arbitrarily large. The large object will continue to live in the database until it is removed by calling PDO::pgsqlLOBUnlink().

Large objects can be up to 2GB in size, but are cumbersome to use; you need to ensure that PDO::pgsqlLOBUnlink() is called prior to deleting the last row that references its OID from your database. In addition, large objects have no access controls. As an alternative, try the bytea column type; recent versions of PostgreSQL allow bytea columns of up to 1GB in size and transparently manage the storage for optimal row size.

Note: This function must be called within a transaction.

Parameters

PDO::pgsqlLOBCreate() takes no parameters.

Return Values

Returns the OID of the newly created large object on success, or FALSE on failure.

Examples

Example #1 A PDO::pgsqlLOBCreate() example

This example creates a new large object and copies the contents of a file into it. The OID is then stored into a table.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$oid = $db->pgsqlLOBCreate();
$stream = $db->pgsqlLOBOpen($oid, 'w');
$local = fopen($filename, 'rb');
stream_copy_to_stream($local, $stream);
$local = null;
$stream = null;
$stmt = $db->prepare("INSERT INTO BLOBS (ident, oid) VALUES (?, ?)");
$stmt->execute(array($some_id, $oid));
$db->commit();
?>

See Also

  • PDO::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_create() - Create a large object

PDO_PGSQL DSN
PDO::pgsqlLOBOpen
PostgreSQL (PDO)


Opens an existing large object stream

PDO::pgsqlLOBCreate
PDO::pgsqlLOBUnlink
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlLOBOpen

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBOpen — Opens an existing large object stream

Description

resource PDO::pgsqlLOBOpen ( string $oid [, string $mode = "rb" ] )

PDO::pgsqlLOBOpen() opens a stream to access the data referenced by oid . If mode is r, the stream is opened for reading, if mode is w, then the stream will be opened for writing. You can use all the usual filesystem functions, such as fread(), fwrite() and fgets() to manipulate the contents of the stream.

Note: This function, and all manipulations of the large object, must be called and carried out within a transaction.

Parameters

oid

A large object identifier.

mode

If mode is r, open the stream for reading. If mode is w, open the stream for writing.

Return Values

Returns a stream resource on success or FALSE on failure.

Examples

Example #1 A PDO::pgsqlLOBOpen() example

Following on from the PDO::pgsqlLOBCreate() example, this code snippet retrieves the large object from the database and outputs it to the browser.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("select oid from BLOBS where ident = ?");
$stmt->execute(array($some_id));
$stmt->bindColumn('oid', $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
fpassthru($lob);
?>

See Also

  • PDO::pgsqlLOBCreate() - Creates a new large object
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_open() - Open a large object

PDO::pgsqlLOBCreate
PDO::pgsqlLOBUnlink
PostgreSQL (PDO)


Deletes the large object

PDO::pgsqlLOBOpen
SQLite (PDO)
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlLOBUnlink

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBUnlink — Deletes the large object

Description

bool PDO::pgsqlLOBUnlink ( string $oid )

Deletes a large object from the database identified by OID.

Note: This function must be called within a transaction.

Parameters

oid

A large object identifier

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A PDO::pgsqlLOBUnlink() example

This example unlinks a large object from the database prior to deleting the row that references it from the blobs table we've been using in our PDO::pgsqlLOBCreate() and PDO::pgsqlLOBOpen() examples.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$db->pgsqlLOBUnlink($oid);
$stmt = $db->prepare("DELETE FROM BLOBS where ident = ?");
$stmt->execute(array($some_id));
$db->commit();
?>

See Also

  • PDO::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBCreate() - Creates a new large object

PDO::pgsqlLOBOpen
SQLite (PDO)
PostgreSQL (PDO)


Registers an aggregating User Defined Function for use in SQL statements

PDO_SQLITE DSN
PDO::sqliteCreateFunction
SQLite (PDO)
PHP Manual

PDO::sqliteCreateAggregate

(PHP 5 >= 5.1.0, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements

Description

PDO
bool sqliteCreateAggregate ( string $function_name , callback $step_func , callback $finalize_func [, int $num_args ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

This method is similar to PDO::sqliteCreateFunction except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this method and PDO::sqliteCreateFunction is that two functions are required to manage the aggregate.

Parameters

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set. Your PHP function should accumulate the result and store it in the aggregation context.

This function need to be defined as:

step ( mixed $context , int $rownumber , mixed $value1 [, mixed $value2 [, mixed $.. ]] )

context will be NULL for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain the aggregate state.

rownumber will hold the current row number.

finalize_func

Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

This function need to be defined as:

fini ( mixed $context , int $rownumber )

context will hold the return value from the very last call to the step function.

rownumber will hold the number of rows over which the aggregate was performed.

The return value of this function will be used as the return value for the aggregate.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = new PDO('sqlite::memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
    $insert->execute(array($str));
}
$insert = null;

function max_len_step(&$context, $rownumber, $string)
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
    return $context;
}

function max_len_finalize(&$context, $rownumber)
{
    return $context;
}

$db->sqliteCreateAggregate('max_len', 'max_len_step', 'max_len_finalize');

var_dump($db->query('SELECT max_len(a) from strings')->fetchAll());

?>

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the context . In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Tip

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Tip

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

Note: This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

See Also

  • PDO::sqliteCreateFunction
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

PDO_SQLITE DSN
PDO::sqliteCreateFunction
SQLite (PDO)


Registers a User Defined Function for use in SQL statements

PDO::sqliteCreateAggregate
Driver 4D for PDO
SQLite (PDO)
PHP Manual

PDO::sqliteCreateFunction

(PHP 5 >= 5.1.0, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateFunction — Registers a User Defined Function for use in SQL statements

Description

PDO
bool sqliteCreateFunction ( string $function_name , callback $callback [, int $num_args ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

This method allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

Parameters

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

Note: Callback functions should return a type understood by SQLite (i.e. scalar type).

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 PDO::sqliteCreateFunction() example

<?php
function md5_and_reverse($string)
{
    return strrev(md5($string));
}

$db = new PDO('sqlite:sqlitedb');
$db->sqliteCreateFunction('md5rev', 'md5_and_reverse', 1);
$rows = $db->query('SELECT md5rev(filename) FROM files')->fetchAll();
?>

In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that you do not need to process the result using a foreach loop after you have queried for the data.

Tip

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

Note: This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

See Also

  • PDO::sqliteCreateAggregate
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

PDO::sqliteCreateAggregate
Driver 4D for PDO
SQLite (PDO)


Returns number of affected records (tuples)

PostgreSQL Functions
pg_cancel_query
PostgreSQL Functions
PHP Manual

pg_affected_rows

(PHP 4 >= 4.2.0, PHP 5)

pg_affected_rows — Returns number of affected records (tuples)

Description

int pg_affected_rows ( resource $result )

pg_affected_rows() returns the number of tuples (instances/records/rows) affected by INSERT, UPDATE, and DELETE queries.

Note: This function used to be called pg_cmdtuples().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

The number of rows affected by the query. If no tuple is affected, it will return 0.

Examples

Example #1 pg_affected_rows() example

<?php
$result = pg_query($conn, "INSERT INTO authors VALUES ('Orwell', 2002, 'Animal Farm')");

$cmdtuples = pg_affected_rows($result);

echo $cmdtuples . " tuples are affected.\n";
?>

The above example will output:

1 tuples are affected.

See Also

  • pg_query() - Execute a query
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_num_rows() - Returns the number of rows in a result

PostgreSQL Functions
pg_cancel_query
PostgreSQL Functions


Cancel an asynchronous query

pg_affected_rows
pg_client_encoding
PostgreSQL Functions
PHP Manual

pg_cancel_query

(PHP 4 >= 4.2.0, PHP 5)

pg_cancel_query — Cancel an asynchronous query

Description

bool pg_cancel_query ( resource $connection )

pg_cancel_query() cancels an asynchronous query sent with pg_send_query(), pg_send_query_params() or pg_send_execute(). You cannot cancel a query executed using pg_query().

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_cancel_query() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
  }

  $res1 = pg_get_result($dbconn);
  echo "First call to pg_get_result(): $res1\n";
  $rows1 = pg_num_rows($res1);
  echo "$res1 has $rows1 records\n\n";

  // Cancel the currently running query.  Will be the second query if it is
  // still running.
  pg_cancel_query($dbconn);
?>

The above example will output:

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

See Also

  • pg_send_query() - Sends asynchronous query
  • pg_connection_busy() - Get connection is busy or not

pg_affected_rows
pg_client_encoding
PostgreSQL Functions


Gets the client encoding

pg_cancel_query
pg_close
PostgreSQL Functions
PHP Manual

pg_client_encoding

(PHP 4 >= 4.0.3, PHP 5)

pg_client_encoding — Gets the client encoding

Description

string pg_client_encoding ([ resource $connection ] )

PostgreSQL supports automatic character set conversion between server and client for certain character sets. pg_client_encoding() returns the client encoding as a string. The returned string will be one of the standard PostgreSQL encoding identifiers.

Note: This function requires PHP 4.0.3 or higher and PostgreSQL 7.0 or higher. If libpq is compiled without multibyte encoding support, pg_client_encoding() always returns SQL_ASCII. Supported encoding depends on PostgreSQL version. Refer to the PostgreSQL Documentation supported encodings.
The function used to be called pg_clientencoding().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

The client encoding, or FALSE on error.

Examples

Example #1 pg_client_encoding() example

<?php
// Assume $conn is a connection to a ISO-8859-1 database
$encoding = pg_client_encoding($conn);

echo "Client encoding is: ", $encoding, "\n";
?>

The above example will output:

Client encoding is: ISO-8859-1

See Also

  • pg_set_client_encoding() - Set the client encoding

pg_cancel_query
pg_close
PostgreSQL Functions


Closes a PostgreSQL connection

pg_client_encoding
pg_connect
PostgreSQL Functions
PHP Manual

pg_close

(PHP 4, PHP 5)

pg_close — Closes a PostgreSQL connection

Description

bool pg_close ([ resource $connection ] )

pg_close() closes the non-persistent connection to a PostgreSQL database associated with the given connection resource.

Note: Using pg_close() is not usually necessary, as non-persistent open connections are automatically closed at the end of the script.

If there is open large object resource on the connection, do not close the connection before closing all large object resources.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_close() example

<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
   or die("Could not connect");
echo "Connected successfully";
pg_close($dbconn);
?>

The above example will output:

Connected successfully

See Also

  • pg_connect() - Open a PostgreSQL connection

pg_client_encoding
pg_connect
PostgreSQL Functions


Open a PostgreSQL connection

pg_close
pg_connection_busy
PostgreSQL Functions
PHP Manual

pg_connect

(PHP 4, PHP 5)

pg_connect — Open a PostgreSQL connection

Description

resource pg_connect ( string $connection_string [, int $connect_type ] )

pg_connect() opens a connection to a PostgreSQL database specified by the connection_string .

If a second call is made to pg_connect() with the same connection_string as an existing connection, the existing connection will be returned unless you pass PGSQL_CONNECT_FORCE_NEW as connect_type .

The old syntax with multiple parameters $conn = pg_connect("host", "port", "options", "tty", "dbname") has been deprecated.

Parameters

connection_string

The connection_string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e., \' and \\.

The currently recognized parameter keywords are: host , hostaddr , port , dbname , user , password , connect_timeout , options , tty (ignored), sslmode , requiressl (deprecated in favor of sslmode ), and service . Which of these arguments exist depends on your PostgreSQL version.

connect_type

If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection is created, even if the connection_string is identical to an existing connection.

Return Values

PostgreSQL connection resource on success, FALSE on failure.

Examples

Example #1 Using pg_connect()

<?php
$dbconn = pg_connect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_connect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password

$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_connect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
?>

See Also

  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_close() - Closes a PostgreSQL connection
  • pg_host() - Returns the host name associated with the connection
  • pg_port() - Return the port number associated with the connection
  • pg_tty() - Return the TTY name associated with the connection
  • pg_options() - Get the options associated with the connection
  • pg_dbname() - Get the database name

pg_close
pg_connection_busy
PostgreSQL Functions


Get connection is busy or not

pg_connect
pg_connection_reset
PostgreSQL Functions
PHP Manual

pg_connection_busy

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_busy — Get connection is busy or not

Description

bool pg_connection_busy ( resource $connection )

pg_connection_busy() determines whether or not a connection is busy. If it is busy, a previous query is still executing. If pg_get_result() is used on the connection, it will be blocked.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE if the connection is busy, FALSE otherwise.

Examples

Example #1 pg_connection_busy() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $bs = pg_connection_busy($dbconn);
  if ($bs) {
      echo 'connection is busy';
  } else {
     echo 'connection is not busy';
  }
?>

See Also

  • pg_connection_status() - Get connection status
  • pg_get_result() - Get asynchronous query result

pg_connect
pg_connection_reset
PostgreSQL Functions


Reset connection (reconnect)

pg_connection_busy
pg_connection_status
PostgreSQL Functions
PHP Manual

pg_connection_reset

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_reset — Reset connection (reconnect)

Description

bool pg_connection_reset ( resource $connection )

pg_connection_reset() resets the connection. It is useful for error recovery.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_connection_reset() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $dbconn2 = pg_connection_reset($dbconn);
  if ($dbconn2) {
      echo "reset successful\n";
  } else {
      echo "reset failed\n";
  }
?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_connection_status() - Get connection status

pg_connection_busy
pg_connection_status
PostgreSQL Functions


Get connection status

pg_connection_reset
pg_convert
PostgreSQL Functions
PHP Manual

pg_connection_status

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_status — Get connection status

Description

int pg_connection_status ( resource $connection )

pg_connection_status() returns the status of the specified connection .

Parameters

connection

PostgreSQL database connection resource.

Return Values

PGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD.

Examples

Example #1 pg_connection_status() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $stat = pg_connection_status($dbconn);
  if ($stat === PGSQL_CONNECTION_OK) {
      echo 'Connection status ok';
  } else {
      echo 'Connection status bad';
  }
?>

See Also

  • pg_connection_busy() - Get connection is busy or not

pg_connection_reset
pg_convert
PostgreSQL Functions


Convert associative array values into suitable for SQL statement

pg_connection_status
pg_copy_from
PostgreSQL Functions
PHP Manual

pg_convert

(PHP 4 >= 4.3.0, PHP 5)

pg_convert — Convert associative array values into suitable for SQL statement

Description

array pg_convert ( resource $connection , string $table_name , array $assoc_array [, int $options = 0 ] )

pg_convert() checks and converts the values in assoc_array into suitable values for use in a SQL statement. Precondition for pg_convert() is the existence of a table table_name which has at least as many columns as assoc_array has elements. The fieldnames in table_name must match the indices in assoc_array and the corresponding datatypes must be compatible. Returns an array with the converted values on success, FALSE otherwise.

Note: If there are boolean fields in table_name don't use the constant TRUE in assoc_array . It will be converted to the string 'TRUE' which is no valid entry for boolean fields in PostgreSQL. Use one of t, true, 1, y, yes instead.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table against which to convert types.

assoc_array

Data to be converted.

options

Any number of PGSQL_CONV_IGNORE_DEFAULT, PGSQL_CONV_FORCE_NULL or PGSQL_CONV_IGNORE_NOT_NULL, combined.

Return Values

An array of converted values, or FALSE on error.

Examples

Example #1 pg_convert() example

<?php
  $dbconn = pg_connect('dbname=foo');

  $tmp = array(
      'author' => 'Joe Thackery',
      'year' => 2005,
      'title' => 'My Life, by Joe Thackery'
  );

  $vals = pg_convert($dbconn, 'authors', $tmp);
?>

See Also

  • pg_meta_data() - Get meta data for table

pg_connection_status
pg_copy_from
PostgreSQL Functions


Insert records into a table from an array

pg_convert
pg_copy_to
PostgreSQL Functions
PHP Manual

pg_copy_from

(PHP 4 >= 4.2.0, PHP 5)

pg_copy_from — Insert records into a table from an array

Description

bool pg_copy_from ( resource $connection , string $table_name , array $rows [, string $delimiter [, string $null_as ]] )

pg_copy_from() inserts records into a table from rows . It issues a COPY FROM SQL command internally to insert records.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to copy the rows .

rows

An array of data to be copied into table_name . Each value in rows becomes a row in table_name . Each value in rows should be a delimited string of the values to insert into each field. Values should be linefeed terminated.

delimiter

The token that separates values for each field in each element of rows . Default is TAB.

null_as

How SQL NULL values are represented in the rows . Default is \N ("\\N").

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_copy_from() example

<?php
   $db = pg_connect("dbname=publisher") or die("Could not connect");

   $rows = pg_copy_to($db, $table_name);

   pg_query($db, "DELETE FROM $table_name");

   pg_copy_from($db, $table_name, $rows);
?>

See Also

  • pg_copy_to() - Copy a table to an array

pg_convert
pg_copy_to
PostgreSQL Functions


Copy a table to an array

pg_copy_from
pg_dbname
PostgreSQL Functions
PHP Manual

pg_copy_to

(PHP 4 >= 4.2.0, PHP 5)

pg_copy_to — Copy a table to an array

Description

array pg_copy_to ( resource $connection , string $table_name [, string $delimiter [, string $null_as ]] )

pg_copy_to() copies a table to an array. It issues COPY TO SQL command internally to retrieve records.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to copy the data into rows .

delimiter

The token that separates values for each field in each element of rows . Default is TAB.

null_as

How SQL NULL values are represented in the rows . Default is \N ("\\N").

Return Values

An array with one element for each line of COPY data. It returns FALSE on failure.

Examples

Example #1 pg_copy_to() example

<?php
   $db = pg_connect("dbname=publisher") or die("Could not connect");

   $rows = pg_copy_to($db, $table_name);

   pg_query($db, "DELETE FROM $table_name");

   pg_copy_from($db, $table_name, $rows);
?>

See Also

  • pg_copy_from() - Insert records into a table from an array

pg_copy_from
pg_dbname
PostgreSQL Functions


Get the database name

pg_copy_to
pg_delete
PostgreSQL Functions
PHP Manual

pg_dbname

(PHP 4, PHP 5)

pg_dbname — Get the database name

Description

string pg_dbname ([ resource $connection ] )

pg_dbname() returns the name of the database that the given PostgreSQL connection resource.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the name of the database the connection is to, or FALSE on error.

Examples

Example #1 pg_dbname() example

<?php
  error_reporting(E_ALL);

  pg_connect("host=localhost port=5432 dbname=mary");
  echo pg_dbname(); // mary
?>

pg_copy_to
pg_delete
PostgreSQL Functions


Deletes records

pg_dbname
pg_end_copy
PostgreSQL Functions
PHP Manual

pg_delete

(PHP 4 >= 4.3.0, PHP 5)

pg_delete — Deletes records

Description

mixed pg_delete ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC ] )

pg_delete() deletes records from a table specified by the keys and values in assoc_array . If options is specified, pg_convert() is applied to assoc_array with the specified options.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to delete rows.

assoc_array

An array whose keys are field names in the table table_name , and whose values are the values of those fields that are to be deleted.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options .

Examples

Example #1 pg_delete() example

<?php
  $db = pg_connect('dbname=foo');
  // This is safe, since $_POST is converted automatically
  $res = pg_delete($db, 'post_log', $_POST);
  if ($res) {
      echo "POST data is deleted: $res\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

pg_dbname
pg_end_copy
PostgreSQL Functions


Sync with PostgreSQL backend

pg_delete
pg_escape_bytea
PostgreSQL Functions
PHP Manual

pg_end_copy

(PHP 4 >= 4.0.3, PHP 5)

pg_end_copy — Sync with PostgreSQL backend

Description

bool pg_end_copy ([ resource $connection ] )

pg_end_copy() syncs the PostgreSQL frontend (usually a web server process) with the PostgreSQL server after doing a copy operation performed by pg_put_line(). pg_end_copy() must be issued, otherwise the PostgreSQL server may get out of sync with the frontend and will report an error.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_end_copy() example

<?php
  $conn = pg_pconnect("dbname=foo");
  pg_query($conn, "create table bar (a int4, b char(16), d float8)");
  pg_query($conn, "copy bar from stdin");
  pg_put_line($conn, "3\thello world\t4.5\n");
  pg_put_line($conn, "4\tgoodbye world\t7.11\n");
  pg_put_line($conn, "\\.\n");
  pg_end_copy($conn);
?>

See Also

  • pg_put_line() - Send a NULL-terminated string to PostgreSQL backend

pg_delete
pg_escape_bytea
PostgreSQL Functions


Escape a string for insertion into a bytea field

pg_end_copy
pg_escape_string
PostgreSQL Functions
PHP Manual

pg_escape_bytea

(PHP 4 >= 4.2.0, PHP 5)

pg_escape_bytea — Escape a string for insertion into a bytea field

Description

string pg_escape_bytea ([ resource $connection ], string $data )

pg_escape_bytea() escapes string for bytea datatype. It returns escaped string.

Note: When you SELECT a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.
This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e. INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea); PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A string containing text or binary data to be inserted into a bytea column.

Return Values

A string containing the escaped data.

Changelog

Version | Description
5.2.0 | connection added

Examples

Example #1 pg_escape_bytea() example

<?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Read in a binary file
  $data = file_get_contents('image1.jpg');

  // Escape the binary data
  $escaped = pg_escape_bytea($data);

  // Insert it into the database
  pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', '{$escaped}')");
?>

See Also

  • pg_unescape_bytea() - Unescape binary for bytea type
  • pg_escape_string() - Escape a string for insertion into a text field

pg_end_copy
pg_escape_string
PostgreSQL Functions


Escape a string for insertion into a text field

pg_escape_bytea
pg_execute
PostgreSQL Functions
PHP Manual

pg_escape_string

(PHP 4 >= 4.2.0, PHP 5)

pg_escape_string — Escape a string for insertion into a text field

Description

string pg_escape_string ([ resource $connection ], string $data )

pg_escape_string() escapes a string for insertion into the database. It returns an escaped string in the PostgreSQL format. Use of this function is recommended instead of addslashes(). If the type of the column is bytea, pg_escape_bytea() must be used instead.

Note: This function requires PostgreSQL 7.2 or later.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A string containing text to be escaped.

Return Values

A string containing the escaped data.

Changelog

Version | Description
5.2.0 | connection added

Examples

Example #1 pg_escape_string() example

<?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Read in a text file (containing apostrophes and backslashes)
  $data = file_get_contents('letter.txt');

  // Escape the text data
  $escaped = pg_escape_string($data);

  // Insert it into the database
  pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', '{$escaped}')");
?>

See Also

  • pg_escape_bytea() - Escape a string for insertion into a bytea field

pg_escape_bytea
pg_execute
PostgreSQL Functions


Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_escape_string
pg_fetch_all_columns
PostgreSQL Functions
PHP Manual

pg_execute

(PHP 5 >= 5.1.0)

pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result.

Description

resource pg_execute ([ resource $connection ], string $stmtname , array $params )

Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_execute() is like pg_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session. pg_execute() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The parameters are identical to pg_query_params(), except that the name of a prepared statement is given instead of a query string.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Warning

Elements are converted to strings by calling this function.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 Using pg_execute()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?>

See Also

  • pg_prepare() - Submits a request to create a prepared statement with the given parameters, and waits for completion.
  • pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion.
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_escape_string
pg_fetch_all_columns
PostgreSQL Functions


Fetches all rows from a result as an array

pg_fetch_all_columns
pg_fetch_array
PostgreSQL Functions
PHP Manual

pg_fetch_all

(PHP 4 >= 4.3.0, PHP 5)

pg_fetch_all — Fetches all rows from a result as an array

Description

array pg_fetch_all ( resource $result )

pg_fetch_all() returns an array that contains all rows (records) in the result resource.

Note: This function sets NULL fields to the PHP NULL value.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

An array with all rows in the result. Each row is an array of field values indexed by field name.

FALSE is returned if there are no rows in the result, or on any other error.

Examples

Example #1 PostgreSQL fetch all

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

$result = pg_query($conn, "SELECT * FROM authors");
if (!$result) {
    echo "An error occured.\n";
    exit;
}

$arr = pg_fetch_all($result);

print_r($arr);

?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Fred
        )

    [1] => Array
        (
            [id] => 2
            [name] => Bob
        )

)

See Also

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

pg_fetch_all_columns
pg_fetch_array
PostgreSQL Functions


Fetches all rows in a particular result column as an array

pg_execute
pg_fetch_all
PostgreSQL Functions
PHP Manual

pg_fetch_all_columns

(PHP 5 >= 5.1.0)

pg_fetch_all_columns — Fetches all rows in a particular result column as an array

Description

array pg_fetch_all_columns ( resource $result [, int $column = 0 ] )

pg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the result resource.

Note: This function sets NULL fields to the PHP NULL value.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

column

Column number, zero-based, to be retrieved from the result resource. Defaults to the first column if not specified.

Return Values

An array with all values in the result column.

FALSE is returned if column is larger than the number of columns in the result, or on any other error.

Examples

Example #1 pg_fetch_all_columns() example

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);

var_dump($arr);

?>

See Also

  • pg_fetch_all() - Fetches all rows from a result as an array

pg_execute
pg_fetch_all
PostgreSQL Functions


Fetch a row as an array

pg_fetch_all
pg_fetch_assoc
PostgreSQL Functions
PHP Manual

pg_fetch_array

(PHP 4, PHP 5)

pg_fetch_array — Fetch a row as an array

Description

array pg_fetch_array ( resource $result [, int $row [, int $result_type ]] )

pg_fetch_array() returns an array that corresponds to the fetched row (record).

pg_fetch_array() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field number) to the result array, it can also store the data using associative indices (field name). It stores both indicies by default.

Note: This function sets NULL fields to the PHP NULL value.

pg_fetch_array() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

result_type

An optional parameter that controls how the returned array is indexed. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, pg_fetch_array() will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH, the default, will return both numerical and associative indices.

Return Values

An array indexed numerically (beginning with 0) or associatively (indexed by field name), or both. Each value in the array is represented as a string. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Changelog

Version | Description
4.1.0 | The row parameter became optional.

Examples

Example #1 pg_fetch_array() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

$arr = pg_fetch_array($result, 0, PGSQL_NUM);
echo $arr[0] . " <- Row 1 Author\n";
echo $arr[1] . " <- Row 1 E-mail\n";

// As of PHP 4.1.0, the row parameter is optional; NULL can be passed instead,
// to pass a result_type.  Successive calls to pg_fetch_array will return the
// next row.
$arr = pg_fetch_array($result, NULL, PGSQL_ASSOC);
echo $arr["author"] . " <- Row 2 Author\n";
echo $arr["email"] . " <- Row 2 E-mail\n";

$arr = pg_fetch_array($result);
echo $arr["author"] . " <- Row 3 Author\n";
echo $arr[1] . " <- Row 3 E-mail\n";

?>

See Also

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

pg_fetch_all
pg_fetch_assoc
PostgreSQL Functions


Fetch a row as an associative array

pg_fetch_array
pg_fetch_object
PostgreSQL Functions
PHP Manual

pg_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

pg_fetch_assoc — Fetch a row as an associative array

Description

array pg_fetch_assoc ( resource $result [, int $row ] )

pg_fetch_assoc() returns an associative array that corresponds to the fetched row (records).

pg_fetch_assoc() is equivalent to calling pg_fetch_array() with PGSQL_ASSOC as the optional third parameter. It only returns an associative array. If you need the numeric indices, use pg_fetch_row().

Note: This function sets NULL fields to the PHP NULL value.

pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

Return Values

An array indexed associatively (by field name). Each value in the array is represented as a string. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Changelog

Version | Description
4.1.0 | The parameter row became optional.

Examples

Example #1 pg_fetch_assoc() example

<?php
$conn = pg_connect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT id, author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

while ($row = pg_fetch_assoc($result)) {
  echo $row['id'];
  echo $row['author'];
  echo $row['email'];
}
?>

See Also

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

pg_fetch_array
pg_fetch_object
PostgreSQL Functions


Fetch a row as an object

pg_fetch_assoc
pg_fetch_result
PostgreSQL Functions
PHP Manual

pg_fetch_object

(PHP 4, PHP 5)

pg_fetch_object — Fetch a row as an object

Description

object pg_fetch_object ( resource $result [, int $row [, int $result_type = PGSQL_ASSOC ]] )
object pg_fetch_object ( resource $result [, int $row [, string $class_name [, array $params ]]] )

pg_fetch_object() returns an object with properties that correspond to the fetched row's field names. It can optionally instantiate an object of a specific class, and pass parameters to that class's constructor.

Note: This function sets NULL fields to the PHP NULL value.

Speed-wise, the function is identical to pg_fetch_array(), and almost as fast as pg_fetch_row() (the difference is insignificant).

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

result_type

Ignored and deprecated.

class_name

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

Return Values

An object with one attribute for each field name in the result. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Changelog

Version | Description
5.0.0 | class_name and params were added. The old form with result_type still exists for backwards compatibility.
4.3.0 | result_type default changed from PGSQL_BOTH to PGSQL_ASSOC, since the numeric index was illegal.
4.1.0 | The parameter row became optional.

Examples

Example #1 pg_fetch_object() example

<?php

$database = "store";

$db_conn = pg_connect("host=localhost port=5432 dbname=$database");
if (!$db_conn) {
  echo "Failed connecting to postgres database $database\n";
  exit;
}

$qu = pg_query($db_conn, "SELECT * FROM books ORDER BY author");

while ($data = pg_fetch_object($qu)) {
  echo $data->author . " (";
  echo $data->year . "): ";
  echo $data->title . "<br />";
}

pg_free_result($qu);
pg_close($db_conn);

?>

See Also

  • pg_query() - Execute a query
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_assoc() - Fetch a row as an associative array
  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_result() - Returns values from a result resource

pg_fetch_assoc
pg_fetch_result
PostgreSQL Functions


Returns values from a result resource

pg_fetch_object
pg_fetch_row
PostgreSQL Functions
PHP Manual

pg_fetch_result

(PHP 4 >= 4.2.0, PHP 5)

pg_fetch_result — Returns values from a result resource

Description

string pg_fetch_result ( resource $result , int $row , mixed $field )
string pg_fetch_result ( resource $result , mixed $field )

pg_fetch_result() returns the value of a particular row and field (column) in a PostgreSQL result resource.

Note: This function used to be called pg_result().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

field

A string representing the name of the field (column) to fetch, otherwise an int representing the field number to fetch. Fields are numbered from 0 upwards.

Return Values

Boolean is returned as "t" or "f". All other types, including arrays are returned as strings formatted in the same default PostgreSQL manner that you would see in the psql program. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, or on any other error.

Examples

Example #1 pg_fetch_result() example

<?php
$db = pg_connect("dbname=users user=me") || die();

$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");

$val = pg_fetch_result($res, 1, 0);

echo "First field in the second row is: ", $val, "\n";
?>

The above example will output:

First field in the second row is: 2

See Also

  • pg_query() - Execute a query
  • pg_fetch_array() - Fetch a row as an array

pg_fetch_object
pg_fetch_row
PostgreSQL Functions


Get a row as an enumerated array

pg_fetch_result
pg_field_is_null
PostgreSQL Functions
PHP Manual

pg_fetch_row

(PHP 4, PHP 5)

pg_fetch_row — Get a row as an enumerated array

Description

array pg_fetch_row ( resource $result [, int $row ] )

pg_fetch_row() fetches one row of data from the result associated with the specified result resource.

Note: This function sets NULL fields to the PHP NULL value.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

Return Values

An array, indexed from 0 upwards, with each value represented as a string. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Changelog

Version | Description
4.1.0 | The parameter row became optional.

Examples

Example #1 pg_fetch_row() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

?>

See Also

  • pg_query() - Execute a query
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

pg_fetch_result
pg_field_is_null
PostgreSQL Functions


Test if a field is SQL NULL

pg_fetch_row
pg_field_name
PostgreSQL Functions
PHP Manual

pg_field_is_null

(PHP 4 >= 4.2.0, PHP 5)

pg_field_is_null — Test if a field is SQL NULL

Description

int pg_field_is_null ( resource $result , int $row , mixed $field )
int pg_field_is_null ( resource $result , mixed $field )

pg_field_is_null() tests if a field in a PostgreSQL result resource is SQL NULL or not.

Note: This function used to be called pg_fieldisnull().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, current row is fetched.

field

Field number (starting from 0) as an integer or the field name as a string.

Return Values

Returns 1 if the field in the given row is SQL NULL, 0 if not. FALSE is returned if the row is out of range, or upon any other error.

Examples

Example #1 pg_field_is_null() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die ("Could not connect");
  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  if ($res) {
      if (pg_field_is_null($res, 0, "year") == 1) {
          echo "The value of the field year is null.\n";
      }
      if (pg_field_is_null($res, 0, "year") == 0) {
          echo "The value of the field year is not null.\n";
    }
 }
?>

pg_fetch_row
pg_field_name
PostgreSQL Functions


Returns the name of a field

pg_field_is_null
pg_field_num
PostgreSQL Functions
PHP Manual

pg_field_name

(PHP 4 >= 4.2.0, PHP 5)

pg_field_name — Returns the name of a field

Description

string pg_field_name ( resource $result , int $field_number )

pg_field_name() returns the name of the field occupying the given field_number in the given PostgreSQL result resource. Field numbering starts from 0.

Note: This function used to be called pg_fieldname().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The field name, or FALSE on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j < $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?>

The above example will output:

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

See Also

  • pg_field_num() - Returns the field number of the named field

pg_field_is_null
pg_field_num
PostgreSQL Functions


Returns the field number of the named field

pg_field_name
pg_field_prtlen
PostgreSQL Functions
PHP Manual

pg_field_num

(PHP 4 >= 4.2.0, PHP 5)

pg_field_num — Returns the field number of the named field

Description

int pg_field_num ( resource $result , string $field_name )

pg_field_num() will return the number of the field number that corresponds to the field_name in the given PostgreSQL result resource.

Note: This function used to be called pg_fieldnum().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_name

The name of the field.

Return Values

The field number (numbered from 0), or -1 on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select author, year, title from authors where author = 'Orwell'");

  echo "Column 'title' is field number: ", pg_field_num($res, 'title');
?>

The above example will output:

Column 'title' is field number: 2

See Also

  • pg_field_name() - Returns the name of a field

pg_field_name
pg_field_prtlen
PostgreSQL Functions


Returns the printed length

pg_field_num
pg_field_size
PostgreSQL Functions
PHP Manual

pg_field_prtlen

(PHP 4 >= 4.2.0, PHP 5)

pg_field_prtlen — Returns the printed length

Description

int pg_field_prtlen ( resource $result , int $row_number , mixed $field_name_or_number )
int pg_field_prtlen ( resource $result , mixed $field_name_or_number )

pg_field_prtlen() returns the actual printed length (number of characters) of a specific value in a PostgreSQL result . Row numbering starts at 0. This function will return -1 on an error.

field_name_or_number can be passed either as an integer or as a string. If it is passed as an integer, PHP recognises it as the field number, otherwise as field name.

See the example given at the pg_field_name() page.

Note: This function used to be called pg_fieldprtlen().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result. Rows are numbered from 0 upwards. If omitted, current row is fetched.

Return Values

The field printed length, or FALSE on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j < $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?>

The above example will output:

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

See Also

  • pg_field_size() - Returns the internal storage size of the named field

pg_field_num
pg_field_size
PostgreSQL Functions


Returns the internal storage size of the named field

pg_field_prtlen
pg_field_table
PostgreSQL Functions
PHP Manual

pg_field_size

(PHP 4 >= 4.2.0, PHP 5)

pg_field_size — Returns the internal storage size of the named field

Description

int pg_field_size ( resource $result , int $field_number )

pg_field_size() returns the internal storage size (in bytes) of the field number in the given PostgreSQL result .

Note: This function used to be called pg_fieldsize().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The internal field storage size (in bytes). -1 indicates a variable length field. FALSE is returned on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
  $i = pg_num_fields($res);
  for ($j = 0; $j < $i; $j++) {
      echo "column $j\n";
      $fieldname = pg_field_name($res, $j);
      echo "fieldname: $fieldname\n";
      echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
      echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
      echo "field type: " . pg_field_type($res, $j) . " \n\n";
  }
?>

The above example will output:

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

See Also

  • pg_field_prtlen() - Returns the printed length
  • pg_field_type() - Returns the type name for the corresponding field number

pg_field_prtlen
pg_field_table
PostgreSQL Functions


Returns the name or oid of the tables field

pg_field_size
pg_field_type_oid
PostgreSQL Functions
PHP Manual

pg_field_table

(PHP 5 >= 5.2.0)

pg_field_table — Returns the name or oid of the tables field

Description

mixed pg_field_table ( resource $result , int $field_number [, bool $oid_only = false ] )

pg_field_table() returns the name of the table that field belongs to, or the table's oid if oid_only is TRUE.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

oid_only

By default the tables name that field belongs to is returned but if oid_only is set to TRUE, then the oid will instead be returned.

Return Values

On success either the fields table name or oid. Or, FALSE on failure.

Examples

Example #1 Getting table information about a field

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

$res = pg_query($dbconn, "SELECT bar FROM foo");

echo pg_field_table($res, 0);
echo pg_field_table($res, 0, true);

$res = pg_query($dbconn, "SELECT version()");
var_dump(pg_field_table($res, 0));
?>

The above example will output something similar to:

foo
14379580

bool(false)

Notes

Note: Returning the oid is much faster than returning the table name because fetching the table name requires a query to the database system table.

See Also

  • pg_field_name() - Returns the name of a field
  • pg_field_type() - Returns the type name for the corresponding field number

pg_field_size
pg_field_type_oid
PostgreSQL Functions


Returns the type name for the corresponding field number

pg_field_type_oid
pg_free_result
PostgreSQL Functions
PHP Manual

pg_field_type

(PHP 4 >= 4.2.0, PHP 5)

pg_field_type — Returns the type name for the corresponding field number

Description

string pg_field_type ( resource $result , int $field_number )

pg_field_type() returns a string containing the base type name of the given field_number in the given PostgreSQL result resource.

Note: If the field uses a PostgreSQL domain (rather than a basic type), it is the name of the domain's underlying type that is returned, rather than the name of the domain itself.

Note: This function used to be called pg_fieldtype().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

A string containing the base name of the field's type, or FALSE on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Assume 'title' is a varchar type
  $res = pg_query($dbconn, "select title from authors where author = 'Orwell'");

  echo "Title field type: ", pg_field_type($res, 0);
?>

The above example will output:

Title field type: varchar

See Also

  • pg_field_prtlen() - Returns the printed length
  • pg_field_name() - Returns the name of a field
  • pg_field_type_oid() - Returns the type ID (OID) for the corresponding field number

pg_field_type_oid
pg_free_result
PostgreSQL Functions


Returns the type ID (OID) for the corresponding field number

pg_field_table
pg_field_type
PostgreSQL Functions
PHP Manual

pg_field_type_oid

(PHP 5 >= 5.1.0)

pg_field_type_oid — Returns the type ID (OID) for the corresponding field number

Description

int pg_field_type_oid ( resource $result , int $field_number )

pg_field_type_oid() returns an integer containing the OID of the base type of the given field_number in the given PostgreSQL result resource.

You can get more information about the field type by querying PostgreSQL's pg_type system table using the OID obtained with this function. The PostgreSQL format_type() function will convert a type OID into an SQL standard type name.

Note: If the field uses a PostgreSQL domain (rather than a basic type), it is the OID of the domain's underlying type that is returned, rather than the OID of the domain itself.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The OID of the field's base type. FALSE is returned on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Assume 'title' is a varchar type
  $res = pg_query($dbconn, "select title from authors where author = 'Orwell'");

  echo "Title field type OID: ", pg_field_type_oid($res, 0);
?>

The above example will output:

Title field type OID: 1043

See Also

  • pg_field_type() - Returns the type name for the corresponding field number
  • pg_field_prtlen() - Returns the printed length
  • pg_field_name() - Returns the name of a field

pg_field_table
pg_field_type
PostgreSQL Functions


Free result memory

pg_field_type
pg_get_notify
PostgreSQL Functions
PHP Manual

pg_free_result

(PHP 4 >= 4.2.0, PHP 5)

pg_free_result — Free result memory

Description

bool pg_free_result ( resource $result )

pg_free_result() frees the memory and data associated with the specified PostgreSQL query result resource.

This function need only be called if memory consumption during script execution is a problem. Otherwise, all result memory will be automatically freed when the script ends.

Note: This function used to be called pg_freeresult().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_free_result() example

<?php
$db = pg_connect("dbname=users user=me") || die();

$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");

$val = pg_fetch_result($res, 1, 0);

echo "First field in the second row is: ", $val, "\n";

pg_free_result($res);
?>

The above example will output:

First field in the second row is: 2

See Also

  • pg_query() - Execute a query
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_field_type
pg_get_notify
PostgreSQL Functions


Gets SQL NOTIFY message

pg_free_result
pg_get_pid
PostgreSQL Functions
PHP Manual

pg_get_notify

(PHP 4 >= 4.3.0, PHP 5)

pg_get_notify — Gets SQL NOTIFY message

Description

array pg_get_notify ( resource $connection [, int $result_type ] )

pg_get_notify() gets notifications generated by a NOTIFY SQL command. To receive notifications, the LISTEN SQL command must be issued.

Parameters

connection

PostgreSQL database connection resource.

result_type

An optional parameter that controls how the returned array is indexed. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, pg_get_notify() will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH, the default, will return both numerical and associative indices.

Return Values

An array containing the NOTIFY message name and backend PID. Otherwise if no NOTIFY is waiting, then FALSE is returned.

Examples

Example #1 PostgreSQL NOTIFY message

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

// Listen 'author_updated' message from other processes
pg_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify) {
  echo "No messages\n";
} else {
  print_r($notify);
}
?>

See Also

  • pg_get_pid() - Gets the backend's process ID

pg_free_result
pg_get_pid
PostgreSQL Functions


Gets the backend's process ID

pg_get_notify
pg_get_result
PostgreSQL Functions
PHP Manual

pg_get_pid

(PHP 4 >= 4.3.0, PHP 5)

pg_get_pid — Gets the backend's process ID

Description

int pg_get_pid ( resource $connection )

pg_get_pid() gets the backend's (database server process) PID. The PID is useful to determine whether or not a NOTIFY message received via pg_get_notify() is sent from another process or not.

Parameters

connection

PostgreSQL database connection resource.

Return Values

The backend database process ID.

Examples

Example #1 PostgreSQL backend PID

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?>

See Also

  • pg_get_notify() - Gets SQL NOTIFY message

pg_get_notify
pg_get_result
PostgreSQL Functions


Get asynchronous query result

pg_get_pid
pg_host
PostgreSQL Functions
PHP Manual

pg_get_result

(PHP 4 >= 4.2.0, PHP 5)

pg_get_result — Get asynchronous query result

Description

resource pg_get_result ([ resource $connection ] )

pg_get_result() gets the result resource from an asynchronous query executed by pg_send_query(), pg_send_query_params() or pg_send_execute().

pg_send_query() and the other asynchronous query functions can send multiple queries to a PostgreSQL server and pg_get_result() is used to get each query's results, one by one.

Parameters

connection

PostgreSQL database connection resource.

Return Values

The result resource, or FALSE if no more results are available.

Examples

Example #1 pg_get_result() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
  }

  $res1 = pg_get_result($dbconn);
  echo "First call to pg_get_result(): $res1\n";
  $rows1 = pg_num_rows($res1);
  echo "$res1 has $rows1 records\n\n";

  $res2 = pg_get_result($dbconn);
  echo "Second call to pg_get_result(): $res2\n";
  $rows2 = pg_num_rows($res2);
  echo "$res2 has $rows2 records\n";
?>

The above example will output:

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records

See Also

  • pg_send_query() - Sends asynchronous query

pg_get_pid
pg_host
PostgreSQL Functions


Returns the host name associated with the connection

pg_get_result
pg_insert
PostgreSQL Functions
PHP Manual

pg_host

(PHP 4, PHP 5)

pg_host — Returns the host name associated with the connection

Description

string pg_host ([ resource $connection ] )

pg_host() returns the host name of the given PostgreSQL connection resource is connected to.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the name of the host the connection is to, or FALSE on error.

Examples

Example #1 pg_host() example

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection

pg_get_result
pg_insert
PostgreSQL Functions


Insert array into table

pg_host
pg_last_error
PostgreSQL Functions
PHP Manual

pg_insert

(PHP 4 >= 4.3.0, PHP 5)

pg_insert — Insert array into table

Description

mixed pg_insert ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC ] )

pg_insert() inserts the values of assoc_array into the table specified by table_name . If options is specified, pg_convert() is applied to assoc_array with the specified options.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to insert rows. The table table_name must at least have as many columns as assoc_array has elements.

assoc_array

An array whose keys are field names in the table table_name , and whose values are the values of those fields that are to be inserted.

options

Any number of PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options .

Examples

Example #1 pg_insert() example

<?php
  $dbconn = pg_connect('dbname=foo');
  // This is safe, since $_POST is converted automatically
  $res = pg_insert($dbconn, 'post_log', $_POST);
  if ($res) {
      echo "POST data is successfully logged\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

pg_host
pg_last_error
PostgreSQL Functions


Get the last error message string of a connection

pg_insert
pg_last_notice
PostgreSQL Functions
PHP Manual

pg_last_error

(PHP 4 >= 4.2.0, PHP 5)

pg_last_error — Get the last error message string of a connection

Description

string pg_last_error ([ resource $connection ] )

pg_last_error() returns the last error message for a given connection .

Error messages may be overwritten by internal PostgreSQL (libpq) function calls. It may not return an appropriate error message if multiple errors occur inside a PostgreSQL module function.

Use pg_result_error(), pg_result_error_field(),
pg_result_status() and
pg_connection_status() for better error handling.

Note: This function used to be called pg_errormessage().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the last error message on the given connection , or FALSE on error.

Examples

Example #1 pg_last_error() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Query that fails
  $res = pg_query($dbconn, "select * from doesnotexist");

  echo pg_last_error($dbconn);
?>

See Also

  • pg_result_error() - Get error message associated with result
  • pg_result_error_field() - Returns an individual field of an error report.

pg_insert
pg_last_notice
PostgreSQL Functions


Returns the last notice message from PostgreSQL server

pg_last_error
pg_last_oid
PostgreSQL Functions
PHP Manual

pg_last_notice

(PHP 4 >= 4.0.6, PHP 5)

pg_last_notice — Returns the last notice message from PostgreSQL server

Description

string pg_last_notice ( resource $connection )

pg_last_notice() returns the last notice message from the PostgreSQL server on the specified connection . The PostgreSQL server sends notice messages in several cases, for instance when creating a SERIAL column in a table.

With pg_last_notice(), you can avoid issuing useless queries by checking whether or not the notice is related to your transaction.

Notice message tracking can be set to optional by setting 1 for pgsql.ignore_notice in php.ini.

Notice message logging can be set to optional by setting 0 for pgsql.log_notice in php.ini. Unless pgsql.ignore_notice is set to 0, notice message cannot be logged.

Parameters

connection

PostgreSQL database connection resource.

Return Values

A string containing the last notice on the given connection , or FALSE on error.

Changelog

Version | Description
4.3.0 | This function is now fully implemented. Earlier versions ignores database connection parameter.
4.3.0 | The pgsql.ignore_notice and pgsql.log_notice php.ini directives were added.
4.0.6 | PHP 4.0.6 has problem with notice message handling. Use of the PostgreSQL module with PHP 4.0.6 is not recommended even if you are not using pg_last_notice().

Examples

Example #1 pg_last_error() example

<?php
  $pgsql_conn = pg_connect("dbname=mark host=localhost");

  $res = pg_query("CREATE TABLE test (id SERIAL)");

  $notice = pg_last_notice($pgsql_conn);

  echo $notice;
?>

The above example will output:

CREATE TABLE will create implicit sequence "test_id_seq" for "serial" column "test.id"

See Also

  • pg_query() - Execute a query
  • pg_last_error() - Get the last error message string of a connection

pg_last_error
pg_last_oid
PostgreSQL Functions


Returns the last row's OID

pg_last_notice
pg_lo_close
PostgreSQL Functions
PHP Manual

pg_last_oid

(PHP 4 >= 4.2.0, PHP 5)

pg_last_oid — Returns the last row's OID

Description

string pg_last_oid ( resource $result )

pg_last_oid() is used to retrieve the OID assigned to an inserted row.

OID field became an optional field from PostgreSQL 7.2 and will not be present by default in PostgreSQL 8.1. When the OID field is not present in a table, the programmer must use pg_result_status() to check for successful insertion.

To get the value of a SERIAL field in an inserted row, it is necessary to use the PostgreSQL CURRVAL function, naming the sequence whose last value is required. If the name of the sequence is unknown, the pg_get_serial_sequence PostgreSQL 8.0 function is necessary.

PostgreSQL 8.1 has a function LASTVAL that returns the value of the most recently used sequence in the session. This avoids the need for naming the sequence, table or column altogether.

Note: This function used to be called pg_getlastoid().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

A string containing the OID assigned to the most recently inserted row in the specified connection , or FALSE on error or no available OID.

Examples

Example #1 pg_last_oid() example

<?php
  $pgsql_conn = pg_connect("dbname=mark host=localhost");

  $res1 = pg_query("CREATE TABLE test (a INTEGER) WITH OIDS");

  $res2 = pg_query("INSERT INTO test VALUES (1)");

  $oid = pg_last_oid($res2);
?>

See Also

  • pg_query() - Execute a query
  • pg_result_status() - Get status of query result

pg_last_notice
pg_lo_close
PostgreSQL Functions


Close a large object

pg_last_oid
pg_lo_create
PostgreSQL Functions
PHP Manual

pg_lo_close

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_close — Close a large object

Description

bool pg_lo_close ( resource $large_object )

pg_lo_close() closes a large object. large_object is a resource for the large object from pg_lo_open().

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_loclose().

Parameters

result

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_lo_close() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   echo "$oid\n";
   $handle = pg_lo_open($database, $oid, "w");
   echo "$handle\n";
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_query($database, "commit");
?>

See Also

  • pg_lo_open() - Open a large object
  • pg_lo_create() - Create a large object
  • pg_lo_import() - Import a large object from file

pg_last_oid
pg_lo_create
PostgreSQL Functions


Create a large object

pg_lo_close
pg_lo_export
PostgreSQL Functions
PHP Manual

pg_lo_create

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_create — Create a large object

Description

int pg_lo_create ([ resource $connection [, mixed $object_id ]] )
int pg_lo_create ( mixed $object_id )

pg_lo_create() creates a large object and returns the OID of the large object. PostgreSQL access modes INV_READ, INV_WRITE, and INV_ARCHIVE are not supported, the object is created always with both read and write access. INV_ARCHIVE has been removed from PostgreSQL itself (version 6.3 and above).

To use the large object interface, it is necessary to enclose it within a transaction block.

Instead of using the large object interface (which has no access controls and is cumbersome to use), try PostgreSQL's bytea column type and pg_escape_bytea().

Note: This function used to be called pg_locreate().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

object_id

If an object_id is given the function will try to create a large object with this id, else a free object id is assigned by the server. The parameter was added in PHP 5.3 and relies on functionality that first appeared in PostgreSQL 8.1.

Return Values

A large object OID or FALSE on error.

Changelog

Version | Description
5.3.0 | The optional object_id was added.

Examples

Example #1 pg_lo_create() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   echo "$oid\n";
   $handle = pg_lo_open($database, $oid, "w");
   echo "$handle\n";
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_query($database, "commit");
?>

pg_lo_close
pg_lo_export
PostgreSQL Functions


Export a large object to file

pg_lo_create
pg_lo_import
PostgreSQL Functions
PHP Manual

pg_lo_export

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_export — Export a large object to file

Description

bool pg_lo_export ([ resource $connection ], int $oid , string $pathname )

pg_lo_export() takes a large object in a PostgreSQL database and saves its contents to a file on the local filesystem.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_loexport().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

oid

The OID of the large object in the database.

pathname

The full path and file name of the file in which to write the large object on the client filesystem.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_lo_export() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   $handle = pg_lo_open($database, $oid, "w");
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_lo_export($database, $oid, '/tmp/lob.dat');
   pg_query($database, "commit");
?>

See Also

  • pg_lo_import() - Import a large object from file

pg_lo_create
pg_lo_import
PostgreSQL Functions


Import a large object from file

pg_lo_export
pg_lo_open
PostgreSQL Functions
PHP Manual

pg_lo_import

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_import — Import a large object from file

Description

int pg_lo_import ([ resource $connection ], string $pathname , mixed $object_id )

pg_lo_import() creates a new large object in the database using a file on the filesystem as its data source.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: This function used to be called pg_loimport().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

pathname

The full path and file name of the file on the client filesystem from which to read the large object data.

object_id

If an object_id is given the function will try to create a large object with this id, else a free object id is assigned by the server. The parameter was added in PHP 5.3 and relies on functionality that first appeared in PostgreSQL 8.1.

Return Values

The OID of the newly created large object, or FALSE on failure.

Changelog

Version | Description
5.3.0 | The optional object_id was added.
4.2.0 | The syntax of this function changed. It used to be: int pg_lo_import ( string $pathname [, resource $connection ] )

Examples

Example #1 pg_lo_import() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_import($database, '/tmp/lob.dat');
   pg_query($database, "commit");
?>

See Also

  • pg_lo_export() - Export a large object to file
  • pg_lo_open() - Open a large object

pg_lo_export
pg_lo_open
PostgreSQL Functions


Open a large object

pg_lo_import
pg_lo_read_all
PostgreSQL Functions
PHP Manual

pg_lo_open

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_open — Open a large object

Description

resource pg_lo_open ( resource $connection , int $oid , string $mode )

pg_lo_open() opens a large object in the database and returns large object resource so that it can be manipulated.

Warning

Do not close the database connection before closing the large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_loopen().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

oid

The OID of the large object in the database.

mode

Can be either "r" for read-only, "w" for write only or "rw" for read and write.

Return Values

A large object resource or FALSE on error.

Examples

Example #1 pg_lo_open() example

<?php
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $oid = pg_lo_create($database);
   echo "$oid\n";
   $handle = pg_lo_open($database, $oid, "w");
   echo "$handle\n";
   pg_lo_write($handle, "large object data");
   pg_lo_close($handle);
   pg_query($database, "commit");
?>

See Also

  • pg_lo_close() - Close a large object
  • pg_lo_create() - Create a large object

pg_lo_import
pg_lo_read_all
PostgreSQL Functions


Read a large object

pg_lo_read_all
pg_lo_seek
PostgreSQL Functions
PHP Manual

pg_lo_read

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_read — Read a large object

Description

string pg_lo_read ( resource $large_object [, int $len = 8192 ] )

pg_lo_read() reads at most len bytes from a large object and returns it as a string.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_loread().

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

len

An optional maximum number of bytes to return.

Return Values

A string containing len bytes from the large object, or FALSE on error.

Examples

Example #1 pg_lo_read() example

<?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   $data = pg_lo_read($handle, 50000);
   pg_query($database, "commit");
   echo $data;
?>

See Also

  • pg_lo_read_all() - Reads an entire large object and send straight to browser

pg_lo_read_all
pg_lo_seek
PostgreSQL Functions


Reads an entire large object and send straight to browser

pg_lo_open
pg_lo_read
PostgreSQL Functions
PHP Manual

pg_lo_read_all

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_read_all — Reads an entire large object and send straight to browser

Description

int pg_lo_read_all ( resource $large_object )

pg_lo_read_all() reads a large object and passes it straight through to the browser after sending all pending headers. Mainly intended for sending binary data like images or sound.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_loreadall().

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

Number of bytes read or FALSE on error.

Examples

Example #1 pg_lo_read_all() example

<?php
   header('Content-type: image/jpeg');
   $image_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $image_oid, "r");
   pg_lo_read_all($handle);
   pg_query($database, "commit");
?>

See Also

  • pg_lo_read() - Read a large object

pg_lo_open
pg_lo_read
PostgreSQL Functions


Seeks position within a large object

pg_lo_read
pg_lo_tell
PostgreSQL Functions
PHP Manual

pg_lo_seek

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_seek — Seeks position within a large object

Description

bool pg_lo_seek ( resource $large_object , int $offset [, int $whence = PGSQL_SEEK_CUR ] )

pg_lo_seek() seeks a position within a large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

offset

The number of bytes to seek.

whence

One of the constants PGSQL_SEEK_SET (seek from object start), PGSQL_SEEK_CUR (seek from current position) or PGSQL_SEEK_END (seek from object end) .

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_lo_seek() example

<?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   // Skip first 50000 bytes
   pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
   // Read the next 10000 bytes
   $data = pg_lo_read($handle, 10000);
   pg_query($database, "commit");
   echo $data;
?>

See Also

  • pg_lo_tell() - Returns current seek position a of large object

pg_lo_read
pg_lo_tell
PostgreSQL Functions


Returns current seek position a of large object

pg_lo_seek
pg_lo_unlink
PostgreSQL Functions
PHP Manual

pg_lo_tell

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_tell — Returns current seek position a of large object

Description

int pg_lo_tell ( resource $large_object )

pg_lo_tell() returns the current position (offset from the beginning) of a large object.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

The current seek offset (in number of bytes) from the beginning of the large object. If there is an error, the return value is negative.

Examples

Example #1 pg_lo_tell() example

<?php
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "r");
   // Skip first 50000 bytes
   pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
   // See how far we've skipped
   $offset = pg_lo_tell($handle);
   echo "Seek position is: $offset";
   pg_query($database, "commit");
?>

The above example will output:

Seek position is: 50000

See Also

  • pg_lo_seek() - Seeks position within a large object

pg_lo_seek
pg_lo_unlink
PostgreSQL Functions


Delete a large object

pg_lo_tell
pg_lo_write
PostgreSQL Functions
PHP Manual

pg_lo_unlink

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_unlink — Delete a large object

Description

bool pg_lo_unlink ( resource $connection , int $oid )

pg_lo_unlink() deletes a large object with the oid . Returns TRUE on success or FALSE on failure.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_lounlink().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

oid

The OID of the large object in the database.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_lo_unlink() example

<?php
   // OID of the large object to delete
   $doc_oid = 189762345;
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   pg_lo_unlink($database, $doc_oid);
   pg_query($database, "commit");
?>

See Also

  • pg_lo_create() - Create a large object
  • pg_lo_import() - Import a large object from file

pg_lo_tell
pg_lo_write
PostgreSQL Functions


Write to a large object

pg_lo_unlink
pg_meta_data
PostgreSQL Functions
PHP Manual

pg_lo_write

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_write — Write to a large object

Description

int pg_lo_write ( resource $large_object , string $data [, int $len ] )

pg_lo_write() writes data into a large object at the current seek position.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: This function used to be called pg_lowrite().

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

data

The data to be written to the large object. If len is specified and is less than the length of data , only len bytes will be written.

len

An optional maximum number of bytes to write. Must be greater than zero and no greater than the length of data . Defaults to the length of data .

Return Values

The number of bytes written to the large object, or FALSE on error.

Examples

Example #1 pg_lo_write() example

<?php
   $doc_oid = 189762345;
   $data = "This will overwrite the start of the large object.";
   $database = pg_connect("dbname=jacarta");
   pg_query($database, "begin");
   $handle = pg_lo_open($database, $doc_oid, "w");
   $data = pg_lo_write($handle, $data);
   pg_query($database, "commit");
?>

See Also

  • pg_lo_create() - Create a large object
  • pg_lo_open() - Open a large object

pg_lo_unlink
pg_meta_data
PostgreSQL Functions


Get meta data for table

pg_lo_write
pg_num_fields
PostgreSQL Functions
PHP Manual

pg_meta_data

(PHP 4 >= 4.3.0, PHP 5)

pg_meta_data — Get meta data for table

Description

array pg_meta_data ( resource $connection , string $table_name )

pg_meta_data() returns table definition for table_name as an array.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

connection

PostgreSQL database connection resource.

table_name

The name of the table.

Return Values

An array of the table definition, or FALSE on error.

Examples

Example #1 Getting table metadata

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  $meta = pg_meta_data($dbconn, 'authors');
  if (is_array($meta)) {
      echo '<pre>';
      var_dump($meta);
      echo '</pre>';
  }
?>

The above example will output:

array(3) {
["author"]=>
array(5) {
  ["num"]=>
  int(1)
  ["type"]=>
  string(7) "varchar"
  ["len"]=>
  int(-1)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
["year"]=>
array(5) {
  ["num"]=>
  int(2)
  ["type"]=>
  string(4) "int2"
  ["len"]=>
  int(2)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
["title"]=>
array(5) {
  ["num"]=>
  int(3)
  ["type"]=>
  string(7) "varchar"
  ["len"]=>
  int(-1)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
}

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

pg_lo_write
pg_num_fields
PostgreSQL Functions


Returns the number of fields in a result

pg_meta_data
pg_num_rows
PostgreSQL Functions
PHP Manual

pg_num_fields

(PHP 4 >= 4.2.0, PHP 5)

pg_num_fields — Returns the number of fields in a result

Description

int pg_num_fields ( resource $result )

pg_num_fields() returns the number of fields (columns) in a PostgreSQL result resource.

Note: This function used to be called pg_numfields().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

The number of fields (columns) in the result. On error, -1 is returned.

Examples

Example #1 pg_num_fields() example

<?php
$result = pg_query($conn, "SELECT 1, 2");

$num = pg_num_fields($result);

echo $num . " field(s) returned.\n";
?>

The above example will output:

2 field(s) returned.

See Also

  • pg_num_rows() - Returns the number of rows in a result
  • pg_affected_rows() - Returns number of affected records (tuples)

pg_meta_data
pg_num_rows
PostgreSQL Functions


Returns the number of rows in a result

pg_num_fields
pg_options
PostgreSQL Functions
PHP Manual

pg_num_rows

(PHP 4 >= 4.2.0, PHP 5)

pg_num_rows — Returns the number of rows in a result

Description

int pg_num_rows ( resource $result )

pg_num_rows() will return the number of rows in a PostgreSQL result resource.

Note: This function used to be called pg_numrows().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

The number of rows in the result. On error, -1 is returned.

Examples

Example #1 pg_num_rows() example

<?php
$result = pg_query($conn, "SELECT 1");

$rows = pg_num_rows($result);

echo $rows . " row(s) returned.\n";
?>

The above example will output:

1 row(s) returned.

See Also

  • pg_num_fields() - Returns the number of fields in a result
  • pg_affected_rows() - Returns number of affected records (tuples)

pg_num_fields
pg_options
PostgreSQL Functions


Get the options associated with the connection

pg_num_rows
pg_parameter_status
PostgreSQL Functions
PHP Manual

pg_options

(PHP 4, PHP 5)

pg_options — Get the options associated with the connection

Description

string pg_options ([ resource $connection ] )

pg_options() will return a string containing the options specified on the given PostgreSQL connection resource.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the connection options, or FALSE on error.

Examples

Example #1 pg_options() example

<?php
   $pgsql_conn = pg_connect("dbname=mark host=localhost");
   echo pg_options($pgsql_conn);
?>

See Also

  • pg_connect() - Open a PostgreSQL connection

pg_num_rows
pg_parameter_status
PostgreSQL Functions


Looks up a current parameter setting of the server.

pg_options
pg_pconnect
PostgreSQL Functions
PHP Manual

pg_parameter_status

(PHP 5)

pg_parameter_status — Looks up a current parameter setting of the server.

Description

string pg_parameter_status ([ resource $connection ], string $param_name )

Looks up a current parameter setting of the server.

Certain parameter values are reported by the server automatically at connection startup or whenever their values change. pg_parameter_status() can be used to interrogate these settings. It returns the current value of a parameter if known, or FALSE if the parameter is not known.

Parameters reported as of PostgreSQL 8.0 include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes. (server_encoding, TimeZone, and integer_datetimes were not reported by releases before 8.0.) Note that server_version, server_encoding and integer_datetimes cannot change after PostgreSQL startup.

PostgreSQL 7.3 or lower servers do not report parameter settings, pg_parameter_status() includes logic to obtain values for server_version and client_encoding anyway. Applications are encouraged to use pg_parameter_status() rather than ad hoc code to determine these values.

Caution

On a pre-7.4 PostgreSQL server, changing client_encoding via SET after connection startup will not be reflected by pg_parameter_status().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

param_name

Possible param_name values include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes.

Return Values

A string containing the value of the parameter, FALSE on failure or invalid param_name .

Examples

Example #1 pg_parameter_status() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  echo "Server encoding: ", pg_parameter_status($dbconn, "server_encoding");
?>

The above example will output:

Server encoding: SQL_ASCII

pg_options
pg_pconnect
PostgreSQL Functions


Open a persistent PostgreSQL connection

pg_parameter_status
pg_ping
PostgreSQL Functions
PHP Manual

pg_pconnect

(PHP 4, PHP 5)

pg_pconnect — Open a persistent PostgreSQL connection

Description

resource pg_pconnect ( string $connection_string [, int $connect_type ] )

pg_pconnect() opens a connection to a PostgreSQL database. It returns a connection resource that is needed by other PostgreSQL functions.

If a second call is made to pg_pconnect() with the same connection_string as an existing connection, the existing connection will be returned unless you pass PGSQL_CONNECT_FORCE_NEW as connect_type .

To enable persistent connection, the pgsql.allow_persistent php.ini directive must be set to "On" (which is the default). The maximum number of persistent connection can be defined with the pgsql.max_persistent php.ini directive (defaults to -1 for no limit). The total number of connections can be set with the pgsql.max_links php.ini directive.

pg_close() will not close persistent links generated by pg_pconnect().

Parameters

connection_string

The connection_string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e., \' and \\.

The currently recognized parameter keywords are: host , hostaddr , port , dbname , user , password , connect_timeout , options , tty (ignored), sslmode , requiressl (deprecated in favor of sslmode ), and service . Which of these arguments exist depends on your PostgreSQL version.

connect_type

If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection is created, even if the connection_string is identical to an existing connection.

Return Values

PostgreSQL connection resource on success, FALSE on failure.

Examples

Example #1 Using pg_pconnect()

<?php
$dbconn = pg_pconnect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_pconnect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_pconnect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password

$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_pconnect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • Persistent Database Connections

pg_parameter_status
pg_ping
PostgreSQL Functions


Ping database connection

pg_pconnect
pg_port
PostgreSQL Functions
PHP Manual

pg_ping

(PHP 4 >= 4.3.0, PHP 5)

pg_ping — Ping database connection

Description

bool pg_ping ([ resource $connection ] )

pg_ping() pings a database connection and tries to reconnect it if it is broken.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_ping() example

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

if (!pg_ping($conn))
  die("Connection is broken\n");
?>

See Also

  • pg_connection_status() - Get connection status
  • pg_connection_reset() - Reset connection (reconnect)

pg_pconnect
pg_port
PostgreSQL Functions


Return the port number associated with the connection

pg_ping
pg_prepare
PostgreSQL Functions
PHP Manual

pg_port

(PHP 4, PHP 5)

pg_port — Return the port number associated with the connection

Description

int pg_port ([ resource $connection ] )

pg_port() returns the port number that the given PostgreSQL connection resource is connected to.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

An int containing the port number of the database server the connection is to, or FALSE on error.

Examples

Example #1 pg_port() example

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Successfully connected to port: " . pg_port($pgsql_conn) . "<br/>\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

pg_ping
pg_prepare
PostgreSQL Functions


Submits a request to create a prepared statement with the given parameters, and waits for completion.

pg_port
pg_put_line
PostgreSQL Functions
PHP Manual

pg_prepare

(PHP 5 >= 5.1.0)

pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.

Description

resource pg_prepare ([ resource $connection ], string $stmtname , string $query )

pg_prepare() creates a prepared statement for later execution with pg_execute() or pg_send_execute(). This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. pg_prepare() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The function creates a prepared statement named stmtname from the query string, which must contain a single SQL command. stmtname may be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as $1, $2, etc.

Prepared statements for use with pg_prepare() can also be created by executing SQL PREPARE statements. (But pg_prepare() is more flexible since it does not require parameter types to be pre-specified.) Also, although there is no PHP function for deleting a prepared statement, the SQL DEALLOCATE statement can be used for that purpose.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 Using pg_prepare()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?>

See Also

  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

pg_port
pg_put_line
PostgreSQL Functions


Send a NULL-terminated string to PostgreSQL backend

pg_prepare
pg_query_params
PostgreSQL Functions
PHP Manual

pg_put_line

(PHP 4 >= 4.0.3, PHP 5)

pg_put_line — Send a NULL-terminated string to PostgreSQL backend

Description

bool pg_put_line ([ resource $connection ], string $data )

pg_put_line() sends a NULL-terminated string to the PostgreSQL backend server. This is needed in conjunction with PostgreSQL's COPY FROM command.

COPY is a high-speed data loading interface supported by PostgreSQL. Data is passed in without being parsed, and in a single transaction.

An alternative to using raw pg_put_line() commands is to use pg_copy_from(). This is a far simpler interface.

Note: The application must explicitly send the two characters "\." on the last line to indicate to the backend that it has finished sending its data, before issuing pg_end_copy().

Warning

Use of the pg_put_line() causes most large object operations, including pg_lo_read() and pg_lo_tell(), to subsequently fail. You can use pg_copy_from() and pg_copy_to() instead.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A line of text to be sent directly to the PostgreSQL backend. A NULL terminator is added automatically.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_put_line() example

<?php
  $conn = pg_pconnect("dbname=foo");
  pg_query($conn, "create table bar (a int4, b char(16), d float8)");
  pg_query($conn, "copy bar from stdin");
  pg_put_line($conn, "3\thello world\t4.5\n");
  pg_put_line($conn, "4\tgoodbye world\t7.11\n");
  pg_put_line($conn, "\\.\n");
  pg_end_copy($conn);
?>

See Also

  • pg_end_copy() - Sync with PostgreSQL backend

pg_prepare
pg_query_params
PostgreSQL Functions


Execute a query

pg_query_params
pg_result_error_field
PostgreSQL Functions
PHP Manual

pg_query

(PHP 4 >= 4.2.0, PHP 5)

pg_query — Execute a query

Description

resource pg_query ([ resource $connection ], string $query )

pg_query() executes the query on the specified database connection .

If an error occurs, and FALSE is returned, details of the error can be retrieved using the pg_last_error() function if the connection is valid.

Note: Although connection can be omitted, it is not recommended, since it can be the cause of hard to find bugs in scripts.

Note: This function used to be called pg_exec(). pg_exec() is still available for compatibility reasons, but users are encouraged to use the newer name.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

query

The SQL statement or statements to be executed. When multiple statements are passed to the function, they are automatically executed as one transaction, unless there are explicit BEGIN/COMMIT commands included in the query string. However, using multiple transactions in one function call is not recommended.

Data inside the query should be properly escaped.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 pg_query() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

?>

Example #2 Using pg_query() with multiple statements

<?php

$conn = pg_pconnect("dbname=publisher");

// these statements will be executed as one transaction

$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
$query .= "UPDATE authors SET author=NULL WHERE id=3;";

pg_query($conn, $query);

?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_num_rows() - Returns the number of rows in a result
  • pg_affected_rows() - Returns number of affected records (tuples)

pg_query_params
pg_result_error_field
PostgreSQL Functions


Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_put_line
pg_query
PostgreSQL Functions
PHP Manual

pg_query_params

(PHP 5 >= 5.1.0)

pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

Description

resource pg_query_params ([ resource $connection ], string $query , array $params )

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_query_params() is like pg_query(), but offers additional functionality: parameter values can be specified separately from the command string proper. pg_query_params() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

If parameters are used, they are referred to in the query string as $1, $2, etc. params specifies the actual values of the parameters. A NULL value in this array means the corresponding parameter is SQL NULL.

The primary advantage of pg_query_params() over pg_query() is that parameter values may be separated from the query string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike pg_query(), pg_query_params() allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.)

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 Using pg_query_params()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Find all shops named Joe's Widgets.  Note that it is not necessary to
// escape "Joe's Widgets"
$result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));

// Compare against just using pg_query
$str = pg_escape_string("Joe's Widgets");
$result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'");

?>

See Also

  • pg_query() - Execute a query

pg_put_line
pg_query
PostgreSQL Functions


Get error message associated with result

pg_result_error_field
pg_result_seek
PostgreSQL Functions
PHP Manual

pg_result_error

(PHP 4 >= 4.2.0, PHP 5)

pg_result_error — Get error message associated with result

Description

string pg_result_error ( resource $result )

pg_result_error() returns any error message associated with the result resource. Therefore, the user has a better chance of getting the correct error message than with pg_last_error().

The function pg_result_error_field() can give much greater detail on result errors than pg_result_error().

Because pg_query() returns FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

Returns a string if there is an error associated with the result parameter, FALSE otherwise.

Examples

Example #1 pg_result_error() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }

  $res1 = pg_get_result($dbconn);
  echo pg_result_error($res1);
?>

See Also

  • pg_result_error_field() - Returns an individual field of an error report.
  • pg_query() - Execute a query
  • pg_send_query() - Sends asynchronous query
  • pg_get_result() - Get asynchronous query result
  • pg_last_error() - Get the last error message string of a connection
  • pg_last_notice() - Returns the last notice message from PostgreSQL server

pg_result_error_field
pg_result_seek
PostgreSQL Functions


Returns an individual field of an error report.

pg_query
pg_result_error
PostgreSQL Functions
PHP Manual

pg_result_error_field

(PHP 5 >= 5.1.0)

pg_result_error_field — Returns an individual field of an error report.

Description

string pg_result_error_field ( resource $result , int $fieldcode )

pg_result_error_field() returns one of the detailed error message fields associated with result resource. It is only available against a PostgreSQL 7.4 or above server. The error field is specified by the fieldcode .

Because pg_query() and pg_query_params() return FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

If you need to get additional error information from failed pg_query() queries, use pg_set_error_verbosity() and pg_last_error() and then parse the result.

Parameters

result

A PostgreSQL query result resource from a previously executed statement.

fieldcode

Possible fieldcode values are: PGSQL_DIAG_SEVERITY, PGSQL_DIAG_SQLSTATE, PGSQL_DIAG_MESSAGE_PRIMARY, PGSQL_DIAG_MESSAGE_DETAIL, PGSQL_DIAG_MESSAGE_HINT, PGSQL_DIAG_STATEMENT_POSITION, PGSQL_DIAG_INTERNAL_POSITION (PostgreSQL 8.0+ only), PGSQL_DIAG_INTERNAL_QUERY (PostgreSQL 8.0+ only), PGSQL_DIAG_CONTEXT, PGSQL_DIAG_SOURCE_FILE, PGSQL_DIAG_SOURCE_LINE or PGSQL_DIAG_SOURCE_FUNCTION.

Return Values

A string containing the contents of the error field, NULL if the field does not exist or FALSE on failure.

Examples

Example #1 pg_result_error_field() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }

  $res1 = pg_get_result($dbconn);
  echo pg_result_error_field($res1, PGSQL_DIAG_SQLSTATE);
?>

See Also

  • pg_result_error() - Get error message associated with result

pg_query
pg_result_error
PostgreSQL Functions


Set internal row offset in result resource

pg_result_error
pg_result_status
PostgreSQL Functions
PHP Manual

pg_result_seek

(PHP 4 >= 4.3.0, PHP 5)

pg_result_seek — Set internal row offset in result resource

Description

bool pg_result_seek ( resource $result , int $offset )

pg_result_seek() sets the internal row offset in a result resource.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

offset

Row to move the internal offset to in the result resource. Rows are numbered starting from zero.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_result_seek() example

<?php

// Connect to the database
$conn = pg_pconnect("dbname=publisher");

// Execute a query
$result = pg_query($conn, "SELECT author, email FROM authors");

// Seek to the 3rd row (assuming there are 3 rows)
pg_result_seek($result, 2);

// Fetch the 3rd row
$row = pg_fetch_row($result);

?>

See Also

  • pg_fetch_row() - Get a row as an enumerated array
  • pg_fetch_assoc() - Fetch a row as an associative array
  • pg_fetch_array() - Fetch a row as an array
  • pg_fetch_object() - Fetch a row as an object
  • pg_fetch_result() - Returns values from a result resource

pg_result_error
pg_result_status
PostgreSQL Functions


Get status of query result

pg_result_seek
pg_select
PostgreSQL Functions
PHP Manual

pg_result_status

(PHP 4 >= 4.2.0, PHP 5)

pg_result_status — Get status of query result

Description

mixed pg_result_status ( resource $result [, int $type ] )

pg_result_status() returns the status of a result resource, or the PostgreSQL command completion tag associated with the result

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

type

Either PGSQL_STATUS_LONG to return the numeric status of the result , or PGSQL_STATUS_STRING to return the command tag of the result . If not specified, PGSQL_STATUS_LONG is the default.

Return Values

Possible return values are PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR if PGSQL_STATUS_LONG is specified. Otherwise, a string containing the PostgreSQL command tag is returned.

Changelog

Version | Description
4.3.0 | The type parameter was added.

Examples

Example #1 pg_result_status() example

<?php

// Connect to the database
$conn = pg_pconnect("dbname=publisher");

// Execute a COPY
$result = pg_query($conn, "COPY authors FROM STDIN;");

// Get the result status
$status = pg_result_status($result);

// Determine status
if ($status == PGSQL_COPY_IN)
   echo "Copy began.";
else
   echo "Copy failed.";

?>

The above example will output:

Copy began.

See Also

  • pg_connection_status() - Get connection status

pg_result_seek
pg_select
PostgreSQL Functions


Select records

pg_result_status
pg_send_execute
PostgreSQL Functions
PHP Manual

pg_select

(PHP 4 >= 4.3.0, PHP 5)

pg_select — Select records

Description

mixed pg_select ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC ] )

pg_select() selects records specified by assoc_array which has field=>value. For a successful query, it returns an array containing all records and fields that match the condition specified by assoc_array.

If options is specified, pg_convert() is applied to assoc_array with the specified flags.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to select rows.

assoc_array

An array whose keys are field names in the table table_name , and whose values are the conditions that a row must meet to be retrieved.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options .

Examples

Example #1 pg_select() example

<?php
  $db = pg_connect('dbname=foo');
  // This is safe, since $_POST is converted automatically
  $rec = pg_select($db, 'post_log', $_POST);
  if ($rec) {
      echo "Records selected\n";
      var_dump($rec);
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

pg_result_status
pg_send_execute
PostgreSQL Functions


Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

pg_select
pg_send_prepare
PostgreSQL Functions
PHP Manual

pg_send_execute

(PHP 5 >= 5.1.0)

pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

Description

bool pg_send_execute ( resource $connection , string $stmtname , array $params )

Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

This is similar to pg_send_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. The function's parameters are handled identically to pg_execute(). Like pg_execute(), it will not work on pre-7.4 versions of PostgreSQL.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Return Values

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Examples

Example #1 Using pg_send_execute()

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Prepare a query for execution
  if (!pg_connection_busy($dbconn)) {
    pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
    $res1 = pg_get_result($dbconn);
  }

  // Execute the prepared query.  Note that it is not necessary to escape
  // the string "Joe's Widgets" in any way
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
    $res2 = pg_get_result($dbconn);
  }

  // Execute the same prepared query, this time with a different parameter
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
    $res3 = pg_get_result($dbconn);
  }

?>

See Also

  • pg_prepare() - Submits a request to create a prepared statement with the given parameters, and waits for completion.
  • pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion.
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_select
pg_send_prepare
PostgreSQL Functions


Sends a request to create a prepared statement with the given parameters, without waiting for completion.

pg_send_execute
pg_send_query_params
PostgreSQL Functions
PHP Manual

pg_send_prepare

(PHP 5 >= 5.1.0)

pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion.

Description

bool pg_send_prepare ( resource $connection , string $stmtname , string $query )

Sends a request to create a prepared statement with the given parameters, without waiting for completion.

This is an asynchronous version of pg_prepare(): it returns TRUE if it was able to dispatch the request, and FALSE if not. After a successful call, call pg_get_result() to determine whether the server successfully created the prepared statement. The function's parameters are handled identically to pg_prepare(). Like pg_prepare(), it will not work on pre-7.4 versions of PostgreSQL.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Return Values

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Examples

Example #1 Using pg_send_prepare()

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Prepare a query for execution
  if (!pg_connection_busy($dbconn)) {
    pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
    $res1 = pg_get_result($dbconn);
  }

  // Execute the prepared query.  Note that it is not necessary to escape
  // the string "Joe's Widgets" in any way
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
    $res2 = pg_get_result($dbconn);
  }

  // Execute the same prepared query, this time with a different parameter
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
    $res3 = pg_get_result($dbconn);
  }

?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
  • pg_send_query_params() - Submits a command and separate parameters to the server without waiting for the result(s).

pg_send_execute
pg_send_query_params
PostgreSQL Functions


Sends asynchronous query

pg_send_query_params
pg_set_client_encoding
PostgreSQL Functions
PHP Manual

pg_send_query

(PHP 4 >= 4.2.0, PHP 5)

pg_send_query — Sends asynchronous query

Description

bool pg_send_query ( resource $connection , string $query )

pg_send_query() sends a query or queries asynchronously to the connection . Unlike pg_query(), it can send multiple queries at once to PostgreSQL and get the results one by one using pg_get_result().

Script execution is not blocked while the queries are executing. Use pg_connection_busy() to check if the connection is busy (i.e. the query is executing). Queries may be cancelled using pg_cancel_query().

Although the user can send multiple queries at once, multiple queries cannot be sent over a busy connection. If a query is sent while the connection is busy, it waits until the last query is finished and discards all its results.

Parameters

connection

PostgreSQL database connection resource.

query

The SQL statement or statements to be executed.

Data inside the query should be properly escaped.

Return Values

Returns TRUE on success or FALSE on failure.

Use pg_get_result() to determine the query result.

Examples

Example #1 pg_send_query() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
  }

  $res1 = pg_get_result($dbconn);
  echo "First call to pg_get_result(): $res1\n";
  $rows1 = pg_num_rows($res1);
  echo "$res1 has $rows1 records\n\n";

  $res2 = pg_get_result($dbconn);
  echo "Second call to pg_get_result(): $res2\n";
  $rows2 = pg_num_rows($res2);
  echo "$res2 has $rows2 records\n";
?>

The above example will output:

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records

See Also

  • pg_query() - Execute a query
  • pg_cancel_query() - Cancel an asynchronous query
  • pg_get_result() - Get asynchronous query result
  • pg_connection_busy() - Get connection is busy or not

pg_send_query_params
pg_set_client_encoding
PostgreSQL Functions


Submits a command and separate parameters to the server without waiting for the result(s).

pg_send_prepare
pg_send_query
PostgreSQL Functions
PHP Manual

pg_send_query_params

(PHP 5 >= 5.1.0)

pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s).

Description

bool pg_send_query_params ( resource $connection , string $query , array $params )

Submits a command and separate parameters to the server without waiting for the result(s).

This is equivalent to pg_send_query() except that query parameters can be specified separately from the query string. The function's parameters are handled identically to pg_query_params(). Like pg_query_params(), it will not work on pre-7.4 PostgreSQL connections, and it allows only one command in the query string.

Parameters

connection

PostgreSQL database connection resource.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Return Values

Returns TRUE on success or FALSE on failure.

Use pg_get_result() to determine the query result.

Examples

Example #1 Using pg_send_query_params()

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Using parameters.  Note that it is not necessary to quote or escape
  // the parameter.
  pg_send_query_params($dbconn, 'select count(*) from authors where city = $1', array('Perth'));

  // Compare against basic pg_send_query usage
  $str = pg_escape_string('Perth');
  pg_send_query($dbconn, "select count(*) from authors where city = '${str}'");
?>

See Also

  • pg_send_query() - Sends asynchronous query

pg_send_prepare
pg_send_query
PostgreSQL Functions


Set the client encoding

pg_send_query
pg_set_error_verbosity
PostgreSQL Functions
PHP Manual

pg_set_client_encoding

(PHP 4 >= 4.0.3, PHP 5)

pg_set_client_encoding — Set the client encoding

Description

int pg_set_client_encoding ([ resource $connection ], string $encoding )

pg_set_client_encoding() sets the client encoding and returns 0 if success or -1 if error.

PostgreSQL will automatically convert data in the backend database encoding into the frontend encoding.

Note: The function used to be called pg_setclientencoding().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

encoding

The required client encoding. One of SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5 or WIN1250.

The exact list of available encodings depends on your PostgreSQL version, so check your PostgreSQL manual for a more specific list.

Return Values

Returns 0 on success or -1 on error.

Examples

Example #1 pg_set_client_encoding() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

// Set the client encoding to UNICODE.  Data will be automatically
// converted from the backend encoding to the frontend.
pg_set_client_encoding($conn, "UNICODE");

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Write out UTF-8 data
while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

?>

See Also

  • pg_client_encoding() - Gets the client encoding

pg_send_query
pg_set_error_verbosity
PostgreSQL Functions


Determines the verbosity of messages returned by pg_last_error and pg_result_error.

pg_set_client_encoding
pg_trace
PostgreSQL Functions
PHP Manual

pg_set_error_verbosity

(PHP 5 >= 5.1.0)

pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

Description

int pg_set_error_verbosity ([ resource $connection ], int $verbosity )

Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

pg_set_error_verbosity() sets the verbosity mode, returning the connection's previous setting. In PGSQL_ERRORS_TERSE mode, returned messages include severity, primary text, and position only; this will normally fit on a single line. The default mode (PGSQL_ERRORS_DEFAULT) produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines). The PGSQL_ERRORS_VERBOSE mode includes all available fields. Changing the verbosity does not affect the messages available from already-existing result objects, only subsequently-created ones.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

verbosity

The required verbosity: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Return Values

The previous verbosity level: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Examples

Example #1 pg_set_error_verbosity() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }

  pg_set_error_verbosity($dbconn, PGSQL_ERRORS_VERBOSE);
  $res1 = pg_get_result($dbconn);
  echo pg_result_error($res1);
?>

See Also

  • pg_last_error() - Get the last error message string of a connection
  • pg_result_error() - Get error message associated with result

pg_set_client_encoding
pg_trace
PostgreSQL Functions


Enable tracing a PostgreSQL connection

pg_set_error_verbosity
pg_transaction_status
PostgreSQL Functions
PHP Manual

pg_trace

(PHP 4 >= 4.0.1, PHP 5)

pg_trace — Enable tracing a PostgreSQL connection

Description

bool pg_trace ( string $pathname [, string $mode = "w" [, resource $connection ]] )

pg_trace() enables tracing of the PostgreSQL frontend/backend communication to a file. To fully understand the results, one needs to be familiar with the internals of PostgreSQL communication protocol.

For those who are not, it can still be useful for tracing errors in queries sent to the server, you could do for example grep '^To backend' trace.log and see what queries actually were sent to the PostgreSQL server. For more information, refer to the » PostgreSQL Documentation.

Parameters

pathname

The full path and file name of the file in which to write the trace log. Same as in fopen().

pathname

An optional file access mode, same as for fopen().

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_trace() example

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
   pg_query("SELECT 1");
   pg_untrace($pgsql_conn);
   // Now /tmp/trace.log will contain backend communication
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

See Also

  • fopen() - Opens file or URL
  • pg_untrace() - Disable tracing of a PostgreSQL connection

pg_set_error_verbosity
pg_transaction_status
PostgreSQL Functions


Returns the current in-transaction status of the server.

pg_trace
pg_tty
PostgreSQL Functions
PHP Manual

pg_transaction_status

(PHP 5 >= 5.1.0)

pg_transaction_status — Returns the current in-transaction status of the server.

Description

int pg_transaction_status ( resource $connection )

Returns the current in-transaction status of the server.

Caution

pg_transaction_status() will give incorrect results when using a PostgreSQL 7.3 server that has the parameter autocommit set to off. The server-side autocommit feature has been deprecated and does not exist in later server versions.

Parameters

connection

PostgreSQL database connection resource.

Return Values

The status can be PGSQL_TRANSACTION_IDLE (currently idle), PGSQL_TRANSACTION_ACTIVE (a command is in progress), PGSQL_TRANSACTION_INTRANS (idle, in a valid transaction block), or PGSQL_TRANSACTION_INERROR (idle, in a failed transaction block). PGSQL_TRANSACTION_UNKNOWN is reported if the connection is bad. PGSQL_TRANSACTION_ACTIVE is reported only when a query has been sent to the server and not yet completed.

Examples

Example #1 pg_transaction_status() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $stat = pg_transaction_status($dbconn);
  if ($stat === PGSQL_TRANSACTION_UNKNOWN) {
      echo 'Connection is bad';
  } else if ($stat === PGSQL_TRANSACTION_IDLE) {
      echo 'Connection is currently idle';
  } else {
      echo 'Connection is in a transaction state';
  }
?>

pg_trace
pg_tty
PostgreSQL Functions


Return the TTY name associated with the connection

pg_transaction_status
pg_unescape_bytea
PostgreSQL Functions
PHP Manual

pg_tty

(PHP 4, PHP 5)

pg_tty — Return the TTY name associated with the connection

Description

string pg_tty ([ resource $connection ] )

pg_tty() returns the TTY name that server side debugging output is sent to on the given PostgreSQL connection resource.

Note: pg_tty() is obsolete, since the server no longer pays attention to the TTY setting, but the function remains for backwards compatibility.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the debug TTY of the connection , or FALSE on error.

Examples

Example #1 pg_tty() example

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   print "Server debug TTY is: " . pg_tty($pgsql_conn) . "<br/>\n";
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

pg_transaction_status
pg_unescape_bytea
PostgreSQL Functions


Unescape binary for bytea type

pg_tty
pg_untrace
PostgreSQL Functions
PHP Manual

pg_unescape_bytea

(PHP 4 >= 4.3.0, PHP 5)

pg_unescape_bytea — Unescape binary for bytea type

Description

string pg_unescape_bytea ( string $data )

pg_unescape_bytea() unescapes PostgreSQL bytea data values. It returns the unescaped string, possibly containing binary data.

Note: When you SELECT a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.
This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e. INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea); PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error.

Parameters

data

A string containing PostgreSQL bytea data to be converted into a PHP binary string.

Return Values

A string containing the unescaped data.

Examples

Example #1 pg_unescape_bytea() example

<?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Get the bytea data
  $res = pg_query("SELECT data FROM gallery WHERE name='Pine trees'");
  $raw = pg_fetch_result($res, 'data');

  // Convert to binary and send to the browser
  header('Content-type: image/jpeg');
  echo pg_unescape_bytea($raw);
?>

See Also

  • pg_escape_bytea() - Escape a string for insertion into a bytea field
  • pg_escape_string() - Escape a string for insertion into a text field

pg_tty
pg_untrace
PostgreSQL Functions


Disable tracing of a PostgreSQL connection

pg_unescape_bytea
pg_update
PostgreSQL Functions
PHP Manual

pg_untrace

(PHP 4 >= 4.0.1, PHP 5)

pg_untrace — Disable tracing of a PostgreSQL connection

Description

bool pg_untrace ([ resource $connection ] )

Stop tracing started by pg_trace().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Always returns TRUE.

Examples

Example #1 pg_untrace() example

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
   pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
   pg_query("SELECT 1");
   pg_untrace($pgsql_conn);
   // Now tracing of backend communication is disabled
} else {
   print pg_last_error($pgsql_conn);
   exit;
}
?>

See Also

  • pg_trace() - Enable tracing a PostgreSQL connection

pg_unescape_bytea
pg_update
PostgreSQL Functions


Update table

pg_untrace
pg_version
PostgreSQL Functions
PHP Manual

pg_update

(PHP 4 >= 4.3.0, PHP 5)

pg_update — Update table

Description

mixed pg_update ( resource $connection , string $table_name , array $data , array $condition [, int $options = PGSQL_DML_EXEC ] )

pg_update() updates records that matches condition with data. If options is specified, pg_convert() is applied to data with specified options.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to update rows.

data

An array whose keys are field names in the table table_name , and whose values are what matched rows are to be updated to.

condition

An array whose keys are field names in the table table_name , and whose values are the conditions that a row must meet to be updated.

options

Any number of PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options .

Examples

Example #1 pg_update() example

<?php
  $db = pg_connect('dbname=foo');
  $data = array('field1'=>'AA', 'field2'=>'BB');

  // This is safe, since $_POST is converted automatically
  $res = pg_update($db, 'post_log', $_POST, $data);
  if ($res) {
      echo "Data is updated: $res\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

pg_untrace
pg_version
PostgreSQL Functions


Returns an array with client, protocol and server version (when available)

pg_update
SQLite
PostgreSQL Functions
PHP Manual

pg_version

(PHP 5)

pg_version — Returns an array with client, protocol and server version (when available)

Description

array pg_version ([ resource $connection ] )

pg_version() returns an array with the client, protocol and server version. Protocol and server versions are only available if PHP was compiled with PostgreSQL 7.4 or later.

For more detailed server information, use pg_parameter_status().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns an array with client, protocol and server_version keys and values (if available). Returns FALSE on error or invalid connection.

Examples

Example #1 pg_version() example

<?php
  $dbconn = pg_connect("host=localhost port=5432 dbname=mary")
     or die("Could not connect");

  $v = pg_version($dbconn);

  echo $v['client'];
?>

The above example will output:

7.4

See Also

  • pg_parameter_status() - Looks up a current parameter setting of the server.

pg_update
SQLite
PostgreSQL Functions


Check the PHP syntax of (and execute) the specified file

pack
php_strip_whitespace
Misc. Functions
PHP Manual

php_check_syntax

(PHP 5 <= 5.0.4)

php_check_syntax — Check the PHP syntax of (and execute) the specified file

Description

bool php_check_syntax ( string $filename [, string &$error_message ] )

Performs a syntax (lint) check on the specified filename testing for scripting errors.

This is similar to using php -l from the commandline except that this function will execute (but not output) the checked filename .

For example, if a function is defined in filename , this defined function will be available to the file that executed php_check_syntax(), but output from filename will be suppressed.

Note: For technical reasons, this function is deprecated and removed from PHP. Instead, use php -l somefile.php from the commandline.

Parameters

filename

The name of the file being checked.

error_message

If the error_message parameter is used, it will contain the error message generated by the syntax check. error_message is passed by reference.

Return Values

Returns TRUE if the lint check passed, and FALSE if the link check failed or if filename cannot be opened.

Changelog

Version | Description
5.0.5 | This function was removed from PHP.
5.0.3 | Calling exit() after php_check_syntax() resulted in a Segfault.
5.0.1 | error_message is passed by reference.

Examples

php -l somefile.php

The above example will output something similar to:

PHP Parse error: unexpected T_STRING in /tmp/somefile.php on line 81

See Also

  • include() - include
  • is_readable() - Tells whether a file exists and is readable

pack
php_strip_whitespace
Misc. Functions


Retrieve a path to the loaded php.ini file

memory_get_usage
php_ini_scanned_files
PHP Options/Info Functions
PHP Manual

php_ini_loaded_file

(PHP 5 >= 5.2.4)

php_ini_loaded_file — Retrieve a path to the loaded php.ini file

Description

string php_ini_loaded_file ( void )

Check if a php.ini file is loaded, and retrieve its path.

Parameters

This function has no parameters.

Return Values

The loaded php.ini path, or FALSE if one is not loaded.

Examples

Example #1 php_ini_loaded_file() example

<?php
$inipath = php_ini_loaded_file();

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

The above example will output something similar to:

Loaded php.ini: /usr/local/php/php.ini

See Also

  • php_ini_scanned_files() - Return a list of .ini files parsed from the additional ini dir
  • phpinfo() - Outputs lots of PHP information
  • The configuration file

memory_get_usage
php_ini_scanned_files
PHP Options/Info Functions


Return a list of .ini files parsed from the additional ini dir

php_ini_loaded_file
php_logo_guid
PHP Options/Info Functions
PHP Manual

php_ini_scanned_files

(PHP 4 >= 4.3.0, PHP 5)

php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir

Description

string php_ini_scanned_files ( void )

php_ini_scanned_files() returns a comma-separated list of configuration files parsed after php.ini. These files are found in a directory defined by the --with-config-file-scan-dir option which is set during compilation.

The returned configuration files also include the path as declared in the --with-config-file-scan-dir option.

Return Values

Returns a comma-separated string of .ini files on success. Each comma is followed by a newline. If the directive --with-config-file-scan-dir wasn't set, FALSE is returned. If it was set and the directory was empty, an empty string is returned. If a file is unrecognizable, the file will still make it into the returned string but a PHP error will also result. This PHP error will be seen both at compile time and while using php_ini_scanned_files().

Examples

Example #1 A simple example to list the returned ini files

<?php
if ($filelist = php_ini_scanned_files()) {
    if (strlen($filelist) > 0) {
        $files = explode(',', $filelist);

        foreach ($files as $file) {
            echo "<li>" . trim($file) . "</li>\n";
        }
    }
}
?>

See Also

  • ini_set() - Sets the value of a configuration option
  • phpinfo() - Outputs lots of PHP information
  • php_ini_loaded_file() - Retrieve a path to the loaded php.ini file

php_ini_loaded_file
php_logo_guid
PHP Options/Info Functions


Gets the logo guid

php_ini_scanned_files
php_sapi_name
PHP Options/Info Functions
PHP Manual

php_logo_guid

(PHP 4, PHP 5)

php_logo_guid — Gets the logo guid

Description

string php_logo_guid ( void )

This function returns the ID which can be used to display the PHP logo using the built-in image. Logo is displayed only if expose_php is On.

Return Values

Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.

Examples

Example #1 php_logo_guid() example

<?php

echo '<img src="' . $_SERVER['PHP_SELF'] .
     '?=' . php_logo_guid() . '" alt="PHP Logo !" />';

?>

See Also

  • phpinfo() - Outputs lots of PHP information
  • phpversion() - Gets the current PHP version
  • phpcredits() - Prints out the credits for PHP
  • zend_logo_guid() - Gets the Zend guid

php_ini_scanned_files
php_sapi_name
PHP Options/Info Functions


Returns the type of interface between web server and PHP

php_logo_guid
php_uname
PHP Options/Info Functions
PHP Manual

php_sapi_name

(PHP 4 >= 4.0.1, PHP 5)

php_sapi_name — Returns the type of interface between web server and PHP

Description

string php_sapi_name ( void )

Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using. For example, in CLI PHP this string will be "cli" whereas with Apache it may have several different values depending on the exact SAPI used. Possible values are listed below.

Return Values

Returns the interface type, as a lowercase string.

Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.

Examples

Example #1 php_sapi_name() example

This example checks for the substring cgi because it may also be cgi-fcgi.

<?php
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') {
    echo "You are using CGI PHP\n";
} else {
    echo "You are not using CGI PHP\n";
}
?>

Notes

Note: An alternative approach
The PHP constant PHP_SAPI has the same value as php_sapi_name().

Tip

A potential gotcha

The defined SAPI may not be obvious, because for example instead of apache it may be defined as apache2handler or apache2filter.

See Also

  • PHP_SAPI

php_logo_guid
php_uname
PHP Options/Info Functions


Return source with stripped comments and whitespace

php_check_syntax
show_source
Misc. Functions
PHP Manual

php_strip_whitespace

(PHP 5)

php_strip_whitespace — Return source with stripped comments and whitespace

Description

string php_strip_whitespace ( string $filename )

Returns the PHP source code in filename with PHP comments and whitespace removed. This may be useful for determining the amount of actual code in your scripts compared with the amount of comments. This is similar to using php -w from the commandline.

Parameters

filename

Path to the PHP file.

Return Values

The stripped source code will be returned on success, or an empty string on failure.

Note: This function works as described as of PHP 5.0.1. Before this it would only return an empty string. For more information on this bug and its prior behavior, see bug report » #29606.

Examples

Example #1 php_strip_whitespace() example

<?php
// PHP comment here

/*
 * Another PHP comment
 */

echo        php_strip_whitespace(__FILE__);
// Newlines are considered whitespace, and are removed too:
do_nothing();
?>

The above example will output:

<?php
 echo php_strip_whitespace(__FILE__); do_nothing(); ?>

Notice the PHP comments are gone, as are the whitespace and newline after the first echo statement.

php_check_syntax
show_source
Misc. Functions


Returns information about the operating system PHP is running on

php_sapi_name
phpcredits
PHP Options/Info Functions
PHP Manual

php_uname

(PHP 4 >= 4.0.2, PHP 5)

php_uname — Returns information about the operating system PHP is running on

Description

string php_uname ([ string $mode = "a" ] )

php_uname() returns a description of the operating system PHP is running on. This is the same string you see at the very top of the phpinfo() output. For the name of just the operating system, consider using the PHP_OS constant, but keep in mind this constant will contain the operating system PHP was built on.

On some older UNIX platforms, it may not be able to determine the current OS information in which case it will revert to displaying the OS PHP was built on. This will only happen if your uname() library call either doesn't exist or doesn't work.

Parameters

mode

mode is a single character that defines what information is returned:

  • 'a': This is the default. Contains all modes in the sequence "s n r v m".
  • 's': Operating system name. eg. FreeBSD.
  • 'n': Host name. eg. localhost.example.com.
  • 'r': Release name. eg. 5.1.2-RELEASE.
  • 'v': Version information. Varies a lot between operating systems.
  • 'm': Machine type. eg. i386.

Return Values

Returns the description, as a string.

Examples

Example #1 Some php_uname() examples

<?php
echo php_uname();
echo PHP_OS;

/* Some possible outputs:
Linux localhost 2.4.21-0.13mdk #1 Fri Mar 14 15:08:06 EST 2003 i686
Linux

FreeBSD localhost 3.2-RELEASE #15: Mon Dec 17 08:46:02 GMT 2001
FreeBSD

Windows NT XN1 5.1 build 2600
WINNT
*/

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    echo 'This is a server using Windows!';
} else {
    echo 'This is a server not using Windows!';
}

?>

There are also some related Predefined PHP constants that may come in handy, for example:

Example #2 A few OS related constant examples

<?php
// *nix
echo DIRECTORY_SEPARATOR; // /
echo PHP_SHLIB_SUFFIX;    // so
echo PATH_SEPARATOR;      // :

// Win*
echo DIRECTORY_SEPARATOR; // \
echo PHP_SHLIB_SUFFIX;    // dll
echo PATH_SEPARATOR;      // ;
?>

See Also

  • phpversion() - Gets the current PHP version
  • php_sapi_name() - Returns the type of interface between web server and PHP
  • phpinfo() - Outputs lots of PHP information

php_sapi_name
phpcredits
PHP Options/Info Functions


Prints out the credits for PHP

php_uname
phpinfo
PHP Options/Info Functions
PHP Manual

phpcredits

(PHP 4, PHP 5)

phpcredits — Prints out the credits for PHP

Description

bool phpcredits ([ int $flag = CREDITS_ALL ] )

This function prints out the credits listing the PHP developers, modules, etc. It generates the appropriate HTML codes to insert the information in a page.

Parameters

flag

To generate a custom credits page, you may want to use the flag parameter.

Pre-defined phpcredits() flags
name | description
CREDITS_ALL | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags.
CREDITS_DOCS | The credits for the documentation team
CREDITS_FULLPAGE | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_GENERAL | General credits: Language design and concept, PHP 4.0 authors and SAPI module.
CREDITS_GROUP | A list of the core developers
CREDITS_MODULES | A list of the extension modules for PHP, and their authors
CREDITS_SAPI | A list of the server API modules for PHP, and their authors

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Prints the general credits

<?php
phpcredits(CREDITS_GENERAL);
?>

Example #2 Prints the core developers and the documentation group

<?php
phpcredits(CREDITS_GROUP + CREDITS_DOCS + CREDITS_FULLPAGE);
?>

Example #3 Printing all the credits

<html>
 <head>
  <title>My credits page</title>
 </head>
 <body>
<?php
// some code of your own
phpcredits(CREDITS_ALL - CREDITS_FULLPAGE);
// some more code
?>
 </body>
</html>

See Also

  • phpversion() - Gets the current PHP version
  • php_logo_guid() - Gets the logo guid
  • phpinfo() - Outputs lots of PHP information

php_uname
phpinfo
PHP Options/Info Functions


Outputs lots of PHP information

phpcredits
phpversion
PHP Options/Info Functions
PHP Manual

phpinfo

(PHP 4, PHP 5)

phpinfo — Outputs lots of PHP information

Description

bool phpinfo ([ int $what = INFO_ALL ] )

Outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the PHP License.

Because every system is setup differently, phpinfo() is commonly used to check configuration settings and for available predefined variables on a given system.

phpinfo() is also a valuable debugging tool as it contains all EGPCS (Environment, GET, POST, Cookie, Server) data.

Parameters

what

The output may be customized by passing one or more of the following constants bitwise values summed together in the optional what parameter. One can also combine the respective constants or bitwise values together with the or operator.

phpinfo() options
Name (constant) | Value | Description
INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS | 2 | PHP Credits. See also phpcredits().
INFO_CONFIGURATION | 4 | Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES | 8 | Loaded modules and their respective settings. See also get_loaded_extensions().
INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV.
INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE | 64 | PHP License information. See also the » license FAQ.
INFO_ALL | -1 | Shows all of the above.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.2.2 | The "Loaded Configuration File" information was added, when before only "Configuration File (php.ini) Path" existed.

Examples

Example #1 phpinfo() Example

<?php

// Show all information, defaults to INFO_ALL
phpinfo();

// Show just the module information.
// phpinfo(8) yields identical results.
phpinfo(INFO_MODULES);

?>

Notes

Note: Parts of the information displayed are disabled when the expose_php configuration setting is set to off. This includes the PHP and Zend logos, and the credits.

Note: phpinfo() outputs plain text instead of HTML when using the CLI mode.

See Also

  • phpversion() - Gets the current PHP version
  • phpcredits() - Prints out the credits for PHP
  • php_logo_guid() - Gets the logo guid
  • ini_get() - Gets the value of a configuration option
  • ini_set() - Sets the value of a configuration option
  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • Predefined Variables

phpcredits
phpversion
PHP Options/Info Functions


Gets the current PHP version

phpinfo
putenv
PHP Options/Info Functions
PHP Manual

phpversion

(PHP 4, PHP 5)

phpversion — Gets the current PHP version

Description

string phpversion ([ string $extension ] )

Returns a string containing the version of the currently running PHP parser or extension.

Parameters

extension

An optional extension name.

Return Values

If the optional extension parameter is specified, phpversion() returns the version of that extension, or FALSE if there is no version information associated or the extension isn't enabled.

Examples

Example #1 phpversion() example

<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();

// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy');
?>

Example #2 PHP_VERSION_ID example and usage

<?php
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (!defined('PHP_VERSION_ID')) {
    $version = explode('.', PHP_VERSION);

    define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}

// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. It's defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn't require to use version_compare() everytime
// you check if the current PHP version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7

if (PHP_VERSION_ID < 50207) {
    define('PHP_MAJOR_VERSION',   $version[0]);
    define('PHP_MINOR_VERSION',   $version[1]);
    define('PHP_RELEASE_VERSION', $version[2]);

    // and so on, ...
}
?>

Notes

Note: This information is also available in the predefined constant PHP_VERSION. More versioning information is available using the PHP_VERSION_* constants.

See Also

  • version_compare() - Compares two "PHP-standardized" version number strings
  • phpinfo() - Outputs lots of PHP information
  • phpcredits() - Prints out the credits for PHP
  • php_logo_guid() - Gets the logo guid
  • zend_version() - Gets the version of the current Zend engine

phpinfo
putenv
PHP Options/Info Functions


Get value of pi

octdec
pow
Math Functions
PHP Manual

pi

(PHP 4, PHP 5)

pi — Get value of pi

Description

float pi ( void )

Returns an approximation of pi. The returned float has a precision based on the precision directive in php.ini, which defaults to 14. Also, you can use the M_PI constant which yields identical results to pi().

Return Values

The value of pi as float.

Examples

Example #1 pi() example

<?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?>

octdec
pow
Math Functions


Convert PNG image file to WBMP image file

jpeg2wbmp
ImageMagick
GD and Image Functions
PHP Manual

png2wbmp

(PHP 4 >= 4.0.5, PHP 5)

png2wbmp — Convert PNG image file to WBMP image file

Description

bool png2wbmp ( string $pngname , string $wbmpname , int $dest_height , int $dest_width , int $threshold )

Converts a PNG file into a WBMP file.

Parameters

pngname

Path to PNG file.

wbmpname

Path to destination WBMP file.

dest_height

Destination image height.

dest_width

Destination image width.

threshold

Threshold value, between 0 and 8 (inclusive).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 png2wbmp() example

<?php
// Path to the target png
$path = './test.png';

// Get the image sizes
$image = getimagesize($path);

// Convert image
png2wbmp($path, './test.wbmp', $image[1], $image[0], 7);
?>

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See Also

  • jpeg2wbmp() - Convert JPEG image file to WBMP image file

jpeg2wbmp
ImageMagick
GD and Image Functions


Opens process file pointer

pclose
readfile
Filesystem Functions
PHP Manual

popen

(PHP 4, PHP 5)

popen — Opens process file pointer

Description

resource popen ( string $command , string $mode )

Opens a pipe to a process executed by forking the command given by command.

Parameters

command

The command

mode

The mode

Return Values

Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fwrite().

If an error occurs, returns FALSE.

Examples

Example #1 popen() example

<?php
$handle = popen("/bin/ls", "r");
?>

If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell:

Example #2 popen() example

<?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>

Notes

Note: If you're looking for bi-directional support (two-way), use proc_open().

Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.

Warning

With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x.

See Also

  • pclose() - Closes process file pointer
  • fopen() - Opens file or URL
  • proc_open() - Execute a command and open file pointers for input/output

pclose
readfile
Filesystem Functions


Determine accessibility of a file

POSIX Functions
posix_ctermid
POSIX Functions
PHP Manual

posix_access

(PHP 5 >= 5.1.0)

posix_access — Determine accessibility of a file

Description

bool posix_access ( string $file [, int $mode = POSIX_F_OK ] )

posix_access() checks the user's permission of a file.

Parameters

file

The name of the file to be tested.

mode

A mask consisting of one or more of POSIX_F_OK, POSIX_R_OK, POSIX_W_OK and POSIX_X_OK.

POSIX_R_OK, POSIX_W_OK and POSIX_X_OK request checking whether the file exists and has read, write and execute permissions, respectively. POSIX_F_OK just requests checking for the existence of the file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_access() example

This example will check if the $file is readable and writable, otherwise will print an error message.

<?php

$file = 'some_file';

if (posix_access($file, POSIX_R_OK | POSIX_W_OK)) {
    echo 'The file is readable and writable!';

} else {
    $error = posix_get_last_error();

    echo "Error $error: " . posix_strerror($error);
}

?>

Notes

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

See Also

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed
  • posix_strerror() - Retrieve the system error message associated with the given errno

POSIX Functions
posix_ctermid
POSIX Functions


Get path name of controlling terminal

posix_access
posix_errno
POSIX Functions
PHP Manual

posix_ctermid

(PHP 4, PHP 5)

posix_ctermid — Get path name of controlling terminal

Description

string posix_ctermid ( void )

Generates a string which is the pathname for the current controlling terminal for the process. On error this will set errno, which can be checked using posix_get_last_error()

Return Values

Upon successful completion, returns string of the pathname to the current controlling terminal. Otherwise FALSE is returned and errno is set, which can be checked with posix_get_last_error().

Examples

Example #1 posix_ctermid() example

This example will display the path to the current TTY.

<?php
echo "I am running from ".posix_ctermid();
?>

See Also

  • posix_ttyname() - Determine terminal device name
  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed

posix_access
posix_errno
POSIX Functions


Alias of posix_get_last_error

posix_ctermid
posix_get_last_error
POSIX Functions
PHP Manual

posix_errno

(PHP 4 >= 4.2.0, PHP 5)

posix_errno — Alias of posix_get_last_error()

Description

This function is an alias of: posix_get_last_error().

posix_ctermid
posix_get_last_error
POSIX Functions


Retrieve the error number set by the last posix function that failed

posix_errno
posix_getcwd
POSIX Functions
PHP Manual

posix_get_last_error

(PHP 4 >= 4.2.0, PHP 5)

posix_get_last_error — Retrieve the error number set by the last posix function that failed

Description

int posix_get_last_error ( void )

Retrieve the error number set by the last posix function that failed. The system error message associated with the errno may be checked with posix_strerror().

Return Values

Returns the errno (error number) set by the last posix function that failed. If no errors exist, 0 is returned.

Examples

Example #1 posix_get_last_error() example

This example attempt to kill a bogus process id, which will set the last error. We will then print out the last errno.

<?php
posix_kill(999459,SIGKILL);
echo 'Your error returned was '.posix_get_last_error(); //Your error was ___
?>

See Also

  • posix_strerror() - Retrieve the system error message associated with the given errno

posix_errno
posix_getcwd
POSIX Functions


Pathname of current directory

posix_get_last_error
posix_getegid
POSIX Functions
PHP Manual

posix_getcwd

(PHP 4, PHP 5)

posix_getcwd — Pathname of current directory

Description

string posix_getcwd ( void )

Gets the absolute pathname of the script's current working directory. On error, it sets errno which can be checked using posix_get_last_error()

Return Values

Returns a string of the absolute pathname on success. On error, returns FALSE and sets errno which can be checked with posix_get_last_error().

Examples

Example #1 posix_getcwd() example

This example will return the absolute path of the current working directory of the script.

<?php
echo 'My current working directory is '.posix_getcwd();
?>

Notes

Note: This function can fail on

  • Read or Search permission was denied
  • Pathname no longer exists

posix_get_last_error
posix_getegid
POSIX Functions


Return the effective group ID of the current process

posix_getcwd
posix_geteuid
POSIX Functions
PHP Manual

posix_getegid

(PHP 4, PHP 5)

posix_getegid — Return the effective group ID of the current process

Description

int posix_getegid ( void )

Return the numeric effective group ID of the current process.

Return Values

Returns an integer of the effective group ID.

Examples

Example #1 posix_getegid() example

This example will print out the effective group id, once it is changed with posix_setegid().

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

Notes

posix_getegid() is different than posix_getgid() because effective group ID can be changed by a calling process using posix_setegid().

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process
  • posix_setgid() - Set the GID of the current process

posix_getcwd
posix_geteuid
POSIX Functions


Return the effective user ID of the current process

posix_getegid
posix_getgid
POSIX Functions
PHP Manual

posix_geteuid

(PHP 4, PHP 5)

posix_geteuid — Return the effective user ID of the current process

Description

int posix_geteuid ( void )

Return the numeric effective user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.

Return Values

Returns the user id, as an integer

Examples

Example #1 posix_geteuid() example

This example will show the current user id then set the effective user id to a separate id using posix_seteuid(), then show the difference between the real id and the effective id.

<?php
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10001
posix_seteuid(10000);
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10000
?>

See Also

  • posix_getpwuid() - Return info about a user by user id
  • posix_getuid() - Return the real user ID of the current process
  • posix_setuid() - Set the UID of the current process
  • POSIX man page GETEUID(2)

posix_getegid
posix_getgid
POSIX Functions


Return the real group ID of the current process

posix_geteuid
posix_getgrgid
POSIX Functions
PHP Manual

posix_getgid

(PHP 4, PHP 5)

posix_getgid — Return the real group ID of the current process

Description

int posix_getgid ( void )

Return the numeric real group ID of the current process.

Return Values

Returns the real group id, as an integer.

Examples

Example #1 posix_getgid() example

This example will print out the real group id, even once the effective group id has been changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getegid() - Return the effective group ID of the current process
  • posix_setgid() - Set the GID of the current process
  • POSIX man page GETGID(2)

posix_geteuid
posix_getgrgid
POSIX Functions


Return info about a group by group id

posix_getgid
posix_getgrnam
POSIX Functions
PHP Manual

posix_getgrgid

(PHP 4, PHP 5)

posix_getgrgid — Return info about a group by group id

Description

array posix_getgrgid ( int $gid )

Gets information about a group provided its id.

Parameters

gid

The group id.

Return Values

The array elements returned are:

The group information array
Element | Description
name | The name element contains the name of the group. This is a short, usually less than 16 character "handle" of the group, not the real, full name.
passwd | The passwd element contains the group's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
gid | Group ID, should be the same as the gid parameter used when calling the function, and hence redundant.
members | This consists of an array of string's for all the members in the group.

Changelog

Version | Description
4.2.0 | Prior to this version, members was simply an integer representing the number of members in the group, and the member names were returned with numerical indices.

Examples

Example #1 Example use of posix_getgrgid()

<?php

$groupid   = posix_getegid();
$groupinfo = posix_getgrgid($groupid);

print_r($groupinfo);
?>

The above example will output something similar to:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

See Also

  • posix_getegid() - Return the effective group ID of the current process
  • posix_getgrnam() - Return info about a group by name
  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • safe_mode_gid
  • POSIX man page GETGRNAM(3)

posix_getgid
posix_getgrnam
POSIX Functions


Return info about a group by name

posix_getgrgid
posix_getgroups
POSIX Functions
PHP Manual

posix_getgrnam

(PHP 4, PHP 5)

posix_getgrnam — Return info about a group by name

Description

array posix_getgrnam ( string $name )

Gets information about a group provided its name.

Parameters

name

The name of the group

Return Values

The array elements returned are:

The group information array
Element | Description
name | The name element contains the name of the group. This is a short, usually less than 16 character "handle" of the group, not the real, full name. This should be the same as the name parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the group's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
gid | Group ID of the group in numeric form.
members | This consists of an array of string's for all the members in the group.

Changelog

Version | Description
4.2.0 | Prior to this version, members was simply an integer representing the number of members in the group, and the member names were returned with numerical indices.

Examples

Example #1 Example use of posix_getgrnam()

<?php

$groupinfo = posix_getgrnam("toons");

print_r($groupinfo);
?>

The above example will output something similar to:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

See Also

  • posix_getegid() - Return the effective group ID of the current process
  • posix_getgrgid() - Return info about a group by group id
  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • safe_mode_gid
  • POSIX man page GETGRNAM(3)

posix_getgrgid
posix_getgroups
POSIX Functions


Return the group set of the current process

posix_getgrnam
posix_getlogin
POSIX Functions
PHP Manual

posix_getgroups

(PHP 4, PHP 5)

posix_getgroups — Return the group set of the current process

Description

array posix_getgroups ( void )

Gets the group set of the current process.

Return Values

Returns an array of integers containing the numeric group ids of the group set of the current process.

Examples

Example #1 Example use of posix_getgroups()

<?php

$groups = posix_getgroups();

print_r($groups);
?>

The above example will output something similar to:

Array
(
    [0] => 4
    [1] => 20
    [2] => 24
    [3] => 25
    [4] => 29
    [5] => 30
    [6] => 33
    [7] => 44
    [8] => 46
    [9] => 104
    [10] => 109
    [11] => 110
    [12] => 1000
)

See Also

  • posix_getgrgid() - Return info about a group by group id

posix_getgrnam
posix_getlogin
POSIX Functions


Return login name

posix_getgroups
posix_getpgid
POSIX Functions
PHP Manual

posix_getlogin

(PHP 4, PHP 5)

posix_getlogin — Return login name

Description

string posix_getlogin ( void )

Returns the login name of the user owning the current process.

Return Values

Returns the login name of the user, as a string.

Examples

Example #1 Example use of posix_getlogin()

<?php
echo posix_getlogin(); //apache
?>

See Also

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETLOGIN(3)

posix_getgroups
posix_getpgid
POSIX Functions


Get process group id for job control

posix_getlogin
posix_getpgrp
POSIX Functions
PHP Manual

posix_getpgid

(PHP 4, PHP 5)

posix_getpgid — Get process group id for job control

Description

int posix_getpgid ( int $pid )

Returns the process group identifier of the process pid or FALSE on failure.

Parameters

pid

The process id.

Return Values

Returns the identifier, as an integer.

Examples

Example #1 Example use of posix_getpgid()

<?php
$pid = posix_getppid();
echo posix_getpgid($pid); //35
?>

Notes

Note: This is a not POSIX function, but is common on BSD and System V systems. If the system does not support this function, then it will not be included at compile time. This may be checked with function_exists().

See Also

  • posix_getppid() - Return the parent process identifier
  • man page SETPGID(2)

posix_getlogin
posix_getpgrp
POSIX Functions


Return the current process group identifier

posix_getpgid
posix_getpid
POSIX Functions
PHP Manual

posix_getpgrp

(PHP 4, PHP 5)

posix_getpgrp — Return the current process group identifier

Description

int posix_getpgrp ( void )

Return the process group identifier of the current process.

Return Values

Returns the identifier, as an integer.

See Also

  • POSIX.1 and the getpgrp(2) manual page on the POSIX system for more information on process groups.

posix_getpgid
posix_getpid
POSIX Functions


Return the current process identifier

posix_getpgrp
posix_getppid
POSIX Functions
PHP Manual

posix_getpid

(PHP 4, PHP 5)

posix_getpid — Return the current process identifier

Description

int posix_getpid ( void )

Return the process identifier of the current process.

Return Values

Returns the identifier, as an integer.

Examples

Example #1 Example use of posix_getpid()

<?php
echo posix_getpid(); //8805
?>

See Also

  • posix_kill() - Send a signal to a process
  • POSIX man page GETPID(2)

posix_getpgrp
posix_getppid
POSIX Functions


Return the parent process identifier

posix_getpid
posix_getpwnam
POSIX Functions
PHP Manual

posix_getppid

(PHP 4, PHP 5)

posix_getppid — Return the parent process identifier

Description

int posix_getppid ( void )

Return the process identifier of the parent process of the current process.

Return Values

Returns the identifier, as an integer.

Examples

Example #1 Example use of posix_getppid()

<?php
echo posix_getppid(); //8259
?>

posix_getpid
posix_getpwnam
POSIX Functions


Return info about a user by username

posix_getppid
posix_getpwuid
POSIX Functions
PHP Manual

posix_getpwnam

(PHP 4, PHP 5)

posix_getpwnam — Return info about a user by username

Description

array posix_getpwnam ( string $username )

Returns an array of information about the given user.

Parameters

username

An alphanumeric username.

Return Values

On success an array with the following elements is returned, else FALSE is returned:

The user information array
Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not the real, full name. This should be the same as the username parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID of the user in numeric form.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

Examples

Example #1 Example use of posix_getpwnam()

<?php

$userinfo = posix_getpwnam("tom");

print_r($userinfo);
?>

The above example will output something similar to:

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [geocs]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

See Also

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETPWNAM(3)

posix_getppid
posix_getpwuid
POSIX Functions


Return info about a user by user id

posix_getpwnam
posix_getrlimit
POSIX Functions
PHP Manual

posix_getpwuid

(PHP 4, PHP 5)

posix_getpwuid — Return info about a user by user id

Description

array posix_getpwuid ( int $uid )

Returns an array of information about the user referenced by the given user ID.

Parameters

uid

The user identifier.

Return Values

Returns an associative array with the following elements:

The user information array
Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not the real, full name.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID, should be the same as the uid parameter used when calling the function, and hence redundant.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

Examples

Example #1 Example use of posix_getpwuid()

<?php

$userinfo = posix_getpwuid(10000);

print_r($userinfo);
?>

The above example will output something similar to:

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [geocs]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

See Also

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETPWNAM(3)

posix_getpwnam
posix_getrlimit
POSIX Functions


Return info about system resource limits

posix_getpwuid
posix_getsid
POSIX Functions
PHP Manual

posix_getrlimit

(PHP 4, PHP 5)

posix_getrlimit — Return info about system resource limits

Description

array posix_getrlimit ( void )

posix_getrlimit() returns an array of information about the current resource's soft and hard limits.

Each resource has an associated soft and hard limit. The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit. An unprivileged process may only set its soft limit to a value from 0 to the hard limit, and irreversibly lower its hard limit.

Return Values

Returns an associative array of elements for each limit that is defined. Each limit has a soft and a hard limit.

List of possible limits returned
Limit name | Limit description
core | The maximum size of the core file. When 0, not core files are created. When core files are larger than this size, they will be truncated at this size.
totalmem | The maximum size of the memory of the process, in bytes.
virtualmem | The maximum size of the virtual memory for the process, in bytes.
data | The maximum size of the data segment for the process, in bytes.
stack | The maximum size of the process stack, in bytes.
rss | The maximum number of virtual pages resident in RAM
maxproc | The maximum number of processes that can be created for the real user ID of the calling process.
memlock | The maximum number of bytes of memory that may be locked into RAM.
cpu | The amount of time the process is allowed to use the CPU.
filesize | The maximum size of the data segment for the process, in bytes.
openfiles | One more than the maximum number of open file descriptors.

Examples

Example #1 Example use of posix_getrlimit()

<?php

$limits = posix_getrlimit();

print_r($limits);
?>

The above example will output something similar to:

Array
(
    [soft core] => 0
    [hard core] => unlimited
    [soft data] => unlimited
    [hard data] => unlimited
    [soft stack] => 8388608
    [hard stack] => unlimited
    [soft totalmem] => unlimited
    [hard totalmem] => unlimited
    [soft rss] => unlimited
    [hard rss] => unlimited
    [soft maxproc] => unlimited
    [hard maxproc] => unlimited
    [soft memlock] => unlimited
    [hard memlock] => unlimited
    [soft cpu] => unlimited
    [hard cpu] => unlimited
    [soft filesize] => unlimited
    [hard filesize] => unlimited
    [soft openfiles] => 1024
    [hard openfiles] => 1024
)

Notes

Note: This is a not POSIX function, but is common on BSD and System V systems. If the system does not support this function, then it will not be included at compile time. This may be checked with function_exists().

See Also

  • man page GETRLIMIT(2)

posix_getpwuid
posix_getsid
POSIX Functions


Get the current sid of the process

posix_getrlimit
posix_getuid
POSIX Functions
PHP Manual

posix_getsid

(PHP 4, PHP 5)

posix_getsid — Get the current sid of the process

Description

int posix_getsid ( int $pid )

Return the session id of the process pid . The session id of a process is the process group id of the session leader.

Parameters

pid

The process identifier. If set to 0, the current process is assumed. If an invalid pid is specified, then FALSE is returned and an error is set which can be checked with posix_get_last_error().

Return Values

Returns the identifier, as an integer.

Examples

Example #1 Example use of posix_getsid()

<?php
$pid = posix_getpid();
echo posix_getsid($pid); //8805
?>

See Also

  • posix_getpgid() - Get process group id for job control
  • posix_setsid() - Make the current process a session leader
  • POSIX man page GETSID(2)

posix_getrlimit
posix_getuid
POSIX Functions


Return the real user ID of the current process

posix_getsid
posix_initgroups
POSIX Functions
PHP Manual

posix_getuid

(PHP 4, PHP 5)

posix_getuid — Return the real user ID of the current process

Description

int posix_getuid ( void )

Return the numeric real user ID of the current process.

Return Values

Returns the user id, as an integer

Examples

Example #1 Example use of posix_getuid()

<?php
echo posix_getuid(); //10000
?>

See Also

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETUID(2)

posix_getsid
posix_initgroups
POSIX Functions


Calculate the group access list

posix_getuid
posix_isatty
POSIX Functions
PHP Manual

posix_initgroups

(PHP 5 >= 5.2.0)

posix_initgroups — Calculate the group access list

Description

bool posix_initgroups ( string $name , int $base_group_id )

Calculates the group access list for the user specified in name.

Parameters

name

The user to calculate the list for.

base_group_id

Typically the group number from the password file.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • The Unix manual page for initgroups(3).

posix_getuid
posix_isatty
POSIX Functions


Determine if a file descriptor is an interactive terminal

posix_initgroups
posix_kill
POSIX Functions
PHP Manual

posix_isatty

(PHP 4, PHP 5)

posix_isatty — Determine if a file descriptor is an interactive terminal

Description

bool posix_isatty ( int $fd )

Determines if the file descriptor fd refers to a valid terminal type device.

Parameters

fd

The file descriptor.

Return Values

Returns TRUE if fd is an open descriptor connected to a terminal and FALSE otherwise.

See Also

  • posix_ttyname() - Determine terminal device name

posix_initgroups
posix_kill
POSIX Functions


Send a signal to a process

posix_isatty
posix_mkfifo
POSIX Functions
PHP Manual

posix_kill

(PHP 4, PHP 5)

posix_kill — Send a signal to a process

Description

bool posix_kill ( int $pid , int $sig )

Send the signal sig to the process with the process identifier pid .

Parameters

pid

The process identifier.

sig

One of the PCNTL signals constants.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • The kill(2) manual page of the POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.

posix_isatty
posix_mkfifo
POSIX Functions


Create a fifo special file (a named pipe)

posix_kill
posix_mknod
POSIX Functions
PHP Manual

posix_mkfifo

(PHP 4, PHP 5)

posix_mkfifo — Create a fifo special file (a named pipe)

Description

bool posix_mkfifo ( string $pathname , int $mode )

posix_mkfifo() creates a special FIFO file which exists in the file system and acts as a bidirectional communication endpoint for processes.

Parameters

pathname

Path to the FIFO file.

mode

The second parameter mode has to be given in octal notation (e.g. 0644). The permission of the newly created FIFO also depends on the setting of the current umask(). The permissions of the created file are (mode & ~umask).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

posix_kill
posix_mknod
POSIX Functions


Create a special or ordinary file (POSIX.1)

posix_mkfifo
posix_setegid
POSIX Functions
PHP Manual

posix_mknod

(PHP 5 >= 5.1.0)

posix_mknod — Create a special or ordinary file (POSIX.1)

Description

bool posix_mknod ( string $pathname , int $mode [, int $major = 0 [, int $minor = 0 ]] )

Creates a special or ordinary file.

Parameters

pathname

The file to create

mode

This parameter is constructed by a bitwise OR between file type (one of the following constants: POSIX_S_IFREG, POSIX_S_IFCHR, POSIX_S_IFBLK, POSIX_S_IFIFO or POSIX_S_IFSOCK) and permissions.

major

The major device kernel identifier (required to pass when using S_IFCHR or S_IFBLK).

minor

The minor device kernel identifier.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A posix_mknod() example

<?php

$file = '/tmp/tmpfile';  // file name
$type = POSIX_S_IFBLK;   // file type
$permissions = 0777;     // octal
$major = 1;
$minor = 8;              // /dev/random

if (!posix_mknod($file, $type | $permissions, $major, $minor)) {
    die('Error ' . posix_get_last_error() . ': ' . posix_strerror(posix_get_last_error()));
}

?>

See Also

  • posix_mkfifo() - Create a fifo special file (a named pipe)

posix_mkfifo
posix_setegid
POSIX Functions


Set the effective GID of the current process

posix_mknod
posix_seteuid
POSIX Functions
PHP Manual

posix_setegid

(PHP 4 >= 4.0.2, PHP 5)

posix_setegid — Set the effective GID of the current process

Description

bool posix_setegid ( int $gid )

Set the effective group ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function.

Parameters

gid

The group id.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_setegid() example

This example will print out the effective group id, once changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process
  • posix_setgid() - Set the GID of the current process

posix_mknod
posix_seteuid
POSIX Functions


Set the effective UID of the current process

posix_setegid
posix_setgid
POSIX Functions
PHP Manual

posix_seteuid

(PHP 4 >= 4.0.2, PHP 5)

posix_seteuid — Set the effective UID of the current process

Description

bool posix_seteuid ( int $uid )

Set the real user ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function.

Parameters

uid

The user id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • posix_setgid() - Set the GID of the current process

posix_setegid
posix_setgid
POSIX Functions


Set the GID of the current process

posix_seteuid
posix_setpgid
POSIX Functions
PHP Manual

posix_setgid

(PHP 4, PHP 5)

posix_setgid — Set the GID of the current process

Description

bool posix_setgid ( int $gid )

Set the real group ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.

Note: If the caller is a super user, this will also set the effective group id.

Parameters

gid

The group id.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_setgid() example

This example will print out the effective group id, once it is changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setgid(40);
echo 'My real group id is '.posix_getgid(); //40
echo 'My effective group id is '.posix_getegid(); //40
?>

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process

posix_seteuid
posix_setpgid
POSIX Functions


Set process group id for job control

posix_setgid
posix_setsid
POSIX Functions
PHP Manual

posix_setpgid

(PHP 4, PHP 5)

posix_setpgid — Set process group id for job control

Description

bool posix_setpgid ( int $pid , int $pgid )

Let the process pid join the process group pgid .

Parameters

pid

The process id.

pgid

The process group id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • See POSIX.1 and the setsid(2) manual page on the POSIX system for more informations on process groups and job control.

posix_setgid
posix_setsid
POSIX Functions


Make the current process a session leader

posix_setpgid
posix_setuid
POSIX Functions
PHP Manual

posix_setsid

(PHP 4, PHP 5)

posix_setsid — Make the current process a session leader

Description

int posix_setsid ( void )

Make the current process a session leader.

Return Values

Returns the session id, or -1 on errors.

See Also

  • The POSIX.1 and the setsid(2) manual page on the POSIX system for more information on process groups and job control.

posix_setpgid
posix_setuid
POSIX Functions


Set the UID of the current process

posix_setsid
posix_strerror
POSIX Functions
PHP Manual

posix_setuid

(PHP 4, PHP 5)

posix_setuid — Set the UID of the current process

Description

bool posix_setuid ( int $uid )

Set the real user ID of the current process. This is a privileged function that needs appropriate privileges (usually root) on the system to be able to perform this function.

Parameters

uid

The user id.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_setuid() example

This example will show the current user id and then set it to a different value.

<?php
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10001
posix_setuid(10000);
echo posix_getuid()."\n"; //10000
echo posix_geteuid()."\n"; //10000
?>

See Also

  • posix_setgid() - Set the GID of the current process
  • posix_seteuid() - Set the effective UID of the current process
  • posix_getuid() - Return the real user ID of the current process
  • posix_geteuid() - Return the effective user ID of the current process

posix_setsid
posix_strerror
POSIX Functions


Retrieve the system error message associated with the given errno

posix_setuid
posix_times
POSIX Functions
PHP Manual

posix_strerror

(PHP 4 >= 4.2.0, PHP 5)

posix_strerror — Retrieve the system error message associated with the given errno

Description

string posix_strerror ( int $errno )

Returns the POSIX system error message associated with the given errno . You may get the errno parameter by calling posix_get_last_error().

Parameters

errno

A POSIX error number, returned by posix_get_last_error(). If set to 0, then the string "Success" is returned.

Return Values

Returns the error message, as a string.

Examples

Example #1 posix_strerror() example

This example will attempt to kill a process which does not exist, then will print out the corresponding error message.

<?php
posix_kill(50,SIGKILL);
echo posix_strerror(posix_get_last_error())."\n";
?>

The above example will output something similar to:

No such process

See Also

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed

posix_setuid
posix_times
POSIX Functions


Get process times

posix_strerror
posix_ttyname
POSIX Functions
PHP Manual

posix_times

(PHP 4, PHP 5)

posix_times — Get process times

Description

array posix_times ( void )

Gets information about the current CPU usage.

Return Values

Returns a hash of strings with information about the current process CPU usage. The indices of the hash are:

  • ticks - the number of clock ticks that have elapsed since reboot.
  • utime - user time used by the current process.
  • stime - system time used by the current process.
  • cutime - user time used by current process and children.
  • cstime - system time used by current process and children.

Notes

Warning

This function isn't reliable to use, it may return negative values for high times.

Examples

Example #1 Example use of posix_times()

<?php

$times = posix_times();

print_r($times);
?>

The above example will output something similar to:

Array
(
    [ticks] => 25814410
    [utime] => 1
    [stime] => 1
    [cutime] => 0
    [cstime] => 0
)

posix_strerror
posix_ttyname
POSIX Functions


Determine terminal device name

posix_times
posix_uname
POSIX Functions
PHP Manual

posix_ttyname

(PHP 4, PHP 5)

posix_ttyname — Determine terminal device name

Description

string posix_ttyname ( int $fd )

Returns a string for the absolute path to the current terminal device that is open on the file descriptor fd .

Parameters

fd

The file descriptor.

Return Values

On success, returns a string of the absolute path of the fd . On failure, returns FALSE

posix_times
posix_uname
POSIX Functions


Get system name

posix_ttyname
Semaphore
POSIX Functions
PHP Manual

posix_uname

(PHP 4, PHP 5)

posix_uname — Get system name

Description

array posix_uname ( void )

Gets information about the system.

Posix requires that assumptions must not be made about the format of the values, e.g. the assumption that a release may contain three digits or anything else returned by this function.

Return Values

Returns a hash of strings with information about the system. The indices of the hash are

  • sysname - operating system name (e.g. Linux)
  • nodename - system name (e.g. valiant)
  • release - operating system release (e.g. 2.2.10)
  • version - operating system version (e.g. #4 Tue Jul 20 17:01:36 MEST 1999)
  • machine - system architecture (e.g. i586)
  • domainname - DNS domainname (e.g. example.com)

domainname is a GNU extension and not part of POSIX.1, so this field is only available on GNU systems or when using the GNU libc.

Examples

Example #1 Example use of posix_uname()

<?php
$uname=posix_uname();
print_r($uname);
?>

The above example will output something similar to:

Array
(
    [sysname] => Linux
    [nodename] => funbox
    [release] => 2.6.20-15-server
    [version] => #2 SMP Sun Apr 15 07:41:34 UTC 2007
    [machine] => i686
)

posix_ttyname
Semaphore
POSIX Functions


Exponential expression

pi
rad2deg
Math Functions
PHP Manual

pow

(PHP 4, PHP 5)

pow — Exponential expression

Description

number pow ( number $base , number $exp )

Returns base raised to the power of exp .

Warning

In PHP 4.0.6 and earlier pow() always returned a float, and did not issue warnings.

Parameters

base

The base to use

exp

The exponent

Return Values

base raised to the power of exp . If the result can be represented as integer it will be returned as type integer, else it will be returned as type float. If the power cannot be computed FALSE will be returned instead.

Changelog

Version | Description
Since 4.0.6 | The function will now return integer results if possible, before this it always returned a float result. For older versions, you may receive a bogus result for complex numbers.
Since 4.2.0 | PHP stops to emit a warning if the value can't be computed, it will now silently return FALSE only.

Examples

Example #1 Some examples of pow()

<?php

var_dump(pow(2, 8)); // int(256)
echo pow(-1, 20); // 1
echo pow(0, 0); // 1

echo pow(-1, 5.5); // PHP >4.0.6  NAN
echo pow(-1, 5.5); // PHP <=4.0.6 1.#IND
?>

See Also

  • exp() - Calculates the exponent of e
  • sqrt() - Square root
  • bcpow() - Raise an arbitrary precision number to another
  • gmp_pow() - Raise number into power

pi
rad2deg
Math Functions


Close a process opened by proc_open and return the exit code of that process

passthru
proc_get_status
Program execution Functions
PHP Manual

proc_close

(PHP 4 >= 4.3.0, PHP 5)

proc_close — Close a process opened by proc_open() and return the exit code of that process

Description

int proc_close ( resource $process )

proc_close() is similar to pclose() except that it only works on processes opened by proc_open(). proc_close() waits for the process to terminate, and returns its exit code. If you have open pipes to that process, you should fclose() them prior to calling this function in order to avoid a deadlock - the child process may not be able to exit while the pipes are open.

Parameters

process

The proc_open() resource that will be closed.

Return Values

Returns the termination status of the process that was run.

passthru
proc_get_status
Program execution Functions


Get information about a process opened by proc_open

proc_close
proc_nice
Program execution Functions
PHP Manual

proc_get_status

(PHP 5)

proc_get_status — Get information about a process opened by proc_open()

Description

array proc_get_status ( resource $process )

proc_get_status() fetches data about a process opened using proc_open().

Parameters

process

The proc_open() resource that will be evaluated.

Return Values

An array of collected information on success, and FALSE on failure. The returned array contains the following elements:

element | type | description
command | string | The command string that was passed to proc_open().
pid | int | process id
running | bool | TRUE if the process is still running, FALSE if it has terminated.
signaled | bool | TRUE if the child process has been terminated by an uncaught signal. Always set to FALSE on Windows.
stopped | bool | TRUE if the child process has been stopped by a signal. Always set to FALSE on Windows.
exitcode | int | The exit code returned by the process (which is only meaningful if running is FALSE). Only first call of this function return real value, next calls return -1.
termsig | int | The number of the signal that caused the child process to terminate its execution (only meaningful if signaled is TRUE).
stopsig | int | The number of the signal that caused the child process to stop its execution (only meaningful if stopped is TRUE).

See Also

  • proc_open() - Execute a command and open file pointers for input/output

proc_close
proc_nice
Program execution Functions


Change the priority of the current process

proc_get_status
proc_open
Program execution Functions
PHP Manual

proc_nice

(PHP 5)

proc_nice — Change the priority of the current process

Description

bool proc_nice ( int $increment )

proc_nice() changes the priority of the current process by the amount specified in increment . A positive increment will lower the priority of the current process, whereas a negative increment will raise the priority.

proc_nice() is not related to proc_open() and its associated functions in any way.

Parameters

increment

The increment value of the priority change.

Return Values

Returns TRUE on success or FALSE on failure. If an error occurs, like the user lacks permission to change the priority, an error of level E_WARNING is also generated.

Notes

Note: Availability
proc_nice() will only exist if your system has 'nice' capabilities. 'nice' conforms to: SVr4, SVID EXT, AT&T, X/OPEN, BSD 4.3. This means that proc_nice() is not available on Windows.

proc_get_status
proc_open
Program execution Functions


Execute a command and open file pointers for input/output

proc_nice
proc_terminate
Program execution Functions
PHP Manual

proc_open

(PHP 4 >= 4.3.0, PHP 5)

proc_open — Execute a command and open file pointers for input/output

Description

resource proc_open ( string $cmd , array $descriptorspec , array &$pipes [, string $cwd [, array $env [, array $other_options ]]] )

proc_open() is similar to popen() but provides a much greater degree of control over the program execution.

Parameters

cmd

The command to execute

descriptorspec

An indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. 0 is stdin, 1 is stdout, while 2 is stderr.

Each element can be:

  • An array describing the pipe to pass to the process. The first element is the descriptor type and the second element is an option for the given type. Valid types are pipe (the second element is either r to pass the read end of the pipe to the process, or w to pass the write end) and file (the second element is a filename).
  • A stream resource representing a real file descriptor (e.g. opened file, a socket, STDIN).

The file descriptor numbers are not limited to 0, 1 and 2 - you may specify any valid file descriptor number and it will be passed to the child process. This allows your script to interoperate with other scripts that run as "co-processes". In particular, this is useful for passing passphrases to programs like PGP, GPG and openssl in a more secure manner. It is also useful for reading status information provided by those programs on auxiliary file descriptors.

pipes

Will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created.

cwd

The initial working dir for the command. This must be an absolute directory path, or NULL if you want to use the default value (the working dir of the current PHP process)

env

An array with the environment variables for the command that will be run, or NULL to use the same environment as the current PHP process

other_options

Allows you to specify additional options. Currently supported options include:

  • suppress_errors (windows only): suppresses errors generated by this function when it's set to TRUE
  • bypass_shell (windows only): bypass cmd.exe shell when set to TRUE
  • context: stream context used when opening files (created with stream_context_create())
  • binary_pipes: open pipes in binary mode, instead of using the usual stream_encoding

Return Values

Returns a resource representing the process, which should be freed using proc_close() when you are finished with it. On failure returns FALSE.

Changelog

Version | Description
6.0.0 | Added the context and binary_pipes options to the other_options parameter.
5.2.1 | Added the bypass_shell option to the other_options parameter.
5.0.0 | Added the cwd , env and other_options parameters.

Examples

Example #1 A proc_open() example

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);

$cwd = '/tmp';
$env = array('some_option' => 'aeiou');

$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], '<?php print_r($_ENV); ?>');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}
?>

The above example will output something similar to:

Array
(
    [some_option] => aeiou
    [PWD] => /tmp
    [SHLVL] => 1
    [_] => /usr/local/bin/php
)
command returned 0

Notes

Note: Windows compatibility: Descriptors beyond 2 (stderr) are made available to the child process as inheritable handles, but since the Windows architecture does not associate file descriptor numbers with low-level handles, the child process does not (yet) have a means of accessing those handles. Stdin, stdout and stderr work as expected.

Note: If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much easier to use.

See Also

  • popen() - Opens process file pointer
  • exec() - Execute an external program
  • system() - Execute an external program and display the output
  • passthru() - Execute an external program and display raw output
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • The backtick operator

proc_nice
proc_terminate
Program execution Functions


Kills a process opened by proc_open

proc_open
shell_exec
Program execution Functions
PHP Manual

proc_terminate

(PHP 5)

proc_terminate — Kills a process opened by proc_open

Description

bool proc_terminate ( resource $process [, int $signal = 15 ] )

Signals a process (created using proc_open()) that it should terminate. proc_terminate() returns immediately and does not wait for the process to terminate.

proc_terminate() allows you terminate the process and continue with other tasks. You may poll the process (to see if it has stopped yet) by using the proc_get_status() function.

Parameters

process

The proc_open() resource that will be closed.

signal

This optional parameter is only useful on POSIX operating systems; you may specify a signal to send to the process using the kill(2) system call. The default is SIGTERM.

Return Values

Returns the termination status of the process that was run.

Changelog

Version | Description
5.2.2 | Previous versions used to destroy the given process resource .

See Also

  • proc_open() - Execute a command and open file pointers for input/output
  • proc_close() - Close a process opened by proc_open and return the exit code of that process
  • proc_get_status() - Get information about a process opened by proc_open

proc_open
shell_exec
Program execution Functions


Add bookmark to current page

PS Functions
ps_add_launchlink
PS Functions
PHP Manual

ps_add_bookmark

(PECL ps >= 1.1.0)

ps_add_bookmark — Add bookmark to current page

Description

int ps_add_bookmark ( resource $psdoc , string $text [, int $parent = 0 [, int $open = 0 ]] )

Adds a bookmark for the current page. Bookmarks usually appear in PDF-Viewers left of the page in a hierarchical tree. Clicking on a bookmark will jump to the given page.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text used for displaying the bookmark.

parent

A bookmark previously created by this function which is used as the parent of the new bookmark.

open

If open is unequal to zero the bookmark will be shown open by the pdf viewer.

Return Values

The returned value is a reference for the bookmark. It is only used if the bookmark shall be used as a parent. The value is greater zero if the function succeeds. In case of an error zero will be returned.

See Also

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

PS Functions
ps_add_launchlink
PS Functions


Adds link which launches file

ps_add_bookmark
ps_add_locallink
PS Functions
PHP Manual

ps_add_launchlink

(PECL ps >= 1.1.0)

ps_add_launchlink — Adds link which launches file

Description

bool ps_add_launchlink ( resource $psdoc , float $llx , float $lly , float $urx , float $ury , string $filename )

Places a hyperlink at the given position pointing to a file program which is being started when clicked on. The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

filename

The path of the program to be started, when the link is clicked on.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

ps_add_bookmark
ps_add_locallink
PS Functions


Adds link to a page in the same document

ps_add_launchlink
ps_add_note
PS Functions
PHP Manual

ps_add_locallink

(PECL ps >= 1.1.0)

ps_add_locallink — Adds link to a page in the same document

Description

bool ps_add_locallink ( resource $psdoc , float $llx , float $lly , float $urx , float $ury , int $page , string $dest )

Places a hyperlink at the given position pointing to a page in the same document. Clicking on the link will jump to the given page. The first page in a document has number 1.

The hyperlink's source position is a rectangle with its lower left corner at (llx , lly ) and its upper right corner at (urx , ury ). The rectangle has by default a thin blue border.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

page

The number of the page displayed when clicking on the link.

dest

The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

ps_add_launchlink
ps_add_note
PS Functions


Adds note to current page

ps_add_locallink
ps_add_pdflink
PS Functions
PHP Manual

ps_add_note

(PECL ps >= 1.1.0)

ps_add_note — Adds note to current page

Description

bool ps_add_note ( resource $psdoc , float $llx , float $lly , float $urx , float $ury , string $contents , string $title , string $icon , int $open )

Adds a note at a certain position on the page. Notes are like little rectangular sheets with text on it, which can be placed anywhere on a page. They are shown either folded or unfolded. If unfolded, the specified icon is used as a placeholder.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

contents

The text of the note.

title

The title of the note as displayed in the header of the note.

icon

The icon shown if the note is folded. This parameter can be set to comment, insert, note, paragraph, newparagraph, key, or help.

open

If open is unequal to zero the note will be shown unfolded after opening the document with a pdf viewer.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_launchlink() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_weblink() - Adds link to a web location

ps_add_locallink
ps_add_pdflink
PS Functions


Adds link to a page in a second pdf document

ps_add_note
ps_add_weblink
PS Functions
PHP Manual

ps_add_pdflink

(PECL ps >= 1.1.0)

ps_add_pdflink — Adds link to a page in a second pdf document

Description

bool ps_add_pdflink ( resource $psdoc , float $llx , float $lly , float $urx , float $ury , string $filename , int $page , string $dest )

Places a hyperlink at the given position pointing to a second pdf document. Clicking on the link will branch to the document at the given page. The first page in a document has number 1.

The hyperlink's source position is a rectangle with its lower left corner at (llx , lly ) and its upper right corner at (urx , ury ). The rectangle has by default a thin blue border.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

filename

The name of the pdf document to be opened when clicking on this link.

page

The page number of the destination pdf document

dest

The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_weblink() - Adds link to a web location

ps_add_note
ps_add_weblink
PS Functions


Adds link to a web location

ps_add_pdflink
ps_arc
PS Functions
PHP Manual

ps_add_weblink

(PECL ps >= 1.1.0)

ps_add_weblink — Adds link to a web location

Description

bool ps_add_weblink ( resource $psdoc , float $llx , float $lly , float $urx , float $ury , string $url )

Places a hyperlink at the given position pointing to a web page. The hyperlink's source position is a rectangle with its lower left corner at (llx , lly ) and its upper right corner at (urx , ury ). The rectangle has by default a thin blue border.

The note will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

url

The url of the hyperlink to be opened when clicking on this link, e.g. http://www.php.net.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_pdflink() - Adds link to a page in a second pdf document

ps_add_pdflink
ps_arc
PS Functions


Draws an arc counterclockwise

ps_add_weblink
ps_arcn
PS Functions
PHP Manual

ps_arc

(PECL ps >= 1.1.0)

ps_arc — Draws an arc counterclockwise

Description

bool ps_arc ( resource $psdoc , float $x , float $y , float $radius , float $alpha , float $beta )

Draws a portion of a circle with at middle point at (x , y ). The arc starts at an angle of alpha and ends at an angle of beta . It is drawn counterclockwise (use ps_arcn() to draw clockwise). The subpath added to the current path starts on the arc at angle alpha and ends on the arc at angle beta .

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

alpha

The start angle given in degrees.

beta

The end angle given in degrees.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_arcn() - Draws an arc clockwise

ps_add_weblink
ps_arcn
PS Functions


Draws an arc clockwise

ps_arc
ps_begin_page
PS Functions
PHP Manual

ps_arcn

(PECL ps >= 1.1.0)

ps_arcn — Draws an arc clockwise

Description

bool ps_arcn ( resource $psdoc , float $x , float $y , float $radius , float $alpha , float $beta )

Draws a portion of a circle with at middle point at (x , y ). The arc starts at an angle of alpha and ends at an angle of beta . It is drawn clockwise (use ps_arc() to draw counterclockwise). The subpath added to the current path starts on the arc at angle beta and ends on the arc at angle alpha .

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

alpha

The starting angle given in degrees.

beta

The end angle given in degrees.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_arc() - Draws an arc counterclockwise

ps_arc
ps_begin_page
PS Functions


Start a new page

ps_arcn
ps_begin_pattern
PS Functions
PHP Manual

ps_begin_page

(PECL ps >= 1.1.0)

ps_begin_page — Start a new page

Description

bool ps_begin_page ( resource $psdoc , float $width , float $height )

Starts a new page. Although the parameters width and height imply a different page size for each page, this is not possible in PostScript. The first call of ps_begin_page() will set the page size for the whole document. Consecutive calls will have no effect, except for creating a new page. The situation is different if you intent to convert the PostScript document into PDF. This function places pdfmarks into the document which can set the size for each page indiviually. The resulting PDF document will have different page sizes.

Though PostScript does not know different page sizes, pslib places a bounding box for each page into the document. This size is evaluated by some PostScript viewers and will have precedence over the BoundingBox in the Header of the document. This can lead to unexpected results when you set a BoundingBox whose lower left corner is not (0, 0), because the bounding box of the page will always have a lower left corner (0, 0) and overwrites the global setting.

Each page is encapsulated into save/restore. This means, that most of the settings made on one page will not be retained on the next page.

If there is up to the first call of ps_begin_page() no call of ps_findfont(), then the header of the PostScript document will be output and the bounding box will be set to the size of the first page. The lower left corner of the bounding box is set to (0, 0). If ps_findfont() was called before, then the header has been output already, and the document will not have a valid bounding box. In order to prevent this, one should call ps_set_info() to set the info field BoundingBox and possibly Orientation before any ps_findfont() or ps_begin_page() calls.

Note: Up to version 0.2.6 of pslib, this function will always overwrite the BoundingBox and Orientation, if it has been set before with ps_set_info() and ps_findfont() has not been called before.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the page in pixel, e.g. 596 for A4 format.

height

The height of the page in pixel, e.g. 842 for A4 format.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_end_page() - End a page
  • ps_findfont() - Loads a font
  • ps_set_info() - Sets information fields of document

ps_arcn
ps_begin_pattern
PS Functions


Start a new pattern

ps_begin_page
ps_begin_template
PS Functions
PHP Manual

ps_begin_pattern

(PECL ps >= 1.2.0)

ps_begin_pattern — Start a new pattern

Description

int ps_begin_pattern ( resource $psdoc , float $width , float $height , float $xstep , float $ystep , int $painttype )

Starts a new pattern. A pattern is like a page containing e.g. a drawing which can be used for filling areas. It is used like a color by calling ps_setcolor() and setting the color space to pattern.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the pattern in pixel.

height

The height of the pattern in pixel.

x-step

The distance in pixel of placements of the pattern in horizontal direction.

y-step

The distance in pixel of placements of the pattern in vertical direction.

painttype

Must be 1 or 2.

Return Values

The identifier of the pattern or FALSE on failure.

Examples

Example #1 Creating and using a pattern

<?php
$ps = ps_new();

if (!ps_open_file($ps, "pattern.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "pattern.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Pattern example");

$pspattern = ps_begin_pattern($ps, 10.0, 10.0, 10.0, 10.0, 1);
ps_setlinewidth($ps, 0.2);
ps_setcolor($ps, "stroke", "rgb", 0.0, 0.0, 1.0, 0.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 7, 7);
ps_stroke($ps);
ps_moveto($ps, 0, 7);
ps_lineto($ps, 7, 0);
ps_stroke($ps);
ps_end_pattern($ps);

ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "both", "pattern", $pspattern, 0.0, 0.0, 0.0);
ps_rect($ps, 50, 400, 200, 200);
ps_fill($ps);
ps_end_page($ps);

ps_close($ps);
ps_delete($ps);
?>

See Also

  • ps_end_pattern() - End a pattern
  • ps_setcolor() - Sets current color
  • ps_shading_pattern() - Creates a pattern based on a shading

ps_begin_page
ps_begin_template
PS Functions


Start a new template

ps_begin_pattern
ps_circle
PS Functions
PHP Manual

ps_begin_template

(PECL ps >= 1.2.0)

ps_begin_template — Start a new template

Description

int ps_begin_template ( resource $psdoc , float $width , float $height )

Starts a new template. A template is called a form in the postscript language. It is created similar to a pattern but used like an image. Templates are often used for drawings which are placed several times through out the document, e.g. like a company logo. All drawing functions may be used within a template. The template will not be drawn until it is placed by ps_place_image().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the template in pixel.

height

The height of the template in pixel.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Creating and using a template

<?php
$ps = ps_new();

if (!ps_open_file($ps, "template.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "template.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Template example");

$pstemplate = ps_begin_template($ps, 30.0, 30.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 30, 30);
ps_moveto($ps, 0, 30);
ps_lineto($ps, 30, 0);
ps_stroke($ps);
ps_end_template($ps);

ps_begin_page($ps, 596, 842);
ps_place_image($ps, $pstemplate, 20.0, 20.0, 1.0);
ps_place_image($ps, $pstemplate, 50.0, 30.0, 0.5);
ps_place_image($ps, $pstemplate, 70.0, 70.0, 0.6);
ps_place_image($ps, $pstemplate, 30.0, 50.0, 1.3);
ps_end_page($ps);

ps_close($ps);
ps_delete($ps);
?>

See Also

  • ps_end_template() - End a template

ps_begin_pattern
ps_circle
PS Functions


Draws a circle

ps_begin_template
ps_clip
PS Functions
PHP Manual

ps_circle

(PECL ps >= 1.1.0)

ps_circle — Draws a circle

Description

bool ps_circle ( resource $psdoc , float $x , float $y , float $radius )

Draws a circle with its middle point at (x , y ). The circle starts and ends at position (x +radius , y ). If this function is called outside a path it will start a new path. If it is called within a path it will add the circle as a subpath. If the last drawing operation does not end in point (x +radius , y ) then there will be a gap in the path.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_arc() - Draws an arc counterclockwise
  • ps_arcn() - Draws an arc clockwise

ps_begin_template
ps_clip
PS Functions


Clips drawing to current path

ps_circle
ps_close_image
PS Functions
PHP Manual

ps_clip

(PECL ps >= 1.1.0)

ps_clip — Clips drawing to current path

Description

bool ps_clip ( resource $psdoc )

Takes the current path and uses it to define the border of a clipping area. Everything drawn outside of that area will not be visible.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_closepath() - Closes path

ps_circle
ps_close_image
PS Functions


Closes a PostScript document

ps_close_image
ps_closepath_stroke
PS Functions
PHP Manual

ps_close

(PECL ps >= 1.1.0)

ps_close — Closes a PostScript document

Description

bool ps_close ( resource $psdoc )

Closes the PostScript document.

This function writes the trailer of the PostScript document. It also writes the bookmark tree. ps_close() does not free any resources, which is done by ps_delete().

This function is also called by ps_delete() if it has not been called before.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_open_file() - Opens a file for output
  • ps_delete() - Deletes all resources of a PostScript document

ps_close_image
ps_closepath_stroke
PS Functions


Closes image and frees memory

ps_clip
ps_close
PS Functions
PHP Manual

ps_close_image

(PECL ps >= 1.1.0)

ps_close_image — Closes image and frees memory

Description

void ps_close_image ( resource $psdoc , int $imageid )

Closes an image and frees its resources. Once an image is closed it cannot be used anymore.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

imageid

Resource identifier of the image as returned by ps_open_image() or ps_open_image_file().

Return Values

Returns NULL on success or FALSE on failure.

See Also

  • ps_open_image() - Reads an image for later placement
  • ps_open_image_file() - Opens image from file

ps_clip
ps_close
PS Functions


Closes path

ps_closepath_stroke
ps_continue_text
PS Functions
PHP Manual

ps_closepath

(PECL ps >= 1.1.0)

ps_closepath — Closes path

Description

bool ps_closepath ( resource $psdoc )

Connects the last point with the first point of a path. The resulting path can be used for stroking, filling, clipping, etc..

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_clip() - Clips drawing to current path
  • ps_closepath_stroke() - Closes and strokes path

ps_closepath_stroke
ps_continue_text
PS Functions


Closes and strokes path

ps_close
ps_closepath
PS Functions
PHP Manual

ps_closepath_stroke

(PECL ps >= 1.1.0)

ps_closepath_stroke — Closes and strokes path

Description

bool ps_closepath_stroke ( resource $psdoc )

Connects the last point with first point of a path and draws the resulting closed line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_closepath() - Closes path

ps_close
ps_closepath
PS Functions


Continue text in next line

ps_closepath
ps_curveto
PS Functions
PHP Manual

ps_continue_text

(PECL ps >= 1.1.0)

ps_continue_text — Continue text in next line

Description

bool ps_continue_text ( resource $psdoc , string $text )

Output a text one line below the last line. The line spacing is taken from the value "leading" which must be set with ps_set_value(). The actual position of the text is determined by the values "textx" and "texty" which can be requested with ps_get_value()

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to output.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_show() - Output text
  • ps_show_xy() - Output text at given position
  • ps_show_boxed() - Output text in a box

ps_closepath
ps_curveto
PS Functions


Draws a curve

ps_continue_text
ps_delete
PS Functions
PHP Manual

ps_curveto

(PECL ps >= 1.1.0)

ps_curveto — Draws a curve

Description

bool ps_curveto ( resource $psdoc , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Add a section of a cubic Bézier curve described by the three given control points to the current path.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x1

x-coordinate of first control point.

y1

y-coordinate of first control point.

x2

x-coordinate of second control point.

y2

y-coordinate of second control point.

x3

x-coordinate of third control point.

y3

y-coordinate of third control point.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_lineto() - Draws a line

ps_continue_text
ps_delete
PS Functions


Deletes all resources of a PostScript document

ps_curveto
ps_end_page
PS Functions
PHP Manual

ps_delete

(PECL ps >= 1.1.0)

ps_delete — Deletes all resources of a PostScript document

Description

bool ps_delete ( resource $psdoc )

Mainly frees memory used by the document. Also closes a file, if it was not closed before with ps_close(). You should in any case close the file with ps_close() before, because ps_close() not just closes the file but also outputs a trailor containing PostScript comments like the number of pages in the document and adding the bookmark hierarchy.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_close() - Closes a PostScript document

ps_curveto
ps_end_page
PS Functions


End a page

ps_delete
ps_end_pattern
PS Functions
PHP Manual

ps_end_page

(PECL ps >= 1.1.0)

ps_end_page — End a page

Description

bool ps_end_page ( resource $psdoc )

Ends a page which was started with ps_begin_page(). Ending a page will leave the current drawing context, which e.g. requires to reload fonts if they were loading within the page, and to set many other drawing parameters like the line width, or color..

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_begin_page() - Start a new page

ps_delete
ps_end_pattern
PS Functions


End a pattern

ps_end_page
ps_end_template
PS Functions
PHP Manual

ps_end_pattern

(PECL ps >= 1.2.0)

ps_end_pattern — End a pattern

Description

bool ps_end_pattern ( resource $psdoc )

Ends a pattern which was started with ps_begin_pattern(). Once a pattern has been ended, it can be used like a color to fill areas.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_begin_pattern() - Start a new pattern

ps_end_page
ps_end_template
PS Functions


End a template

ps_end_pattern
ps_fill_stroke
PS Functions
PHP Manual

ps_end_template

(PECL ps >= 1.2.0)

ps_end_template — End a template

Description

bool ps_end_template ( resource $psdoc )

Ends a template which was started with ps_begin_template(). Once a template has been ended, it can be used like an image.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_begin_template() - Start a new template

ps_end_pattern
ps_fill_stroke
PS Functions


Fills the current path

ps_fill_stroke
ps_findfont
PS Functions
PHP Manual

ps_fill

(PECL ps >= 1.1.0)

ps_fill — Fills the current path

Description

bool ps_fill ( resource $psdoc )

Fills the path constructed with previously called drawing functions like ps_lineto().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_fill_stroke() - Fills and strokes the current path
  • ps_stroke() - Draws the current path

ps_fill_stroke
ps_findfont
PS Functions


Fills and strokes the current path

ps_end_template
ps_fill
PS Functions
PHP Manual

ps_fill_stroke

(PECL ps >= 1.1.0)

ps_fill_stroke — Fills and strokes the current path

Description

bool ps_fill_stroke ( resource $psdoc )

Fills and draws the path constructed with previously called drawing functions like ps_lineto().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_fill() - Fills the current path
  • ps_stroke() - Draws the current path

ps_end_template
ps_fill
PS Functions


Loads a font

ps_fill
ps_get_buffer
PS Functions
PHP Manual

ps_findfont

(PECL ps >= 1.1.0)

ps_findfont — Loads a font

Description

int ps_findfont ( resource $psdoc , string $fontname , string $encoding [, bool $embed = false ] )

Loads a font for later use. Before text is output with a loaded font it must be set with ps_setfont(). This function needs the adobe font metric file in order to calculate the space used up by the characters. A font which is loaded within a page will only be available on that page. Fonts which are to be used in the complete document have to be loaded before the first call of ps_begin_page(). Calling ps_findfont() between pages will make that font available for all following pages.

The name of the afm file must be fontname .afm. If the font shall be embedded the file fontname .pfb containing the font outline must be present as well.

Calling ps_findfont() before the first page requires to output the postscript header which includes the BoundingBox for the whole document. Usually the BoundingBox is set with the first call of ps_begin_page() which now comes after ps_findfont(). Consequently the BoundingBox has not been set and a warning will be issued when ps_findfont() is called. In order to prevent this situation, one should call ps_set_parameter() to set the BoundingBox before ps_findfont() is called.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

fontname

The name of the font.

encoding

ps_findfont() will try to load the file passed in the parameter encoding . Encoding files are of the same syntax as those used by dvips(1). They contain a font encoding vector (which is currently not used but must be present) and a list of extra ligatures to extend the list of ligatures derived from the afm file.

encoding can be NULL or the empty string if the default encoding (TeXBase1) shall be used.

If the encoding is set to builtin then there will be no reencoding and the font specific encoding will be used. This is very useful with symbol fonts.

embed

If set to a value >0 the font will be embedded into the document. This requires the font outline (.pfb file) to be present.

Return Values

Returns the identifier of the font or zero in case of an error. The identifier is a positive number.

See Also

  • ps_begin_page() - Start a new page
  • ps_setfont() - Sets font to use for following output

ps_fill
ps_get_buffer
PS Functions


Fetches the full buffer containig the generated PS data

ps_findfont
ps_get_parameter
PS Functions
PHP Manual

ps_get_buffer

(PECL ps >= 1.1.0)

ps_get_buffer — Fetches the full buffer containig the generated PS data

Description

string ps_get_buffer ( resource $psdoc )

This function is not implemented yet. It will always return an empty string. The idea for a later implementation is to write the contents of the postscript file into an internal buffer if in memory creation is requested, and retrieve the buffer content with this function. Currently, documents created in memory are send to the browser without buffering.

Warning

This function is currently not documented; only its argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

See Also

  • ps_open_file() - Opens a file for output

ps_findfont
ps_get_parameter
PS Functions


Gets certain parameters

ps_get_buffer
ps_get_value
PS Functions
PHP Manual

ps_get_parameter

(PECL ps >= 1.1.0)

ps_get_parameter — Gets certain parameters

Description

string ps_get_parameter ( resource $psdoc , string $name [, float $modifier ] )

Gets several parameters which were directly set by ps_set_parameter() or indirectly by one of the other functions. Parameters are by definition string values. This function cannot be used to retrieve resources which were also set by ps_set_parameter().

The parameter name can have the following values.

fontname

The name of the currently active font or the font whose identifier is passed in parameter modifier .

fontencoding

The encoding of the currently active font.

dottedversion

The version of the underlying pslib library in the format <major>.<minor>.<subminor>

scope

The current drawing scope. Can be object, document, null, page, pattern, path, template, prolog, font, glyph.

ligaturedisolvechar

The character which dissolves a ligature. If your are using a font which contains the ligature `ff' and `|' is the char to dissolve the ligature, then `f|f' will result in two `f' instead of the ligature `ff'.

imageencoding

The encoding used for encoding images. Can be either hex or 85. hex encoding uses two bytes in the postscript file each byte in the image. 85 stand for Ascii85 encoding.

linenumbermode

Set to paragraph if lines are numbered within a paragraph or box if they are numbered within the surrounding box.

linebreak

Only used if text is output with ps_show_boxed(). If set to true a carriage return will add a line break.

parbreak

Only used if text is output with ps_show_boxed(). If set to true a carriage return will start a new paragraph.

hyphenation

Only used if text is output with ps_show_boxed(). If set to true the paragraph will be hyphenated if a hypen dictionary is set and exists.

hyphendict

Filename of the dictionary used for hyphenation pattern.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the parameter.

modifier

An identifier needed if a parameter of a resource is requested, e.g. the size of an image. In such a case the resource id is passed.

Return Values

Returns the value of the parameter or FALSE on failure.

See Also

  • ps_set_parameter() - Sets certain parameters

ps_get_buffer
ps_get_value
PS Functions


Gets certain values

ps_get_parameter
ps_hyphenate
PS Functions
PHP Manual

ps_get_value

(PECL ps >= 1.1.0)

ps_get_value — Gets certain values

Description

float ps_get_value ( resource $psdoc , string $name [, float $modifier ] )

Gets several values which were set by ps_set_value(). Values are by definition float values.

The parameter name can have the following values.

fontsize

The size of the currently active font or the font whose identifier is passed in parameter modifier .

font

The currently active font itself.

imagewidth

The width of the image whose id is passed in the parameter modifier .

imageheight

The height of the image whose id is passed in the parameter modifier .

capheight

The height of a capital M in the currently active font or the font whose identifier is passed in parameter modifier .

ascender

The ascender of the currently active font or the font whose identifier is passed in parameter modifier .

descender

The descender of the currently active font or the font whose identifier is passed in parameter modifier .

italicangle

The italicangle of the currently active font or the font whose identifier is passed in parameter modifier .

underlineposition

The underlineposition of the currently active font or the font whose identifier is passed in parameter modifier .

underlinethickness

The underlinethickness of the currently active font or the font whose identifier is passed in parameter modifier .

textx

The current x-position for text output.

texty

The current y-position for text output.

textrendering

The current mode for text rendering.

textrise

The space by which text is risen above the base line.

leading

The distance between text lines in points.

wordspacing

The space between words as a multiple of the width of a space char.

charspacing

The space between chars. If charspacing is != 0.0 ligatures will always be dissolved.

hyphenminchars

Minimum number of chars hyphenated at the end of a word.

parindent

Indention of the first n line in a paragraph.

numindentlines

Number of line in a paragraph to indent if parindent != 0.0.

parskip

Distance between paragraphs.

linenumberspace

Overall space in front of each line for the line number.

linenumbersep

Space between the line and the line number.

major

The major version number of pslib.

minor

The minor version number of pslib.

subminor, revision

The subminor version number of pslib.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the value.

modifier

The parameter modifier specifies the resource for which the value is to be retrieved. This can be the id of a font or an image.

Return Values

Returns the value of the parameter or FALSE.

See Also

  • ps_set_value() - Sets certain values

ps_get_parameter
ps_hyphenate
PS Functions


Hyphenates a word

ps_get_value
ps_include_file
PS Functions
PHP Manual

ps_hyphenate

(PECL ps >= 1.1.1)

ps_hyphenate — Hyphenates a word

Description

array ps_hyphenate ( resource $psdoc , string $text )

Hyphenates the passed word. ps_hyphenate() evaluates the value hyphenminchars (set by ps_set_value()) and the parameter hyphendict (set by ps_set_parameter()). hyphendict must be set before calling this function.

This function requires the locale category LC_CTYPE to be set properly. This is done when the extension is initialized by using the environment variables. On Unix systems read the man page of locale for more information.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

text should not contain any non alpha characters. Possible positions for breaks are returned in an array of interger numbers. Each number is the position of the char in text after which a hyphenation can take place.

Return Values

An array of integers indicating the position of possible breaks in the text or FALSE on failure.

Examples

Example #1 Hyphennate a text

<?php
$word = "Koordinatensystem";
$psdoc = ps_new();
ps_set_parameter($psdoc, "hyphendict", "hyph_de.dic");
$hyphens = ps_hyphenate($psdoc, $word);
for($i=0; $i<strlen($word); $i++) {
  echo $word[$i];
  if(in_array($i, $hyphens))
    echo "-";
}
ps_delete($psdoc);
?>

The above example will output:

Ko-ordi-na-ten-sys-tem

See Also

  • ps_show_boxed() - Output text in a box
  • locale(1)

ps_get_value
ps_include_file
PS Functions


Reads an external file with raw PostScript code

ps_hyphenate
ps_lineto
PS Functions
PHP Manual

ps_include_file

(PECL ps >= 1.3.4)

ps_include_file — Reads an external file with raw PostScript code

Description

bool ps_include_file ( resource $psdoc , string $file )

Warning

This function is currently not documented; only its argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

file

Return Values

Returns TRUE on success or FALSE on failure.

ps_hyphenate
ps_lineto
PS Functions


Draws a line

ps_include_file
ps_makespotcolor
PS Functions
PHP Manual

ps_lineto

(PECL ps >= 1.1.0)

ps_lineto — Draws a line

Description

bool ps_lineto ( resource $psdoc , float $x , float $y )

Adds a straight line from the current point to the given coordinates to the current path. Use ps_moveto() to set the starting point of the line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the end point of the line.

y

y-coordinate of the end point of the line.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Drawing a rectangle

<?php
$ps = ps_new();
if (!ps_open_file($ps, "rectangle.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "rectangle.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Lineto example");

ps_begin_page($ps, 596, 842);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_stroke($ps);
ps_end_page($ps);

ps_delete($ps);
?>

See Also

  • ps_moveto() - Sets current point

ps_include_file
ps_makespotcolor
PS Functions


Create spot color

ps_lineto
ps_moveto
PS Functions
PHP Manual

ps_makespotcolor

(PECL ps >= 1.1.0)

ps_makespotcolor — Create spot color

Description

int ps_makespotcolor ( resource $psdoc , string $name [, int $reserved = 0 ] )

Creates a spot color from the current fill color. The fill color must be defined in rgb, cmyk or gray colorspace. The spot color name can be an arbitrary name. A spot color can be set as any color with ps_setcolor(). When the document is not printed but displayed by an postscript viewer the given color in the specified color space is use.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the spot color, e.g. Pantone 5565.

Return Values

The id of the new spot color or 0 in case of an error.

Examples

Example #1 Creating and using a spot color

<?php
$ps = ps_new();
if (!ps_open_file($ps, "spotcolor.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "spotcolor.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Spot color example");

ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "fill", "cmyk", 0.37, 0.0, 0.34, 0.34);
$spotcolor = ps_makespotcolor($ps, "PANTONE 5565 C", 0);
ps_setcolor($ps, "fill", "spot", $spotcolor, 0.5, 0.0, 0.0);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_fill($ps);
ps_end_page($ps);

ps_delete($ps);
?>

This example creates the spot color "PANTONE 5565 C" which is a darker green (olive) and fills a rectangle with 50% intensity.

See Also

  • ps_setcolor() - Sets current color

ps_lineto
ps_moveto
PS Functions


Sets current point

ps_makespotcolor
ps_new
PS Functions
PHP Manual

ps_moveto

(PECL ps >= 1.1.0)

ps_moveto — Sets current point

Description

bool ps_moveto ( resource $psdoc , float $x , float $y )

Sets the current point to new coordinates. If this is the first call of ps_moveto() after a previous path has been ended then it will start a new path. If this function is called in the middle of a path it will just set the current point and start a subpath.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the point to move to.

y

y-coordinate of the point to move to.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_lineto() - Draws a line

ps_makespotcolor
ps_new
PS Functions


Creates a new PostScript document object

ps_moveto
ps_open_file
PS Functions
PHP Manual

ps_new

(PECL ps >= 1.1.0)

ps_new — Creates a new PostScript document object

Description

resource ps_new ( void )

Creates a new document instance. It does not create the file on disk or in memory, it just sets up everything. ps_new() is usually followed by a call of ps_open_file() to actually create the postscript document.

Return Values

Resource of PostScript document or FALSE on failure. The return value is passed to all other functions as the first argument.

See Also

  • ps_delete() - Deletes all resources of a PostScript document

ps_moveto
ps_open_file
PS Functions


Opens a file for output

ps_new
ps_open_image_file
PS Functions
PHP Manual

ps_open_file

(PECL ps >= 1.1.0)

ps_open_file — Opens a file for output

Description

bool ps_open_file ( resource $psdoc [, string $filename ] )

Creates a new file on disk and writes the PostScript document into it. The file will be closed when ps_close() is called.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

filename

The name of the postscript file. If filename is not passed the document will be created in memory and all output will go straight to the browser.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_close() - Closes a PostScript document

ps_new
ps_open_image_file
PS Functions


Reads an image for later placement

ps_open_image_file
ps_open_memory_image
PS Functions
PHP Manual

ps_open_image

(PECL ps >= 1.1.0)

ps_open_image — Reads an image for later placement

Description

int ps_open_image ( resource $psdoc , string $type , string $source , string $data , int $lenght , int $width , int $height , int $components , int $bpc , string $params )

Reads an image which is already available in memory. The parameter source is currently not evaluated and assumed to be memory. The image data is a sequence of pixels starting in th upper left corner and ending in the lower right corner. Each pixel consists of components color components, and each component has bpc bits.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of the image. Possible values are png, jpeg, or eps.

source

Not used.

data

The image data.

length

The length of the image data.

width

The width of the image.

height

The height of the image.

components

The number of components for each pixel. This can be 1 (gray scale images), 3 (rgb images), or 4 (cmyk, rgba images).

bpc

Number of bits per component (quite often 8).

params

Return Values

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

See Also

  • ps_open_image_file() - Opens image from file
  • ps_place_image() - Places image on the page
  • ps_close_image() - Closes image and frees memory

ps_open_image_file
ps_open_memory_image
PS Functions


Opens image from file

ps_open_file
ps_open_image
PS Functions
PHP Manual

ps_open_image_file

(PECL ps >= 1.1.0)

ps_open_image_file — Opens image from file

Description

int ps_open_image_file ( resource $psdoc , string $type , string $filename [, string $stringparam [, int $intparam = 0 ]] )

Loads an image for later use.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of the image. Possible values are png, jpeg, or eps.

filename

The name of the file containing the image data.

stringparam

Not used.

intparam

Not used.

Return Values

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

See Also

  • ps_open_image() - Reads an image for later placement
  • ps_place_image() - Places image on the page
  • ps_close_image() - Closes image and frees memory

ps_open_file
ps_open_image
PS Functions


Takes an GD image and returns an image for placement in a PS document

ps_open_image
ps_place_image
PS Functions
PHP Manual

ps_open_memory_image

(PECL ps >= 1.1.0)

ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document

Description

int ps_open_memory_image ( resource $psdoc , int $gd )

Warning

This function is currently not documented; only its argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

gd

ps_open_image
ps_place_image
PS Functions


Places image on the page

ps_open_memory_image
ps_rect
PS Functions
PHP Manual

ps_place_image

(PECL ps >= 1.1.0)

ps_place_image — Places image on the page

Description

bool ps_place_image ( resource $psdoc , int $imageid , float $x , float $y , float $scale )

Places a formerly loaded image on the page. The image can be scaled. If the image shall be rotated as well, you will have to rotate the coordinate system before with ps_rotate().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

imageid

The resource identifier of the image as returned by ps_open_image() or ps_open_image_file().

x

x-coordinate of the lower left corner of the image.

y

y-coordinate of the lower left corner of the image.

scale

The scaling factor for the image. A scale of 1.0 will result in a resolution of 72 dpi, because each pixel is equivalent to 1 point.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_open_image() - Reads an image for later placement
  • ps_open_image_file() - Opens image from file

ps_open_memory_image
ps_rect
PS Functions


Draws a rectangle

ps_place_image
ps_restore
PS Functions
PHP Manual

ps_rect

(PECL ps >= 1.1.0)

ps_rect — Draws a rectangle

Description

bool ps_rect ( resource $psdoc , float $x , float $y , float $width , float $height )

Draws a rectangle with its lower left corner at (x , y ). The rectangle starts and ends in its lower left corner. If this function is called outside a path it will start a new path. If it is called within a path it will add the rectangle as a subpath. If the last drawing operation does not end in the lower left corner then there will be a gap in the path.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the lower left corner of the rectangle.

y

y-coordinate of the lower left corner of the rectangle.

width

The width of the image.

height

The height of the image.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_arc() - Draws an arc counterclockwise
  • ps_cirle()
  • ps_lineto() - Draws a line

ps_place_image
ps_restore
PS Functions


Restore previously save context

ps_rect
ps_rotate
PS Functions
PHP Manual

ps_restore

(PECL ps >= 1.1.0)

ps_restore — Restore previously save context

Description

bool ps_restore ( resource $psdoc )

Restores a previously saved graphics context. Any call of ps_save() must be accompanied by a call to ps_restore(). All coordinate transformations, line style settings, color settings, etc. are being restored to the state before the call of ps_save().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_save() - Save current context

ps_rect
ps_rotate
PS Functions


Sets rotation factor

ps_restore
ps_save
PS Functions
PHP Manual

ps_rotate

(PECL ps >= 1.1.0)

ps_rotate — Sets rotation factor

Description

bool ps_rotate ( resource $psdoc , float $rot )

Sets the rotation of the coordinate system.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

rot

Angle of rotation in degree.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Rotation of the coordinate system

<?php
function rectangle($ps) {
    ps_moveto($ps, 0, 0);
    ps_lineto($ps, 0, 50);
    ps_lineto($ps, 50, 50);
    ps_lineto($ps, 50, 0);
    ps_lineto($ps, 0, 0);
    ps_stroke($ps);
}

$ps = ps_new();
if (!ps_open_file($ps, "rotation.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "rotation.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Rotation example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");

$psfont = ps_findfont($ps, "Helvetica", "", 0);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 100, 100);
ps_rotate($ps, 45);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text without rotation");
ps_end_page($ps);

ps_delete($ps);
?>

The above example illustrates a very common way of rotating a graphic (in this case just a rectangle) by simply rotating the coordinate system. Since the graphic's coordinate system assumes (0,0) to be the origin, the page coordinate system is also translated to place the graphics not on the edge of the page. Pay attention to the order of ps_translate() and ps_rotate(). In the above case the rectancle is rotated around the point (100, 100) in the untranslated coordinate system. Switching the two statements has a completely different result.

In order to output the following text at the original position, all modifications of the coordinate system are encapsulated in ps_save() and ps_restore().

See Also

  • ps_scale() - Sets scaling factor
  • ps_translate() - Sets translation

ps_restore
ps_save
PS Functions


Save current context

ps_rotate
ps_scale
PS Functions
PHP Manual

ps_save

(PECL ps >= 1.1.0)

ps_save — Save current context

Description

bool ps_save ( resource $psdoc )

Saves the current graphics context, containing colors, translation and rotation settings and some more. A saved context can be restored with ps_restore().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_restore() - Restore previously save context

ps_rotate
ps_scale
PS Functions


Sets scaling factor

ps_save
ps_set_border_color
PS Functions
PHP Manual

ps_scale

(PECL ps >= 1.1.0)

ps_scale — Sets scaling factor

Description

bool ps_scale ( resource $psdoc , float $x , float $y )

Sets horizontal and vertical scaling of the coordinate system.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

Scaling factor in horizontal direction.

y

Scaling factor in vertical direction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_rotate() - Sets rotation factor
  • ps_translate() - Sets translation

ps_save
ps_set_border_color
PS Functions


Sets color of border for annotations

ps_scale
ps_set_border_dash
PS Functions
PHP Manual

ps_set_border_color

(PECL ps >= 1.1.0)

ps_set_border_color — Sets color of border for annotations

Description

bool ps_set_border_color ( resource $psdoc , float $red , float $green , float $blue )

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the color of the rectangle's border line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

red

The red component of the border color.

green

The green component of the border color.

blue

The blue component of the border color.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_set_border_dash() - Sets length of dashes for border of annotations
  • ps_set_border_style() - Sets border style of annotations

ps_scale
ps_set_border_dash
PS Functions


Sets length of dashes for border of annotations

ps_set_border_color
ps_set_border_style
PS Functions
PHP Manual

ps_set_border_dash

(PECL ps >= 1.1.0)

ps_set_border_dash — Sets length of dashes for border of annotations

Description

bool ps_set_border_dash ( resource $psdoc , float $black , float $white )

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the length of the black and white portion of a dashed border line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

black

The length of the dash.

white

The length of the gap between dashes.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_set_border_color() - Sets color of border for annotations
  • ps_set_border_style() - Sets border style of annotations

ps_set_border_color
ps_set_border_style
PS Functions


Sets border style of annotations

ps_set_border_dash
ps_set_info
PS Functions
PHP Manual

ps_set_border_style

(PECL ps >= 1.1.0)

ps_set_border_style — Sets border style of annotations

Description

bool ps_set_border_style ( resource $psdoc , string $style , float $width )

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the appearance and width of the border line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

style

style can be solid or dashed.

width

The line width of the border.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_set_border_color() - Sets color of border for annotations
  • ps_set_border_dash() - Sets length of dashes for border of annotations

ps_set_border_dash
ps_set_info
PS Functions


Sets information fields of document

ps_set_border_style
ps_set_parameter
PS Functions
PHP Manual

ps_set_info

(PECL ps >= 1.1.0)

ps_set_info — Sets information fields of document

Description

bool ps_set_info ( resource $p , string $key , string $val )

Sets certain information fields of the document. This fields will be shown as a comment in the header of the PostScript file. If the document is converted to pdf this fields will also be used for the document information.

The BoundingBox is usually set to the value given to the first page. This only works if ps_findfont() has not been called before. In such cases the BoundingBox would be left unset unless you set it explicitly with this function.

This function will have no effect anymore when the header of the postscript file has been already written. It must be called before the first page or the first call of ps_findfont().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

key

The name of the information field to set. The values which can be set are Keywords, Subject, Title, Creator, Author, BoundingBox, and Orientation. Be aware that some of them has a meaning to PostScript viewers.

value

The value of the information field. The field Orientation can be set to either Portrait or Landscape. The BoundingBox is a string consisting of four numbers. The first two numbers are the coordinates of the lower left corner of the page. The last two numbers are the coordinates of the upper right corner.

Note: Up to version 0.2.6 of pslib, the BoundingBox and Orientation will be overwritten by ps_begin_page(), unless ps_findfont() has been called before.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_findfont() - Loads a font
  • ps_begin_page() - Start a new page

ps_set_border_style
ps_set_parameter
PS Functions


Sets certain parameters

ps_set_info
ps_set_text_pos
PS Functions
PHP Manual

ps_set_parameter

(PECL ps >= 1.1.0)

ps_set_parameter — Sets certain parameters

Description

bool ps_set_parameter ( resource $psdoc , string $name , string $value )

Sets several parameters which are used by many functions. Parameters are by definition string values.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

For a list of possible names see ps_get_parameter().

value

The value of the parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_get_parameters()
  • ps_set_value() - Sets certain values

ps_set_info
ps_set_text_pos
PS Functions


Sets position for text output

ps_set_parameter
ps_set_value
PS Functions
PHP Manual

ps_set_text_pos

(PECL ps >= 1.1.0)

ps_set_text_pos — Sets position for text output

Description

bool ps_set_text_pos ( resource $psdoc , float $x , float $y )

Set the position for the next text output. You may alternatively set the x and y value separately by calling ps_set_value() and choosing textx respectively texty as the value name.

If you want to output text at a certain position it is more convenient to use ps_show_xy() instead of setting the text position and calling ps_show().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the new text position.

y

y-coordinate of the new text position.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Placing text at a given position

<?php
$ps = ps_new();
if (!ps_open_file($ps, "text.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "rectangle.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Text placement example");

ps_begin_page($ps, 596, 842);
$psfont = ps_findfont($ps, "Helvetica", "", 0);
ps_setfont($ps, $psfont, 8.0);
ps_show_xy($ps, "Some text at (100, 100)", 100, 100);

ps_set_value($ps, "textx", 100);
ps_set_value($ps, "texty", 120);
ps_show($ps, "Some text at (100, 120)");
ps_end_page($ps);

ps_delete($ps);
?>

See Also

  • ps_set_value() - Sets certain values
  • ps_show() - Output text

ps_set_parameter
ps_set_value
PS Functions


Sets certain values

ps_set_text_pos
ps_setcolor
PS Functions
PHP Manual

ps_set_value

(PECL ps >= 1.1.0)

ps_set_value — Sets certain values

Description

bool ps_set_value ( resource $psdoc , string $name , float $value )

Sets several values which are used by many functions. Parameters are by definition float values.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

The name can be one of the following:

textrendering

The way how text is shown.

textx

The x coordinate for text output.

texty

The y coordinate for text output.

wordspacing

The distance between words relative to the width of a space.

leading

The distance between lines in pixels.

value

The value of the parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_get_value() - Gets certain values
  • ps_set_parameter() - Sets certain parameters

ps_set_text_pos
ps_setcolor
PS Functions


Sets current color

ps_set_value
ps_setdash
PS Functions
PHP Manual

ps_setcolor

(PECL ps >= 1.1.0)

ps_setcolor — Sets current color

Description

bool ps_setcolor ( resource $psdoc , string $type , string $colorspace , float $c1 , float $c2 , float $c3 , float $c4 )

Sets the color for drawing, filling, or both.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The parameter type can be both, fill, or fillstroke.

colorspace

The colorspace should be one of gray, rgb, cmyk, spot, pattern. Depending on the colorspace either only the first, the first three or all parameters will be used.

c1

Depending on the colorspace this is either the red component (rgb), the cyan component (cmyk), the gray value (gray), the identifier of the spot color or the identifier of the pattern.

c2

Depending on the colorspace this is either the green component (rgb), the magenta component (cmyk).

c3

Depending on the colorspace this is either the blue component (rgb), the yellow component (cmyk).

c4

This must only be set in cmyk colorspace and specifies the black component.

Bugs

The second parameter is currently not always evaluated. The color is sometimes set for filling and drawing just as if fillstroke were passed.

Return Values

Returns TRUE on success or FALSE on failure.

ps_set_value
ps_setdash
PS Functions


Sets appearance of a dashed line

ps_setcolor
ps_setflat
PS Functions
PHP Manual

ps_setdash

(PECL ps >= 1.1.0)

ps_setdash — Sets appearance of a dashed line

Description

bool ps_setdash ( resource $psdoc , float $on , float $off )

Sets the length of the black and white portions of a dashed line.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

on

The length of the dash.

off

The length of the gap between dashes.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_setpolydash() - Sets appearance of a dashed line

ps_setcolor
ps_setflat
PS Functions


Sets flatness

ps_setdash
ps_setfont
PS Functions
PHP Manual

ps_setflat

(PECL ps >= 1.1.0)

ps_setflat — Sets flatness

Description

bool ps_setflat ( resource $psdoc , float $value )

Warning

This function is currently not documented; only its argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

value

The value must be between 0.2 and 1.

Return Values

Returns TRUE on success or FALSE on failure.

ps_setdash
ps_setfont
PS Functions


Sets font to use for following output

ps_setflat
ps_setgray
PS Functions
PHP Manual

ps_setfont

(PECL ps >= 1.1.0)

ps_setfont — Sets font to use for following output

Description

bool ps_setfont ( resource $psdoc , int $fontid , float $size )

Sets a font, which has to be loaded before with ps_findfont(). Outputting text without setting a font results in an error.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

fontid

The font identifier as returned by ps_findfont().

size

The size of the font.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_findfont() - Loads a font
  • ps_set_text_pos() - Sets position for text output for an example.

ps_setflat
ps_setgray
PS Functions


Sets gray value

ps_setfont
ps_setlinecap
PS Functions
PHP Manual

ps_setgray

(PECL ps >= 1.1.0)

ps_setgray — Sets gray value

Description

bool ps_setgray ( resource $psdoc , float $gray )

Sets the gray value for all following drawing operations.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

gray

The value must be between 0 (white) and 1 (black).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_setcolor() - Sets current color

ps_setfont
ps_setlinecap
PS Functions


Sets appearance of line ends

ps_setgray
ps_setlinejoin
PS Functions
PHP Manual

ps_setlinecap

(PECL ps >= 1.1.0)

ps_setlinecap — Sets appearance of line ends

Description

bool ps_setlinecap ( resource $psdoc , int $type )

Sets how line ends look like.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of line ends. Possible values are PS_LINECAP_BUTT, PS_LINECAP_ROUND, or PS_LINECAP_SQUARED.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setlinewidth() - Sets width of a line
  • ps_setmiterlimit() - Sets the miter limit

ps_setgray
ps_setlinejoin
PS Functions


Sets how contected lines are joined

ps_setlinecap
ps_setlinewidth
PS Functions
PHP Manual

ps_setlinejoin

(PECL ps >= 1.1.0)

ps_setlinejoin — Sets how contected lines are joined

Description

bool ps_setlinejoin ( resource $psdoc , int $type )

Sets how lines are joined.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The way lines are joined. Possible values are PS_LINEJOIN_MITER, PS_LINEJOIN_ROUND, or PS_LINEJOIN_BEVEL.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_setlinecap() - Sets appearance of line ends
  • ps_setlinewidth() - Sets width of a line
  • ps_setmiterlimit() - Sets the miter limit

ps_setlinecap
ps_setlinewidth
PS Functions


Sets width of a line

ps_setlinejoin
ps_setmiterlimit
PS Functions
PHP Manual

ps_setlinewidth

(PECL ps >= 1.1.0)

ps_setlinewidth — Sets width of a line

Description

bool ps_setlinewidth ( resource $psdoc , float $width )

Sets the line width for all following drawing operations.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of lines in points.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_setlinecap() - Sets appearance of line ends
  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setmiterlimit() - Sets the miter limit

ps_setlinejoin
ps_setmiterlimit
PS Functions


Sets the miter limit

ps_setlinewidth
ps_setoverprintmode
PS Functions
PHP Manual

ps_setmiterlimit

(PECL ps >= 1.1.0)

ps_setmiterlimit — Sets the miter limit

Description

bool ps_setmiterlimit ( resource $psdoc , float $value )

If two lines join in a small angle and the line join is set to PS_LINEJOIN_MITER, then the resulting spike will be very long. The miter limit is the maximum ratio of the miter length (the length of the spike) and the line width.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

value

The maximum ratio between the miter length and the line width. Larger values (> 10) will result in very long spikes when two lines meet in a small angle. Keep the default unless you know what you are doing.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_setlinecap() - Sets appearance of line ends
  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setlinewidth() - Sets width of a line

ps_setlinewidth
ps_setoverprintmode
PS Functions


Sets overprint mode

ps_setmiterlimit
ps_setpolydash
PS Functions
PHP Manual

ps_setoverprintmode

(PECL ps >= 1.3.0)

ps_setoverprintmode — Sets overprint mode

Description

bool ps_setoverprintmode ( resource $psdoc , int $mode )

Warning

This function is currently not documented; only its argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

mode

Return Values

Returns TRUE on success or FALSE on failure.

ps_setmiterlimit
ps_setpolydash
PS Functions


Sets appearance of a dashed line

ps_setoverprintmode
ps_shading_pattern
PS Functions
PHP Manual

ps_setpolydash

(PECL ps >= 1.1.0)

ps_setpolydash — Sets appearance of a dashed line

Description

bool ps_setpolydash ( resource $psdoc , float $arr )

Sets the length of the black and white portions of a dashed line. ps_setpolydash() is used to set more complicated dash patterns.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

arr

arr is a list of length elements alternately for the black and white portion.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Drawing a dashed line

<?php
$ps = ps_new();
if (!ps_open_file($ps, "polydash.ps")) {
   print "Cannot open PostScript file\n";
     exit;
}

ps_set_info($ps, "Creator", "polydash.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Poly dash example");

ps_begin_page($ps, 596, 842);
ps_setpolydash($ps, array(10, 5, 2, 5));
ps_moveto($ps, 100, 100);
ps_lineto($ps, 200, 200);
ps_stroke($ps);
ps_end_page($ps);

ps_delete($ps);
?>

This example draws a line with a 10 and 2 points long line, and gaps of 5 points inbetween.

See Also

  • ps_setdash() - Sets appearance of a dashed line

ps_setoverprintmode
ps_shading_pattern
PS Functions


Creates a shading for later use

ps_shading_pattern
ps_shfill
PS Functions
PHP Manual

ps_shading

(PECL ps >= 1.3.0)

ps_shading — Creates a shading for later use

Description

int ps_shading ( resource $psdoc , string $type , float $x0 , float $y0 , float $x1 , float $y1 , float $c1 , float $c2 , float $c3 , float $c4 , string $optlist )

Creates a shading, which can be used by ps_shfill() or ps_shading_pattern().

The color of the shading can be in any color space except for pattern.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of shading can be either radial or axial. Each shading starts with the current fill color and ends with the given color values passed in the parameters c1 to c4 (see ps_setcolor() for their meaning).

x0, x1, y0, y1

The coordinates x0 , y0 , x1 , y1 are the start and end point of the shading. If the type of shading is radial the two points are the middle points of a starting and ending circle.

c1, c2, c3, c4

See ps_setcolor() for their meaning.

optlist

If the shading is of type radial the optlist must also contain the parameters r0 and r1 with the radius of the start and end circle.

Return Values

Returns the identifier of the pattern or FALSE on failure.

See Also

  • ps_shading_pattern() - Creates a pattern based on a shading
  • ps_shfill() - Fills an area with a shading

ps_shading_pattern
ps_shfill
PS Functions


Creates a pattern based on a shading

ps_setpolydash
ps_shading
PS Functions
PHP Manual

ps_shading_pattern

(PECL ps >= 1.3.0)

ps_shading_pattern — Creates a pattern based on a shading

Description

int ps_shading_pattern ( resource $psdoc , int $shadingid , string $optlist )

Creates a pattern based on a shading, which has to be created before with ps_shading(). Shading patterns can be used like regular patterns.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

shadingid

The identifier of a shading previously created with ps_shading().

optlist

This argument is not currently used.

Return Values

The identifier of the pattern or FALSE on failure.

See Also

  • ps_shading() - Creates a shading for later use
  • ps_shfill() - Fills an area with a shading

ps_setpolydash
ps_shading
PS Functions


Fills an area with a shading

ps_shading
ps_show_boxed
PS Functions
PHP Manual

ps_shfill

(PECL ps >= 1.3.0)

ps_shfill — Fills an area with a shading

Description

bool ps_shfill ( resource $psdoc , int $shadingid )

Fills an area with a shading, which has to be created before with ps_shading(). This is an alternative way to creating a pattern from a shading ps_shading_pattern() and using the pattern as the filling color.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

shadingid

The identifier of a shading previously created with ps_shading().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_shading() - Creates a shading for later use
  • ps_shading_pattern() - Creates a pattern based on a shading

ps_shading
ps_show_boxed
PS Functions


Output text

ps_show2
ps_string_geometry
PS Functions
PHP Manual

ps_show

(PECL ps >= 1.1.0)

ps_show — Output text

Description

bool ps_show ( resource $psdoc , string $text )

Output a text at the current text position. The text position can be set by storing the x and y coordinates into the values textx and texty with the function ps_set_value(). The function will issue an error if a font was not set before with ps_setfont().

ps_show() evaluates the following parameters and values as set by ps_set_parameter() and ps_set_value().

charspacing (value)

Distance between two consecutive glyphs. If this value is unequal to zero then all ligatures will be resolved. Values less than zero are allowed.

kerning (parameter)

Setting this parameter to "false" will turn off kerning. Kerning is turned on by default.

ligatures (parameter)

Setting this parameter to "false" will turn off the use of ligatures. Ligatures are turned on by default.

underline (parameter)

Setting this parameter to "true" will turn on underlining. Underlining is turned off by default.

overline (parameter)

Setting this parameter to "true" will turn on overlining. Overlining is turned off by default.

strikeout (parameter)

Setting this parameter to "true" will turn on striking out. Striking out is turned off by default.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_continue_text() - Continue text in next line
  • ps_show_xy() - Output text at given position
  • ps_setfont() - Sets font to use for following output

ps_show2
ps_string_geometry
PS Functions


Output a text at current position

ps_show_xy
ps_show
PS Functions
PHP Manual

ps_show2

(PECL ps >= 1.1.0)

ps_show2 — Output a text at current position

Description

bool ps_show2 ( resource $psdoc , string $text , int $len )

Warning

This function is currently not documented; only its argument list is available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

len

Return Values

Returns TRUE on success or FALSE on failure.

ps_show_xy
ps_show
PS Functions


Output text in a box

ps_shfill
ps_show_xy2
PS Functions
PHP Manual

ps_show_boxed

(PECL ps >= 1.1.0)

ps_show_boxed — Output text in a box

Description

int ps_show_boxed ( resource $psdoc , string $text , float $left , float $bottom , float $width , float $height , string $hmode [, string $feature ] )

Outputs a text in a given box. The lower left corner of the box is at (left , bottom ). Line breaks will be inserted where needed. Multiple spaces are treated as one. Tabulators are treated as spaces.

The text will be hyphenated if the parameter hyphenation is set to true and the parameter hyphendict contains a valid filename for a hyphenation file. The line spacing is taken from the value leading. Paragraphs can be separated by an empty line just like in TeX. If the value parindent is set to value > 0.0 then the first n lines will be indented. The number n of lines is set by the parameter numindentlines. In order to prevent indenting of the first m paragraphs set the value parindentskip to a positive number.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output into the given box.

left

x-coordinate of the lower left corner of the box.

bottom

y-coordinate of the lower left corner of the box.

width

Width of the box.

height

Height of the box.

hmode

The parameter hmode can be "justify", "fulljustify", "right", "left", or "center". The difference of "justify" and "fulljustify" just affects the last line of the box. In fulljustify mode the last line will be left and right justified unless this is also the last line of paragraph. In justify mode it will always be left justified.

feature

Used parameters

The output of ps_show_boxed() can be configured with several parameters and values which must be set with either ps_set_parameter() or ps_set_value(). Beside the parameters and values which affect text output, the following parameters and values are evaluated.

leading (value)

Distance between baselines of two consecutive lines.

linebreak (parameter)

Set to "true" if you want a carriage return to start a new line instead of treating it as a space. Defaults to "false".

parbreak (parameter)

Set to "true" if you want a carriage return on a single line to start a new paragraph instead of treating it as a space. Defaults to "true".

hyphenation (parameter)

Set to "true" in order to turn hyphenation on. This requires a dictionary to be set with the parameter "hyphendict". Defaults to "false".

hyphendict (parameter)

Filename of the dictionary used for hyphenation pattern (see below).

hyphenminchar (value)

The number of chars which must at least be left over before or after the hyphen. This implies that only words of at least two times this value will be hyphenated. The default value is three. Setting a value of zero will result in the default value.

parindent (value)

Set the amount of space in pixel for indenting the first m lines of a paragraph. m can be set with the value "numindentlines".

parskip (value)

Set the amount of extra space in pixel between paragraphs. Defaults to 0 which will result in a normal line distance.

numindentlines (value)

Number of lines from the start of the paragraph which will be indented. Defaults to 1.

parindentskip (value)

Number of paragraphs in the box whose first lines will not be indented. This defaults to 0. This is useful for paragraphs right after a section heading or text being continued in a second box. In both case one would set this to 1.

linenumbermode (parameter)

Set how lines are to be numbered. Possible values are "box" for numbering lines in the whole box or "paragraph" to number lines within each paragraph.

linenumberspace (value)

The space for the column left of the numbered line containing the line number. The line number will be right justified into this column. Defaults to 20.

linenumbersep (value)

The space between the column with line numbers and the line itself. Defaults to 5.

Hyphenation

Text is hyphenated if the parameter hyphenation is set to true and a valid hyphenation dictionary is set. pslib does not ship its own hyphenation dictionary but uses one from openoffice, scribus or koffice. You can find their dictionaries for different languages in one of the following directories if the software is installed:

  • /usr/share/apps/koffice/hyphdicts/
  • /usr/lib/scribus/dicts/
  • /usr/lib/openoffice/share/dict/ooo/

Currently scribus appears to have the most complete hyphenation dictionaries.

Return Values

Number of characters that could not be written.

See Also

  • ps_continue_text() - Continue text in next line

ps_shfill
ps_show_xy2
PS Functions


Output text at given position

ps_show_xy2
ps_show2
PS Functions
PHP Manual

ps_show_xy

(PECL ps >= 1.1.0)

ps_show_xy — Output text at given position

Description

bool ps_show_xy ( resource $psdoc , string $text , float $x , float $y )

Output a text at the given text position.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

x

x-coordinate of the lower left corner of the box surrounding the text.

y

y-coordinate of the lower left corner of the box surrounding the text.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_continue_text() - Continue text in next line
  • ps_show() - Output text

ps_show_xy2
ps_show2
PS Functions


Output text at position

ps_show_boxed
ps_show_xy
PS Functions
PHP Manual

ps_show_xy2

(PECL ps >= 1.1.0)

ps_show_xy2 — Output text at position

Description

bool ps_show_xy2 ( resource $psdoc , string $text , int $len , float $xcoor , float $ycoor )

Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

ps_show_boxed
ps_show_xy
PS Functions


Gets geometry of a string

ps_show
ps_stringwidth
PS Functions
PHP Manual

ps_string_geometry

(PECL ps >= 1.2.0)

ps_string_geometry — Gets geometry of a string

Description

array ps_string_geometry ( resource $psdoc , string $text [, int $fontid = 0 [, float $size = 0.0 ]] )

This function is similar to ps_stringwidth() but returns an array of dimensions containing the width, ascender, and descender of the text.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text for which the geometry is to be calculated.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

Return Values

An array of the dimensions of a string. The element 'width' contains the width of the string as returned by ps_stringwidth(). The element 'descender' contains the maximum descender and 'ascender' the maximum ascender of the string.

See Also

  • ps_continue_text() - Continue text in next line
  • ps_stringwidth() - Gets width of a string

ps_show
ps_stringwidth
PS Functions


Gets width of a string

ps_string_geometry
ps_stroke
PS Functions
PHP Manual

ps_stringwidth

(PECL ps >= 1.1.0)

ps_stringwidth — Gets width of a string

Description

float ps_stringwidth ( resource $psdoc , string $text [, int $fontid = 0 [, float $size = 0.0 ]] )

Calculates the width of a string in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width. If kerning is turned on, it will be taken into account.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text for which the width is to be calculated.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

Return Values

Width of a string in points.

See Also

  • ps_string_geometry() - Gets geometry of a string

ps_string_geometry
ps_stroke
PS Functions


Draws the current path

ps_stringwidth
ps_symbol_name
PS Functions
PHP Manual

ps_stroke

(PECL ps >= 1.1.0)

ps_stroke — Draws the current path

Description

bool ps_stroke ( resource $psdoc )

Draws the path constructed with previously called drawing functions like ps_lineto().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_closepath_stroke() - Closes and strokes path
  • ps_fill() - Fills the current path
  • ps_fill_stroke() - Fills and strokes the current path

ps_stringwidth
ps_symbol_name
PS Functions


Output a glyph

ps_symbol_width
ps_translate
PS Functions
PHP Manual

ps_symbol

(PECL ps >= 1.2.0)

ps_symbol — Output a glyph

Description

bool ps_symbol ( resource $psdoc , int $ord )

Output the glyph at position ord in the font encoding vector of the current font. The font encoding for a font can be set when loading the font with ps_findfont().

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The position of the glyph in the font encoding vector.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ps_symbol_name() - Gets name of a glyph
  • ps_symbol_width() - Gets width of a glyph

ps_symbol_width
ps_translate
PS Functions


Gets name of a glyph

ps_stroke
ps_symbol_width
PS Functions
PHP Manual

ps_symbol_name

(PECL ps >= 1.2.0)

ps_symbol_name — Gets name of a glyph

Description

string ps_symbol_name ( resource $psdoc , int $ord [, int $fontid = 0 ] )

This function needs an Adobe font metrics file to know which glyphs are available.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The parameter ord is the position of the glyph in the font encoding vector.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

Return Values

The name of a glyph in the given font.

See Also

  • ps_symbol() - Output a glyph
  • ps_symbol_width() - Gets width of a glyph

ps_stroke
ps_symbol_width
PS Functions


Gets width of a glyph

ps_symbol_name
ps_symbol
PS Functions
PHP Manual

ps_symbol_width

(PECL ps >= 1.2.0)

ps_symbol_width — Gets width of a glyph

Description

float ps_symbol_width ( resource $psdoc , int $ord [, int $fontid = 0 [, float $size = 0.0 ]] )

Calculates the width of a glyph in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The position of the glyph in the font encoding vector.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

Return Values

The width of a glyph in points.

See Also

  • ps_symbol() - Output a glyph
  • ps_symbol_name() - Gets name of a glyph

ps_symbol_name
ps_symbol
PS Functions


Sets translation

ps_symbol
RPM Reader
PS Functions
PHP Manual

ps_translate

(PECL ps >= 1.1.0)

ps_translate — Sets translation

Description

bool ps_translate ( resource $psdoc , float $x , float $y )

Sets a new initial point of the coordinate system.

Parameters

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the origin of the translated coordinate system.

y

y-coordinate of the origin of the translated coordinate system.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Translation of the coordinate system

<?php
function rectangle($ps) {
    ps_moveto($ps, 0, 0);
    ps_lineto($ps, 0, 50);
    ps_lineto($ps, 50, 50);
    ps_lineto($ps, 50, 0);
    ps_lineto($ps, 0, 0);
    ps_stroke($ps);
}

$ps = ps_new();
if (!ps_open_file($ps, "translate.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "translate.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Translated example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");

$psfont = ps_findfont($ps, "Helvetica", "", 0);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_translate($ps, -500, -750);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);

ps_delete($ps);
?>

The above example demonstrates two possible ways to place a graphic (in this case just a rectangle) at any position on the page, while the graphic itself uses its own coordinate system. The trick is to change the origin of the current coordinate system before drawing the rectangle. The translation has to undone after the graphic has been drawn.

On the second page a slightly different and more elegant approach is applied. Instead of undoing the translation with a second call of ps_translate() the graphics context is saved before modifying the coordinate system and restored after drawing the rectangle.

See Also

  • ps_scale() - Sets scaling factor
  • ps_rotate() - Sets rotation factor

ps_symbol
RPM Reader
PS Functions


Add the word to a personal wordlist

Pspell Functions
pspell_add_to_session
Pspell Functions
PHP Manual

pspell_add_to_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_add_to_personal — Add the word to a personal wordlist

Description

bool pspell_add_to_personal ( int $dictionary_link , string $word )

pspell_add_to_personal() adds a word to the personal wordlist. If you used pspell_new_config() with pspell_config_personal() to open the dictionary, you can save the wordlist later with pspell_save_wordlist().

Parameters

dictionary_link

word

The added word.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_save_wordlist($pspell_link);
?>

Notes

Note: This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Pspell Functions
pspell_add_to_session
Pspell Functions


Add the word to the wordlist in the current session

pspell_add_to_personal
pspell_check
Pspell Functions
PHP Manual

pspell_add_to_session

(PHP 4 >= 4.0.2, PHP 5)

pspell_add_to_session — Add the word to the wordlist in the current session

Description

bool pspell_add_to_session ( int $dictionary_link , string $word )

pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()

Parameters

dictionary_link

word

The added word.

Return Values

Returns TRUE on success or FALSE on failure.

pspell_add_to_personal
pspell_check
Pspell Functions


Check a word

pspell_add_to_session
pspell_clear_session
Pspell Functions
PHP Manual

pspell_check

(PHP 4 >= 4.0.2, PHP 5)

pspell_check — Check a word

Description

bool pspell_check ( int $dictionary_link , string $word )

pspell_check() checks the spelling of a word.

Parameters

dictionary_link

word

The tested word.

Return Values

Returns TRUE if the spelling is correct, FALSE if not.

Examples

Example #1 pspell_check() Example

<?php
$pspell_link = pspell_new("en");

if (pspell_check($pspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}
?>

pspell_add_to_session
pspell_clear_session
Pspell Functions


Clear the current session

pspell_check
pspell_config_create
Pspell Functions
PHP Manual

pspell_clear_session

(PHP 4 >= 4.0.2, PHP 5)

pspell_clear_session — Clear the current session

Description

bool pspell_clear_session ( int $dictionary_link )

pspell_clear_session() clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with pspell_save_wordlist(), nothing happens.

Parameters

dictionary_link

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_add_to_personal() Example

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_clear_session($pspell_link);
pspell_save_wordlist($pspell_link);    //"Vlad" will not be saved
?>

pspell_check
pspell_config_create
Pspell Functions


Create a config used to open a dictionary

pspell_clear_session
pspell_config_data_dir
Pspell Functions
PHP Manual

pspell_config_create

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_create — Create a config used to open a dictionary

Description

int pspell_config_create ( string $language [, string $spelling [, string $jargon [, string $encoding ]]] )

Create a config used to open a dictionary.

pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create() immediately followed by pspell_new_config() will produce the exact same result. However, after creating a new config, you can also use pspell_config_*() functions before calling pspell_new_config() to take advantage of some advanced functionality.

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

Parameters

language

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

spelling

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

Return Values

Retuns a pspell config identifier, or FALSE on error.

Examples

Example #1 pspell_config_create()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_personal($pspell_config, "en");
?>

pspell_clear_session
pspell_config_data_dir
Pspell Functions


location of language data files

pspell_config_create
pspell_config_dict_dir
Pspell Functions
PHP Manual

pspell_config_data_dir

(PHP 5)

pspell_config_data_dir — location of language data files

Description

bool pspell_config_data_dir ( int $conf , string $directory )

Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

pspell_config_create
pspell_config_dict_dir
Pspell Functions


Location of the main word list

pspell_config_data_dir
pspell_config_ignore
Pspell Functions
PHP Manual

pspell_config_dict_dir

(PHP 5)

pspell_config_dict_dir — Location of the main word list

Description

bool pspell_config_dict_dir ( int $conf , string $directory )

Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

pspell_config_data_dir
pspell_config_ignore
Pspell Functions


Ignore words less than N characters long

pspell_config_dict_dir
pspell_config_mode
Pspell Functions
PHP Manual

pspell_config_ignore

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_ignore — Ignore words less than N characters long

Description

bool pspell_config_ignore ( int $dictionary_link , int $n )

pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function allows short words to be skipped by the spell checker.

Parameters

dictionary_link

n

Words less than n characters will be skipped.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_ignore()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_ignore($pspell_config, 5);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "abcd");    //will not result in an error
?>

pspell_config_dict_dir
pspell_config_mode
Pspell Functions


Change the mode number of suggestions returned

pspell_config_ignore
pspell_config_personal
Pspell Functions
PHP Manual

pspell_config_mode

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_mode — Change the mode number of suggestions returned

Description

bool pspell_config_mode ( int $dictionary_link , int $mode )

pspell_config_mode() should be used on a config before calling pspell_new_config(). This function determines how many suggestions will be returned by pspell_suggest().

Parameters

dictionary_link

mode

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)
  • PSPELL_NORMAL - Normal mode (more suggestions)
  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_mode() Example

<?php
$pspell_config = pspell_config_create("en");
pspell_config_mode($pspell_config, PSPELL_FAST);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

pspell_config_ignore
pspell_config_personal
Pspell Functions


Set a file that contains personal wordlist

pspell_config_mode
pspell_config_repl
Pspell Functions
PHP Manual

pspell_config_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_personal — Set a file that contains personal wordlist

Description

bool pspell_config_personal ( int $dictionary_link , string $file )

Set a file that contains personal wordlist. The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). The file is also the file where pspell_save_wordlist() will save personal wordlist to.

pspell_config_personal() should be used on a config before calling pspell_new_config().

Parameters

dictionary_link

file

The personal wordlist. If the file does not exist, it will be created. The file should be writable by whoever PHP runs as (e.g. nobody).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

Notes

Note: This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_config_mode
pspell_config_repl
Pspell Functions


Set a file that contains replacement pairs

pspell_config_personal
pspell_config_runtogether
Pspell Functions
PHP Manual

pspell_config_repl

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_repl — Set a file that contains replacement pairs

Description

bool pspell_config_repl ( int $dictionary_link , string $file )

Set a file that contains replacement pairs.

The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, pspell_store_replacement() can be used to store a replacement pair and then pspell_save_wordlist() to save the wordlist along with the replacement pairs.

pspell_config_repl() should be used on a config before calling pspell_new_config().

Parameters

dictionary_link

file

The file should be writable by whoever PHP runs as (e.g. nobody).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_repl()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

Notes

Note: This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_config_personal
pspell_config_runtogether
Pspell Functions


Consider run-together words as valid compounds

pspell_config_repl
pspell_config_save_repl
Pspell Functions
PHP Manual

pspell_config_runtogether

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_runtogether — Consider run-together words as valid compounds

Description

bool pspell_config_runtogether ( int $dictionary_link , bool $flag )

This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

pspell_config_runtogether() should be used on a config before calling pspell_new_config().

Parameters

dictionary_link

flag

TRUE if run-together words should be treated as legal compounds, FALSE otherwise.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_runtogether()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_runtogether($pspell_config, true);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

pspell_config_repl
pspell_config_save_repl
Pspell Functions


Determine whether to save a replacement pairs list along with the wordlist

pspell_config_runtogether
pspell_new_config
Pspell Functions
PHP Manual

pspell_config_save_repl

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist

Description

bool pspell_config_save_repl ( int $dictionary_link , bool $flag )

pspell_config_save_repl() determines whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved.

pspell_config_save_repl() should be used on a config before calling pspell_new_config().

Parameters

dictionary_link

flag

TRUE if replacement pairs should be saved, FALSE otherwise.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_config_runtogether
pspell_new_config
Pspell Functions


Load a new dictionary

pspell_new_personal
pspell_save_wordlist
Pspell Functions
PHP Manual

pspell_new

(PHP 4 >= 4.0.2, PHP 5)

pspell_new — Load a new dictionary

Description

int pspell_new ( string $language [, string $spelling [, string $jargon [, string $encoding [, int $mode = 0 ]]]] )

pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell functions.

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

Parameters

language

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

spelling

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

mode

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)
  • PSPELL_NORMAL - Normal mode (more suggestions)
  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

Return Values

Returns the dictionary link identifier on success or FALSE on failure.

Examples

Example #1 pspell_new()

<?php
$pspell_link = pspell_new("en", "", "", "",
                           (PSPELL_FAST|PSPELL_RUN_TOGETHER));
?>

pspell_new_personal
pspell_save_wordlist
Pspell Functions


Load a new dictionary with settings based on a given config

pspell_config_save_repl
pspell_new_personal
Pspell Functions
PHP Manual

pspell_new_config

(PHP 4 >= 4.0.2, PHP 5)

pspell_new_config — Load a new dictionary with settings based on a given config

Description

int pspell_new_config ( int $config )

pspell_new_config() opens up a new dictionary with settings specified in a config, created with pspell_config_create() and modified with pspell_config_*() functions. This method provides you with the most flexibility and has all the functionality provided by pspell_new() and pspell_new_personal().

Parameters

config

The config parameter is the one returned by pspell_config_create() when the config was created.

Return Values

Returns a dictionary link identifier on success.

Examples

Example #1 pspell_new_config()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);
?>

pspell_config_save_repl
pspell_new_personal
Pspell Functions


Load a new dictionary with personal wordlist

pspell_new_config
pspell_new
Pspell Functions
PHP Manual

pspell_new_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_new_personal — Load a new dictionary with personal wordlist

Description

int pspell_new_personal ( string $personal , string $language [, string $spelling [, string $jargon [, string $encoding [, int $mode = 0 ]]]] )

pspell_new_personal() opens up a new dictionary with a personal wordlist. The wordlist can be modified and saved with pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a new dictionary with pspell_new_config().

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

Parameters

personal

The file where words added to the personal list will be stored. It should be an absolute filename beginning with '/' because otherwise it will be relative to $HOME, which is "/root" for most systems, and is probably not what you want.

language

The language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

spelling

The requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

Extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

The encoding that words are expected to be in. Valid values are utf-8, iso8859-*, koi8-r, viscii, cp1252, machine unsigned 16, machine unsigned 32.

mode

The mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)
  • PSPELL_NORMAL - Normal mode (more suggestions)
  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

Return Values

Returns the dictionary link identifier for use in other pspell functions.

Examples

Example #1 pspell_new_personal()

<?php
$pspell_link = pspell_new_personal ("/var/dictionaries/custom.pws",
        "en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER);
?>

pspell_new_config
pspell_new
Pspell Functions


Save the personal wordlist to a file

pspell_new
pspell_store_replacement
Pspell Functions
PHP Manual

pspell_save_wordlist

(PHP 4 >= 4.0.2, PHP 5)

pspell_save_wordlist — Save the personal wordlist to a file

Description

bool pspell_save_wordlist ( int $dictionary_link )

pspell_save_wordlist() saves the personal wordlist from the current session. The location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl().

Parameters

dictionary_link

A dictionary link identifier opened with pspell_new_personal().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/tmp/dicts/newdict");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_save_wordlist($pspell_link);
?>

Notes

Note: This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_new
pspell_store_replacement
Pspell Functions


Store a replacement pair for a word

pspell_save_wordlist
pspell_suggest
Pspell Functions
PHP Manual

pspell_store_replacement

(PHP 4 >= 4.0.2, PHP 5)

pspell_store_replacement — Store a replacement pair for a word

Description

bool pspell_store_replacement ( int $dictionary_link , string $misspelled , string $correct )

pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by pspell_suggest() later. In order to be able to take advantage of this function, you have to use pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom wordlists, and then use pspell_save_wordlist() for the changes to be written to disk.

Parameters

dictionary_link

A dictionary link identifier, opened with pspell_new_personal()

misspelled

The misspelled word.

correct

The fixed spelling for the misspelled word.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_store_replacement()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);

pspell_store_replacement($pspell_link, $misspelled, $correct);
pspell_save_wordlist($pspell_link);
?>

Notes

Note: This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_save_wordlist
pspell_suggest
Pspell Functions


Suggest spellings of a word

pspell_store_replacement
Recode
Pspell Functions
PHP Manual

pspell_suggest

(PHP 4 >= 4.0.2, PHP 5)

pspell_suggest — Suggest spellings of a word

Description

array pspell_suggest ( int $dictionary_link , string $word )

pspell_suggest() returns an array of possible spellings for the given word.

Parameters

dictionary_link

word

The tested word.

Return Values

Returns an array of possible spellings.

Examples

Example #1 pspell_suggest() example

<?php
$pspell_link = pspell_new("en");

if (!pspell_check($pspell_link, "testt")) {
    $suggestions = pspell_suggest($pspell_link, "testt");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br />";
    }
}
?>

pspell_store_replacement
Recode
Pspell Functions


Sets the value of an environment variable

phpversion
restore_include_path
PHP Options/Info Functions
PHP Manual

putenv

(PHP 4, PHP 5)

putenv — Sets the value of an environment variable

Description

bool putenv ( string $setting )

Adds setting to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state.

Setting certain environment variables may be a potential security breach. The safe_mode_allowed_env_vars directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied by this directive. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty, PHP will let the user modify ANY environment variable!

The safe_mode_protected_env_vars directive contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

Parameters

setting

The setting, like "FOO=BAR"

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting an environment variable

<?php
putenv("UNIQID=$uniqid");
?>

Notes

Warning

These directives have only effect when safe-mode itself is enabled!

See Also

  • getenv() - Gets the value of an environment variable

phpversion
restore_include_path
PHP Options/Info Functions


Closes a paradox database

Paradox Functions
px_create_fp
Paradox Functions
PHP Manual

px_close

(PECL paradox >= 1.0.0)

px_close — Closes a paradox database

Description

bool px_close ( resource $pxdoc )

Closes the paradox database. This function will not close the file. You will have to call fclose() afterwards.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • px_open_fp() - Open paradox database
  • The example at px_new() - Create a new paradox object

Paradox Functions
px_create_fp
Paradox Functions


Create a new paradox database

px_close
px_date2string
Paradox Functions
PHP Manual

px_create_fp

(PECL paradox >= 1.0.0)

px_create_fp — Create a new paradox database

Description

bool px_create_fp ( resource $pxdoc , resource $file , array $fielddesc )

Create a new paradox database file. The actual file has to be opened before with fopen(). Make sure the file is writable.

Note: Calling this functions issues a warning about an empty tablename which can be safely ignored. Just set the tablename afterwards with px_set_parameter().

Note: This function is highly experimental, due to insufficient documentation of the paradox file format. Database files created with this function can be opened by px_open_fp() and has been successfully opened by the Paradox software, but your milage may vary.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

file

File handle as returned by fopen().

fielddesc

fielddesc is an array containing one element for each field specification. A field specification is an array itself with either two or three elements.The first element is always a string value used as the name of the field. It may not be larger than ten characters. The second element contains the field type which is one of the constants listed in the table Constants for field types. In the case of a character field or bcd field, you will have to provide a third element specifying the length respectively the precesion of the field. If your field specification contains blob fields, you will have to make sure to either make the field large enough for all field values to fit or specify a blob file with px_set_blob_file() for storing the blobs. If this is not done the field data is truncated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Creating a Paradox database with two fields

<?php
if(!$pxdoc = px_new()) {
  /* Error handling */
}
$fp = fopen("test.db", "w+");
$fields = array(array("col1", "S"), array("col2", "I"));
if(!px_create_fp($pxdoc, $fp, $fields)) {
  /* Error handling */
}
px_set_parameter($pxdoc, "tablename", "testtable");
for($i=-50; $i<50; $i++) {
  $rec = array($i, -$i);
  px_put_record($pxdoc, $rec);
}
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

See Also

  • px_new() - Create a new paradox object
  • px_put_record() - Stores record into paradox database
  • fopen() - Opens file or URL

px_close
px_date2string
Paradox Functions


Converts a date into a string.

px_create_fp
px_delete_record
Paradox Functions
PHP Manual

px_date2string

(PECL paradox >= 1.4.0)

px_date2string — Converts a date into a string.

Description

string px_date2string ( resource $pxdoc , int $value , string $format )

Turns a date as it stored in the paradox file into human readable format. Paradox dates are the number of days since 1.1.0000. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the example below.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

value

Value as stored in paradox database field of type PX_FIELD_DATE.

format

String format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, L).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Turn a paradox date into a human readable form

<?php
$px = px_new();

/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days = 700000;

/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";
/* px_date2string() outputs the same */
echo px_date2string($px, $days, "n/d/Y")."\n";

px_delete($px);
?>

The above example will output:

7/15/1917
7/15/1917

See Also

  • px_timestamp2string() - Converts the timestamp into a string.
  • jdtogregorian() - Converts Julian Day Count to Gregorian date

px_create_fp
px_delete_record
Paradox Functions


Deletes resource of paradox database

px_delete_record
px_get_field
Paradox Functions
PHP Manual

px_delete

(PECL paradox >= 1.0.0)

px_delete — Deletes resource of paradox database

Description

bool px_delete ( resource $pxdoc )

Deletes the resource of the paradox file and frees all memory.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns TRUE on success or FALSE on failure.

px_delete_record
px_get_field
Paradox Functions


Deletes record from paradox database

px_date2string
px_delete
Paradox Functions
PHP Manual

px_delete_record

(PECL paradox >= 1.4.0)

px_delete_record — Deletes record from paradox database

Description

bool px_delete_record ( resource $pxdoc , int $num )

This function deletes a record from the database. It does not free the space in the database file but just marks it as deleted. Inserting a new record afterwards will reuse the space.

Note: This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

Return Values

Returns TRUE on success or FALSE on failure.

px_date2string
px_delete
Paradox Functions


Returns the specification of a single field

px_delete
px_get_info
Paradox Functions
PHP Manual

px_get_field

(PECL paradox >= 1.0.0)

px_get_field — Returns the specification of a single field

Description

array px_get_field ( resource $pxdoc , int $fieldno )

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

fieldno

Number of the field. The first field has number 0. Specifying a field number less than 0 and greater or equal the number of fields will trigger an error.

Return Values

Returns the specification of the fieldno'th database field as an associated array. The array contains three fields named name, type, and size.

px_delete
px_get_info
Paradox Functions


Return lots of information about a paradox file

px_get_field
px_get_parameter
Paradox Functions
PHP Manual

px_get_info

(PECL paradox >= 1.0.0)

px_get_info — Return lots of information about a paradox file

Description

array px_get_info ( resource $pxdoc )

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns an associated array with lots of information about a paradox file. This array is likely to be extended in the future.

fileversion

Version of file multiplied by 10, e.g. 70.

tablename

Name of table as stored in the file. If the database was created by pxlib, then this will be the name of the file without the extension.

numrecords

Number of records in this table.

numfields

Number of fields in this table.

headersize

Number of bytes used for the header. This is usually 0x800.

recordsize

Number of bytes used for each record. This is the sum of all field sizes (available since version 1.4.2).

maxtablesize

This value multiplied by 0x400 is the size of a data block in bytes. The maximum number of records in a datablock is the integer part of (maxtablesize * 0x400 - 8) / recordsize.

numdatablocks

The number of data blocks in the file. Each data block contains a certain number of records which depends on the record size and the data block size (maxtablesize). Data blocks may not necessarily be completely filled.

numindexfields

Number of fields used for the primary index. The fields do always start with field number 1.

codepage

The DOS codepage which was used for encoding fields with character data. If the target encoding is not set with px_set_targetencoding() this will be the encoding for character fields when records are being accessed with px_get_record() or px_retrieve_record().

See Also

  • px_numfields() - Returns number of fields in a database
  • px_numrecords() - Returns number of records in a database

px_get_field
px_get_parameter
Paradox Functions


Gets a parameter

px_get_info
px_get_record
Paradox Functions
PHP Manual

px_get_parameter

(PECL paradox >= 1.1.0)

px_get_parameter — Gets a parameter

Description

string px_get_parameter ( resource $pxdoc , string $name )

Gets various parameters.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

The name can be one of the following:

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields with px_get_record() or px_retrieve_record() is recoded into the targetencoding. If it is not set, then the data will be delivered as stored in the database file.

inputencoding

The encoding of the input data which is to be stored into the database. When storing data of character fields in the database, the data is expected to be delivered in this encoding.

Return Values

Returns the value of the parameter or FALSE on failure.

px_get_info
px_get_record
Paradox Functions


Returns record of paradox database

px_get_parameter
px_get_schema
Paradox Functions
PHP Manual

px_get_record

(PECL paradox >= 1.0.0)

px_get_record — Returns record of paradox database

Description

array px_get_record ( resource $pxdoc , int $num [, int $mode = 0 ] )

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

mode

The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys of the returned array into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp (PX_FIELD_TIMESTAMP) and date (PX_FIELD_DATE) are floating point respectively int values counting milliseconds respectively days starting at the beginning of julian calendar. Use the functions px-timestamp2string() and px-date2string() to convert them into a character representation.

Return Values

Returns the num 'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

See Also

  • px_retrieve_record() - Returns record of paradox database

px_get_parameter
px_get_schema
Paradox Functions


Returns the database schema

px_get_record
px_get_value
Paradox Functions
PHP Manual

px_get_schema

(PECL paradox >= 1.0.0)

px_get_schema — Returns the database schema

Description

array px_get_schema ( resource $pxdoc [, int $mode = 0 ] )

px_get_schema() returns the database schema.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

mode

If the optional mode is PX_KEYTOLOWER or PX_KEYTOUPPER the keys of the returned array will be converted to lower or upper case. If mode is 0 or not passed at all, then the key name will be identical to the field name.

Return Values

Returns the schema of a database file as an associated array. The key name is equal to the field name. Each array element is itself an associated array containing the two fields type and size. type is one of the constants in table Constants for field types. size is the number of bytes this field consumes in the record. The total of all field sizes is equal to the record size as it can be retrieved with px-get-info().

px_get_record
px_get_value
Paradox Functions


Gets a value

px_get_schema
px_insert_record
Paradox Functions
PHP Manual

px_get_value

(PECL paradox >= 1.1.0)

px_get_value — Gets a value

Description

float px_get_value ( resource $pxdoc , string $name )

Gets various values.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

Return Values

Returns the value of the parameter or FALSE on failure.

px_get_schema
px_insert_record
Paradox Functions


Inserts record into paradox database

px_get_value
px_new
Paradox Functions
PHP Manual

px_insert_record

(PECL paradox >= 1.4.0)

px_insert_record — Inserts record into paradox database

Description

int px_insert_record ( resource $pxdoc , array $data )

Inserts a new record into the database. The record is not necessarily inserted at the end of the database, but may be inserted at any position depending on where the first free slot is found.

The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.

Most field values can be passed as its equivalent php type e.g. a long value is used for fields of type PX_FIELD_LONG, PX_FIELD_SHORT and PX_FIELD_AUTOINC, a double values is used for fields of type PX_FIELD_CURRENCY and PX_FIELD_NUMBER. Field values for blob and alpha fields are passed as strings.

Fields of type PX_FIELD_TIME and PX_FIELD_DATE both require a long value. In the first case this is the number of milliseconds since midnight. In the second case this is the number of days since 1.1.0000. Below there are two examples to convert the current date or timestamp into a value suitable for one of paradox's date/time fields.

Note: This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

data

Associated or indexed array containing the field values as e.g. returned by px_retrieve_record().

Return Values

Returns FALSE on failure or the record number in case of success.

Examples

Example #1 Set the date/time fields in a paradox database to the current date/time

<?php
$px = px_new();
$fp = fopen("test.db", "w+");
px_create_fp($px, $fp, array(array("timestamp", "@"), array("time", "T"), array("date", "D")));

$curdate = getdate();
$jd = gregoriantojd($curdate["mon"], $curdate["mday"], $curdate["year"]);
$days = $jd - 1721425; /* Number of days between 1.1.4714 b.c. and 1.1.0000 */
$secs = $curdate["hours"]*3600 + $curdate["minutes"]*60 + $curdate["seconds"];
px_insert_record($px, array($days*86400000.0 + $secs*1000.0, $secs*1000.0, $days));

$curtimestamp = microtime(true);
$days = (int) ($curtimestamp/86400);
$secs = $curtimestamp - ($days * 86400.0);
$days += 2440588; /* Number of days between 1.1.4714 b.c. and 1.1.1970 */
$days -= 1721425; /* Number of days between 1.1.4714 b.c. and 1.1.0000 */
px_insert_record($px, array($days*86400000.0 + $secs*1000.0, $secs*1000.0, $days));
for($i=0; $i<2; $i++) {
    $rec = px_retrieve_record($px, $i);
    echo px_timestamp2string($px, $rec["timestamp"], "n/d/Y H:i:s")."\n";
    echo px_date2string($px, $rec["date"], "n/d/Y")."\n";
}
px_close($px);
px_delete($px);
?>

The above example will output:

2/21/2006 21:42:30
2/21/2006
2/21/2006 20:42:30
2/21/2006

The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain milli seconds.

See Also

px_update_record() - Updates record in paradox database

px_get_value
px_new
Paradox Functions


Create a new paradox object

px_insert_record
px_numfields
Paradox Functions
PHP Manual

px_new

(PECL paradox >= 1.0.0)

px_new — Create a new paradox object

Description

resource px_new ( void )

Create a new paradox object. You will have to call this function before any further functions. px_new() does not create any file on the disk, it just creates an instance of a paradox object. This function must not be called if the object oriented interface is used. Use new paradox_db() instead.

Return Values

Returns FALSE on failure.

Examples

Example #1 Opening a Paradox database

<?php
if(!$pxdoc = px_new()) {
  /* Error handling */
}
$fp = fopen("test.db", "r");
if(!px_open_fp($pxdoc, $fp)) {
  /* Error handling */
}
// ...
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

If you prefer the object oriented API, then the above example will look like the following.

Example #2 Opening a Paradox database

<?php
$fp = fopen("test.db", "r");
$pxdoc = new paradox_db();
if(!$pxdoc->open_fp($fp)) {
  /* Error handling */
}
// ...
$pxdoc->close();
fclose($fp);
?>

See Also

  • px_delete() - Deletes resource of paradox database
  • px_open_fp() - Open paradox database

px_insert_record
px_numfields
Paradox Functions


Returns number of fields in a database

px_new
px_numrecords
Paradox Functions
PHP Manual

px_numfields

(PECL paradox >= 1.0.0)

px_numfields — Returns number of fields in a database

Description

int px_numfields ( resource $pxdoc )

Get the number of fields in a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns the number of fields in a database file. The return value of this function is identical to the element numfields in the array returned by px_get_info().

px_new
px_numrecords
Paradox Functions


Returns number of records in a database

px_numfields
px_open_fp
Paradox Functions
PHP Manual

px_numrecords

(PECL paradox >= 1.0.0)

px_numrecords — Returns number of records in a database

Description

int px_numrecords ( resource $pxdoc )

Get the number of records in a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns the number of records in a database file. The return value of this function is identical to the element numrecords in the array returned by px_get_info().

px_numfields
px_open_fp
Paradox Functions


Open paradox database

px_numrecords
px_put_record
Paradox Functions
PHP Manual

px_open_fp

(PECL paradox >= 1.0.0)

px_open_fp — Open paradox database

Description

bool px_open_fp ( resource $pxdoc , resource $file )

Open an existing paradox database file. The actual file has to be opened before with fopen(). This function can also be used to open primary index files and tread them like a paradox database. This is supported for those who would like to investigate a primary index. It cannot be used to accelerate access to a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

file

file is the return value from fopen() with the actual database file as parameter. Make sure the database is writable if you plan to update or insert records.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fopen() - Opens file or URL
  • The example at px_new() - Create a new paradox object

px_numrecords
px_put_record
Paradox Functions


Stores record into paradox database

px_open_fp
px_retrieve_record
Paradox Functions
PHP Manual

px_put_record

(PECL paradox >= 1.0.0)

px_put_record — Stores record into paradox database

Description

bool px_put_record ( resource $pxdoc , array $record [, int $recpos = -1 ] )

Stores a record into a paradox database. The record is always added at the end of the database, regardless of any free slots. Use px_insert_record() to add a new record into the first free slot found in the database.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

record

Associated or indexed array containing the field values as e.g. returned by px_retrieve_record().

recpos

This optional parameter may be used to specify a record number greater than the current number of records in the database. The function will add as many empty records as needed. There is hardly any need for this parameter.

Return Values

Returns TRUE on success or FALSE on failure.

px_open_fp
px_retrieve_record
Paradox Functions


Returns record of paradox database

px_put_record
px_set_blob_file
Paradox Functions
PHP Manual

px_retrieve_record

(PECL paradox >= 1.4.0)

px_retrieve_record — Returns record of paradox database

Description

array px_retrieve_record ( resource $pxdoc , int $num [, int $mode = 0 ] )

This function is very similar to px_get_record() but uses internally a different approach to retrieve the data. It relies on pxlib for reading each single field value, which usually results in support for more field types.

Note: This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

mode

The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp is a floating point value also counting milliseconds starting at the beginning of julian calendar.

Return Values

Returns the num 'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

See Also

  • px_get_record() - Returns record of paradox database

px_put_record
px_set_blob_file
Paradox Functions


Sets the file where blobs are read from

px_retrieve_record
px_set_parameter
Paradox Functions
PHP Manual

px_set_blob_file

(PECL paradox >= 1.3.0)

px_set_blob_file — Sets the file where blobs are read from

Description

bool px_set_blob_file ( resource $pxdoc , string $filename )

Sets the name of the file where blobs are going to be read from or written into. Without calling this function, px_get_record() or px_retrieve_record() will only return data in blob fields if the data is part of the record and not stored in the blob file. Blob data is stored in the record if it is small enough to fit in the size of the blob field.

Calling px_put_record(),
px_insert_record(), or
px_update_record() without calling
px_set_blob_file() will result in truncated blob fields
unless the data fits into the database file.

Calling this function twice will close the first blob file and open the new one.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

filename

The name of the file. Its extension should be .MB.

Return Values

Returns TRUE on success or FALSE on failure.

px_retrieve_record
px_set_parameter
Paradox Functions


Sets a parameter

px_set_blob_file
px_set_tablename
Paradox Functions
PHP Manual

px_set_parameter

(PECL paradox >= 1.1.0)

px_set_parameter — Sets a parameter

Description

bool px_set_parameter ( resource $pxdoc , string $name , string $value )

Sets various parameters.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

Depending on the parameter you want to set, name can be one of the following.

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.

inputencoding

The encoding of the input data which is to be stored into the database.

value

The value of parameter to set. For inputencoding and targetencoding this must be the name of the encoding as understood by iconv or recode, e.g. iso-8859-1, utf-8, cp850.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • px_get_info() - Return lots of information about a paradox file to determine the DOS code page.

px_set_blob_file
px_set_tablename
Paradox Functions


Sets the name of a table (deprecated)

px_set_parameter
px_set_targetencoding
Paradox Functions
PHP Manual

px_set_tablename

(PECL paradox >= 1.0.0)

px_set_tablename — Sets the name of a table (deprecated)

Description

void px_set_tablename ( resource $pxdoc , string $name )

Sets the table name of a paradox database, which was created with px_create_fp(). This function is deprecated use px_set_parameter() instead.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

tablename

The name of the table. If it is not set explicitly it will be set to the name of the database file.

Return Values

Returns NULL on success or FALSE on failure.

See Also

px_set_parameter() - Sets a parameter

px_set_parameter
px_set_targetencoding
Paradox Functions


Sets the encoding for character fields (deprecated)

px_set_tablename
px_set_value
Paradox Functions
PHP Manual

px_set_targetencoding

(PECL paradox >= 1.0.0)

px_set_targetencoding — Sets the encoding for character fields (deprecated)

Description

bool px_set_targetencoding ( resource $pxdoc , string $encoding )

Set the encoding for data retrieved from a character field. All character fields will be recoded to the encoding set by this function. If the encoding is not set, the character data will be returned in the DOS code page encoding as specified in the database file. The encoding can be any string identifier known to iconv or recode. On Unix systems run iconv -l for a list of available encodings.

This function is deprecated and should be replaced by calling px_set_parameter().

See also px_get_info() to determine the DOS code page as stored in the database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

encoding

The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.

Return Values

Returns FALSE if the encoding could not be set, e.g. the encoding is unknown, or pxlib does not support recoding at all. In the second case a warning will be issued.

See Also

px_set_parameter() - Sets a parameter

px_set_tablename
px_set_value
Paradox Functions


Sets a value

px_set_targetencoding
px_timestamp2string
Paradox Functions
PHP Manual

px_set_value

(PECL paradox >= 1.1.0)

px_set_value — Sets a value

Description

bool px_set_value ( resource $pxdoc , string $name , float $value )

Sets various values.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

value

Return Values

Returns TRUE on success or FALSE on failure.

See Also

px_set_parameter() - Sets a parameter

px_set_targetencoding
px_timestamp2string
Paradox Functions


Converts the timestamp into a string.

px_set_value
px_update_record
Paradox Functions
PHP Manual

px_timestamp2string

(PECL paradox >= 1.4.0)

px_timestamp2string — Converts the timestamp into a string.

Description

string px_timestamp2string ( resource $pxdoc , float $value , string $format )

Turns a timestamp as it stored in the paradox file into human readable format. Paradox timestamps are the number of miliseconds since 0001-01-02. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the following example.

Parameters

pxdoc

Resource identifier of the paradox database.

value

Value as stored in paradox database field of type PX_FIELD_TIME, or PX_FIELD_TIMESTAMP.

format

String format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, H, h, G, g, i, s, A, a, L).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Turn a paradox timestamp into a human readable form

<?php
$px = px_new();

/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days = 700000;

/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";

/* Turn it into a timestamp as it stored in a paradox database */
/* Timestamps are stored in miliseconds since 0001-01-02 */
$stamp = $days * 86400.0 * 1000.0;
/* Add one hour */
$stamp += 3600000.0;
/* The following will output '7/15/1917 01:00:00'. */
echo px_timestamp2string($px, $stamp, "n/d/Y H:i:s")."\n";

px_delete($px);
?>

The above example will output:

7/15/1917
7/15/1917 01:00:00

The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain miliseconds.

See Also

  • px_date2string() - Converts a date into a string.
  • jdtogregorian() - Converts Julian Day Count to Gregorian date

px_set_value
px_update_record
Paradox Functions


Updates record in paradox database

px_timestamp2string
PostgreSQL
Paradox Functions
PHP Manual

px_update_record

(PECL paradox >= 1.4.0)

px_update_record — Updates record in paradox database

Description

bool px_update_record ( resource $pxdoc , array $data , int $num )

Updates an exiting record in the database. The record starts at 0.

The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.

Note: This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

data

Associated array containing the field values as returned by px_retrieve_record().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

px_insert_record() - Inserts record into paradox database

px_timestamp2string
PostgreSQL
Paradox Functions


Converts the radian number to the equivalent number in degrees

pow
rand
Math Functions
PHP Manual

rad2deg

(PHP 4, PHP 5)

rad2deg — Converts the radian number to the equivalent number in degrees

Description

float rad2deg ( float $number )

This function converts number from radian to degrees.

Parameters

number

A radian value

Return Values

The equivalent of number in degrees

Examples

Example #1 rad2deg() example

<?php

echo rad2deg(M_PI_4); // 45

?>

See Also

  • deg2rad() - Converts the number in degrees to the radian equivalent

pow
rand
Math Functions


Creates a Radius handle for accounting

Radius Functions
radius_add_server
Radius Functions
PHP Manual

radius_acct_open

(PECL radius >= 1.1.0)

radius_acct_open — Creates a Radius handle for accounting

Description

resource radius_acct_open ( void )

Return Values

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

Examples

Example #1 radius_acct_open() example

<?php
$res = radius_acct_open ()
    or die ("Could not create handle");
print("Handle successfully created");
?>

Radius Functions
radius_add_server
Radius Functions


Adds a server

radius_acct_open
radius_auth_open
Radius Functions
PHP Manual

radius_add_server

(PECL radius >= 1.1.0)

radius_add_server — Adds a server

Description

bool radius_add_server ( resource $radius_handle , string $hostname , int $port , string $secret , int $timeout , int $max_tries )

radius_add_server() may be called multiple times, and it may be used together with radius_config(). At most 10 servers may be specified. When multiple servers are given, they are tried in round-robin fashion until a valid response is received, or until each server's max_tries limit has been reached.

Parameters

radius_handle

hostname

The hostname parameter specifies the server host, either as a fully qualified domain name or as a dotted-quad IP address in text form.

port

The port specifies the UDP port to contact on the server. If port is given as 0, the library looks up the radius/udp or radacct/udp service in the network services database, and uses the port found there. If no entry is found, the library uses the standard Radius ports, 1812 for authentication and 1813 for accounting.

secret

The shared secret for the server host is passed to the secret parameter. The Radius protocol ignores all but the leading 128 bytes of the shared secret.

timeout

The timeout for receiving replies from the server is passed to the timeout parameter, in units of seconds.

max_tries

The maximum number of repeated requests to make before giving up is passed into the max_tries .

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 radius_add_server() example

<?php
if (!radius_add_server($res, 'radius.example.com', 1812, 'testing123', 3, 3)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br>";
    exit;
}
?>

See Also

  • radius_config() - Causes the library to read the given configuration file

radius_acct_open
radius_auth_open
Radius Functions


Creates a Radius handle for authentication

radius_add_server
radius_close
Radius Functions
PHP Manual

radius_auth_open

(PECL radius >= 1.1.0)

radius_auth_open — Creates a Radius handle for authentication

Description

resource radius_auth_open ( void )

Return Values

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

Examples

Example #1 radius_auth_open() example

<?php
$radh = radius_auth_open()
    or die ("Could not create handle");
echo "Handle successfully created";
?>

radius_add_server
radius_close
Radius Functions


Frees all ressources

radius_auth_open
radius_config
Radius Functions
PHP Manual

radius_close

(PECL radius >= 1.1.0)

radius_close — Frees all ressources

Description

bool radius_close ( resource $radius_handle )

It is not needed to call this function because php frees all resources at the end of each request.

Return Values

Returns TRUE on success or FALSE on failure.

radius_auth_open
radius_config
Radius Functions


Causes the library to read the given configuration file

radius_close
radius_create_request
Radius Functions
PHP Manual

radius_config

(PECL radius >= 1.1.0)

radius_config — Causes the library to read the given configuration file

Description

bool radius_config ( resource $radius_handle , string $file )

Before issuing any Radius requests, the library must be made aware of the servers it can contact. The easiest way to configure the library is to call radius_config(). radius_config() causes the library to read a configuration file whose format is described in » radius.conf.

Parameters

radius_handle

file

The pathname of the configuration file is passed as the file argument to radius_config(). The library can also be configured programmatically by calls to radius_add_server().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • radius_add_server() - Adds a server

radius_close
radius_create_request
Radius Functions


Create accounting or authentication request

radius_config
radius_cvt_addr
Radius Functions
PHP Manual

radius_create_request

(PECL radius >= 1.1.0)

radius_create_request — Create accounting or authentication request

Description

bool radius_create_request ( resource $radius_handle , int $type )

A Radius request consists of a code specifying the kind of request, and zero or more attributes which provide additional information. To begin constructing a new request, call radius_create_request().

Note: Attention: You must call this function, before you can put any attribute!

Parameters

radius_handle

type

Type is RADIUS_ACCESS_REQUEST or RADIUS_ACCOUNTING_REQUEST.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 radius_create_request() example

<?php
if (!radius_create_request($res, RADIUS_ACCESS_REQUEST)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

See Also

  • radius_send_request() - Sends the request and waites for a reply

radius_config
radius_cvt_addr
Radius Functions


Converts raw data to IP-Address

radius_create_request
radius_cvt_int
Radius Functions
PHP Manual

radius_cvt_addr

(PECL radius >= 1.1.0)

radius_cvt_addr — Converts raw data to IP-Address

Description

string radius_cvt_addr ( string $data )

Examples

Example #1 radius_cvt_addr() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    switch ($attr) {

    case RADIUS_FRAMED_IP_ADDRESS:
        $ip = radius_cvt_addr($data);
        echo "IP: $ip<br>\n";
        break;

    case RADIUS_FRAMED_IP_NETMASK:
        $mask = radius_cvt_addr($data);
        echo "MASK: $mask<br>\n";
        break;
    }
}
?>

See Also

  • radius_cvt_int() - Converts raw data to integer
  • radius_cvt_string() - Converts raw data to string

radius_create_request
radius_cvt_int
Radius Functions


Converts raw data to integer

radius_cvt_addr
radius_cvt_string
Radius Functions
PHP Manual

radius_cvt_int

(PECL radius >= 1.1.0)

radius_cvt_int — Converts raw data to integer

Description

int radius_cvt_int ( string $data )

Examples

Example #1 radius_cvt_int() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    switch ($attr) {

    case RADIUS_FRAMED_MTU:
        $mtu = radius_cvt_int($data);
        echo "MTU: $mtu<br>\n";
        break;
    }
}
?>

See Also

  • radius_cvt_addr() - Converts raw data to IP-Address
  • radius_cvt_string() - Converts raw data to string

radius_cvt_addr
radius_cvt_string
Radius Functions


Converts raw data to string

radius_cvt_int
radius_demangle_mppe_key
Radius Functions
PHP Manual

radius_cvt_string

(PECL radius >= 1.1.0)

radius_cvt_string — Converts raw data to string

Description

string radius_cvt_string ( string $data )

Examples

Example #1 radius_cvt_string() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];

    switch ($attr) {

    case RADIUS_FILTER_ID:
        $id = radius_cvt_string($data);
        echo "Filter ID: $id<br>\n";
        break;
    }
}
?>

See Also

  • radius_cvt_addr() - Converts raw data to IP-Address
  • radius_cvt_int() - Converts raw data to integer

radius_cvt_int
radius_demangle_mppe_key
Radius Functions


Demangles data

radius_demangle_mppe_key
radius_get_attr
Radius Functions
PHP Manual

radius_demangle

(PECL radius >= 1.2.0)

radius_demangle — Demangles data

Description

string radius_demangle ( resource $radius_handle , string $mangled )

Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security reasons, and must be demangled before you can use them.

Return Values

Returns the demangled string, or FALSE on error.

radius_demangle_mppe_key
radius_get_attr
Radius Functions


Derives mppe-keys from mangled data

radius_cvt_string
radius_demangle
Radius Functions
PHP Manual

radius_demangle_mppe_key

(PECL radius >= 1.2.0)

radius_demangle_mppe_key — Derives mppe-keys from mangled data

Description

string radius_demangle_mppe_key ( resource $radius_handle , string $mangled )

When using MPPE with MS-CHAPv2, the send- and recv-keys are mangled (see » RFC 2548), however this function is useless, because I don't think that there is or will be a PPTP-MPPE implementation in PHP.

Return Values

Returns the demangled string, or FALSE on error.

radius_cvt_string
radius_demangle
Radius Functions


Extracts an attribute

radius_demangle
radius_get_vendor_attr
Radius Functions
PHP Manual

radius_get_attr

(PECL radius >= 1.1.0)

radius_get_attr — Extracts an attribute

Description

mixed radius_get_attr ( resource $radius_handle )

Like Radius requests, each response may contain zero or more attributes. After a response has been received successfully by radius_send_request(), its attributes can be extracted one by one using radius_get_attr(). Each time radius_get_attr() is called, it gets the next attribute from the current response.

Return Values

Returns an associative array containing the attribute-type and the data, or error number <= 0.

Examples

Example #1 radius_get_attr() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];
    printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));
}
?>

See Also

  • radius_put_attr() - Attaches a binary attribute
  • radius_get_vendor_attr() - Extracts a vendor specific attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute
  • radius_send_request() - Sends the request and waites for a reply

radius_demangle
radius_get_vendor_attr
Radius Functions


Extracts a vendor specific attribute

radius_get_attr
radius_put_addr
Radius Functions
PHP Manual

radius_get_vendor_attr

(PECL radius >= 1.1.0)

radius_get_vendor_attr — Extracts a vendor specific attribute

Description

array radius_get_vendor_attr ( string $data )

If radius_get_attr() returns RADIUS_VENDOR_SPECIFIC, radius_get_vendor_attr() may be called to determine the vendor.

Return Values

Returns an associative array containing the attribute-type, vendor and the data, or FALSE on error.

Examples

Example #1 radius_get_vendor_attr() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];
    printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));
    if ($attr == RADIUS_VENDOR_SPECIFIC) {

        $resv = radius_get_vendor_attr($data);
        if (is_array($resv)) {
            $vendor = $resv['vendor'];
            $attrv = $resv['attr'];
            $datav = $resv['data'];
            printf("Got Vendor Attr:%d %d Bytes %s\n", $attrv, strlen($datav), bin2hex($datav));
        }

    }
}
?>

See Also

  • radius_get_attr() - Extracts an attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute

radius_get_attr
radius_put_addr
Radius Functions


Attaches an IP-Address attribute

radius_get_vendor_attr
radius_put_attr
Radius Functions
PHP Manual

radius_put_addr

(PECL radius >= 1.1.0)

radius_put_addr — Attaches an IP-Address attribute

Description

bool radius_put_addr ( resource $radius_handle , int $type , string $addr )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

radius_get_vendor_attr
radius_put_attr
Radius Functions


Attaches a binary attribute

radius_put_addr
radius_put_int
Radius Functions
PHP Manual

radius_put_attr

(PECL radius >= 1.1.0)

radius_put_attr — Attaches a binary attribute

Description

bool radius_put_attr ( resource $radius_handle , int $type , string $value )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 radius_put_attr() example

<?php
mt_srand(time());
$chall = mt_rand();
$chapval = md5(pack('Ca*',1 , 'sepp' . $chall));
$pass = pack('CH*', 1, $chapval);
if (!radius_put_attr($res, RADIUS_CHAP_PASSWORD, $pass)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

See Also

  • radius_get_attr() - Extracts an attribute
  • radius_get_vendor_attr() - Extracts a vendor specific attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute

radius_put_addr
radius_put_int
Radius Functions


Attaches an integer attribute

radius_put_attr
radius_put_string
Radius Functions
PHP Manual

radius_put_int

(PECL radius >= 1.1.0)

radius_put_int — Attaches an integer attribute

Description

bool radius_put_int ( resource $radius_handle , int $type , int $value )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 radius_put_int() example

<?php
if (!radius_put_int($res, RAD_FRAMED_PROTOCOL, RAD_PPP)) {
   echo 'RadiusError:' . radius_strerror($res). "\n<br />";
   exit;
}
?>

See Also

  • radius_put_string() - Attaches a string attribute
  • radius_put_vendor_int() - Attaches a vendor specific integer attribute
  • radius_put_vendor_string() - Attaches a vendor specific string attribute

radius_put_attr
radius_put_string
Radius Functions


Attaches a string attribute

radius_put_int
radius_put_vendor_addr
Radius Functions
PHP Manual

radius_put_string

(PECL radius >= 1.1.0)

radius_put_string — Attaches a string attribute

Description

bool radius_put_string ( resource $radius_handle , int $type , string $value )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 radius_put_string() example

<?php
if (!radius_put_string($res, RADIUS_USER_NAME, 'billy')) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

See Also

  • radius_put_int() - Attaches an integer attribute
  • radius_put_vendor_int() - Attaches a vendor specific integer attribute
  • radius_put_vendor_string() - Attaches a vendor specific string attribute

radius_put_int
radius_put_vendor_addr
Radius Functions


Attaches a vendor specific IP-Address attribute

radius_put_string
radius_put_vendor_attr
Radius Functions
PHP Manual

radius_put_vendor_addr

(PECL radius >= 1.1.0)

radius_put_vendor_addr — Attaches a vendor specific IP-Address attribute

Description

bool radius_put_vendor_addr ( resource $radius_handle , int $vendor , int $type , string $addr )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

radius_put_string
radius_put_vendor_attr
Radius Functions


Attaches a vendor specific binary attribute

radius_put_vendor_addr
radius_put_vendor_int
Radius Functions
PHP Manual

radius_put_vendor_attr

(PECL radius >= 1.1.0)

radius_put_vendor_attr — Attaches a vendor specific binary attribute

Description

bool radius_put_vendor_attr ( resource $radius_handle , int $vendor , int $type , string $value )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 radius_put_vendor_attr() example

<?php
if (!radius_put_vendor_attr($res, RADIUS_VENDOR_MICROSOFT, RAD_MICROSOFT_MS_CHAP_CHALLENGE, $challenge)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

See Also

  • radius_get_vendor_attr() - Extracts a vendor specific attribute

radius_put_vendor_addr
radius_put_vendor_int
Radius Functions


Attaches a vendor specific integer attribute

radius_put_vendor_attr
radius_put_vendor_string
Radius Functions
PHP Manual

radius_put_vendor_int

(PECL radius >= 1.1.0)

radius_put_vendor_int — Attaches a vendor specific integer attribute

Description

bool radius_put_vendor_int ( resource $radius_handle , int $vendor , int $type , int $value )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • radius_put_vendor_string() - Attaches a vendor specific string attribute

radius_put_vendor_attr
radius_put_vendor_string
Radius Functions


Attaches a vendor specific string attribute

radius_put_vendor_int
radius_request_authenticator
Radius Functions
PHP Manual

radius_put_vendor_string

(PECL radius >= 1.1.0)

radius_put_vendor_string — Attaches a vendor specific string attribute

Description

bool radius_put_vendor_string ( resource $radius_handle , int $vendor , int $type , string $value )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • radius_put_vendor_int() - Attaches a vendor specific integer attribute

radius_put_vendor_int
radius_request_authenticator
Radius Functions


Returns the request authenticator

radius_put_vendor_string
radius_send_request
Radius Functions
PHP Manual

radius_request_authenticator

(PECL radius >= 1.1.0)

radius_request_authenticator — Returns the request authenticator

Description

string radius_request_authenticator ( resource $radius_handle )

The request authenticator is needed for demangling mangled data like passwords and encryption-keys.

Return Values

Returns the request authenticator as string, or FALSE on error.

See Also

  • radius_demangle() - Demangles data

radius_put_vendor_string
radius_send_request
Radius Functions


Sends the request and waites for a reply

radius_request_authenticator
radius_server_secret
Radius Functions
PHP Manual

radius_send_request

(PECL radius >= 1.1.0)

radius_send_request — Sends the request and waites for a reply

Description

int radius_send_request ( resource $radius_handle )

After the Radius request has been constructed, it is sent by radius_send_request().

The radius_send_request() function sends the request and waits for a valid reply, retrying the defined servers in round-robin fashion as necessary.

Return Values

If a valid response is received, radius_send_request() returns the Radius code which specifies the type of the response. This will typically be RADIUS_ACCESS_ACCEPT, RADIUS_ACCESS_REJECT, or RADIUS_ACCESS_CHALLENGE. If no valid response is received, radius_send_request() returns FALSE.

See Also

  • radius_create_request() - Create accounting or authentication request

radius_request_authenticator
radius_server_secret
Radius Functions


Returns the shared secret

radius_send_request
radius_strerror
Radius Functions
PHP Manual

radius_server_secret

(PECL radius >= 1.1.0)

radius_server_secret — Returns the shared secret

Description

string radius_server_secret ( resource $radius_handle )

The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys.

Return Values

Returns the server's shared secret as string, or FALSE on error.

radius_send_request
radius_strerror
Radius Functions


Returns an error message

radius_server_secret
Date and Time Related Extensions
Radius Functions
PHP Manual

radius_strerror

(PECL radius >= 1.1.0)

radius_strerror — Returns an error message

Description

string radius_strerror ( resource $radius_handle )

If Radius-functions fail then they record an error message. This error message can be retrieved with this function.

Return Values

Returns error messages as string from failed radius functions.

radius_server_secret
Date and Time Related Extensions
Radius Functions


Generate a random integer

rad2deg
round
Math Functions
PHP Manual

rand

(PHP 4, PHP 5)

rand — Generate a random integer

Description

int rand ( void )
int rand ( int $min , int $max )

If called without the optional min , max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).

Note: On some platforms (such as Windows), getrandmax() is only 32768. If you require a range larger than 32768, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead.

Parameters

min

The lowest value to return (default: 0)

max

The highest value to return (default: getrandmax())

Return Values

A pseudo random value between min (or 0) and max (or getrandmax(), inclusive).

Changelog

Version | Description
4.2.0 | The random number generator is seeded automatically.

Examples

Example #1 rand() example

<?php
echo rand() . "\n";
echo rand() . "\n";

echo rand(5, 15);
?>

The above example will output something similar to:

7771
22264
11

See Also

  • srand() - Seed the random number generator
  • getrandmax() - Show largest possible random value
  • mt_rand() - Generate a better random value

rad2deg
round
Math Functions


Alias of exif_read_data

exif_thumbnail
GD
Exif Functions
PHP Manual

read_exif_data

(PHP 4 >= 4.0.1, PHP 5)

read_exif_data — Alias of exif_read_data()

Description

This function is an alias of: exif_read_data().

exif_thumbnail
GD
Exif Functions


Read entry from directory handle

opendir
rewinddir
Directory Functions
PHP Manual

readdir

(PHP 4, PHP 5)

readdir — Read entry from directory handle

Description

string readdir ([ resource $dir_handle ] )

Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

Parameters

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Return Values

Returns the filename on success or FALSE on failure.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 List all files in a directory

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").

<?php

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Files:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle))) {
        echo "$file\n";
    }

    /* This is the WRONG way to loop over the directory. */
    while ($file = readdir($handle)) {
        echo "$file\n";
    }

    closedir($handle);
}
?>

Example #2 List all files in the current directory and strip out . and ..

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>

See Also

  • is_dir() - Tells whether the filename is a directory
  • glob() - Find pathnames matching a pattern
  • opendir() - Open directory handle
  • scandir() - List files and directories inside the specified path

opendir
rewinddir
Directory Functions


Outputs a file

popen
readlink
Filesystem Functions
PHP Manual

readfile

(PHP 4, PHP 5)

readfile — Outputs a file

Description

int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

Reads a file and writes it to the output buffer.

Parameters

filename

The filename being read.

use_include_path

You can use the optional second parameter and set it to TRUE, if you want to search for the file in the include_path, too.

context

A context stream resource.

Return Values

Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed.

Examples

Example #1 Forcing a download using readfile()

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

The above example will output something similar to:

Open / Save dialogue

Notes

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Stream Functions.

See Also

  • fpassthru() - Output all remaining data on a file pointer
  • file() - Reads entire file into an array
  • fopen() - Opens file or URL
  • include() - include
  • require() - require
  • virtual() - Perform an Apache sub-request
  • file_get_contents() - Reads entire file into a string
  • List of Supported Protocols/Wrappers

popen
readlink
Filesystem Functions


Output a gz-file

gzwrite
zlib_get_coding_type
Zlib Functions
PHP Manual

readgzfile

(PHP 4, PHP 5)

readgzfile — Output a gz-file

Description

int readgzfile ( string $filename [, int $use_include_path = 0 ] )

Reads a file, decompresses it and writes it to standard output.

readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.

Parameters

filename

The file name. This file will be opened from the filesystem and its contents written to standard output.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Return Values

Returns the number of (uncompressed) bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readgzfile, an error message is printed.

See Also

  • gzpassthru() - Output all remaining data on a gz-file pointer
  • gzfile() - Read entire gz-file into an array
  • gzopen() - Open gz-file

gzwrite
zlib_get_coding_type
Zlib Functions


Reads a line

readline_write_history
Compression and Archive Extensions
Readline Functions
PHP Manual

readline

(PHP 4, PHP 5)

readline — Reads a line

Description

string readline ([ string $prompt ] )

Reads a single line from the user. You must add this line to the history yourself using readline_add_history().

Parameters

prompt

You may specify a string with which to prompt the user.

Return Values

Returns a single string from the user. The line returned has the ending newline removed.

Examples

Example #1 readline() Example

<?php
//get 3 commands from user
for ($i=0; $i < 3; $i++) {
        $line = readline("Command: ");
        readline_add_history($line);
}

//dump history
print_r(readline_list_history());

//dump variables
print_r(readline_info());
?>

readline_write_history
Compression and Archive Extensions
Readline Functions


Adds a line to the history

Readline Functions
readline_callback_handler_install
Readline Functions
PHP Manual

readline_add_history

(PHP 4, PHP 5)

readline_add_history — Adds a line to the history

Description

bool readline_add_history ( string $line )

This function adds a line to the command line history.

Parameters

line

The line to be added in the history.

Return Values

Returns TRUE on success or FALSE on failure.

Readline Functions
readline_callback_handler_install
Readline Functions


Initializes the readline callback interface and terminal, prints the prompt and returns immediately

readline_add_history
readline_callback_handler_remove
Readline Functions
PHP Manual

readline_callback_handler_install

(PHP 5 >= 5.1.0)

readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately

Description

bool readline_callback_handler_install ( string $prompt , callback $callback )

Sets up a readline callback interface then prints prompt and immediately returns. Calling this function twice without removing the previous callback interface will automatically and conveniently overwrite the old interface.

The callback feature is useful when combined with stream_select() as it allows interleaving of IO and user input, unlike readline().

Parameters

prompt

The prompt message.

callback

The callback function takes one parameter; the user input returned.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Readline Callback Interface Example

<?php
function rl_callback($ret)
{
    global $c, $prompting;

    echo "You entered: $ret\n";
    $c++;

    if ($c > 10) {
        $prompting = false;
        readline_callback_handler_remove();
    } else {
        readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
    }
}

$c = 1;
$prompting = true;

readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');

while ($prompting) {
    $w = NULL;
    $e = NULL;
    $n = stream_select($r = array(STDIN), $w, $e, null);
    if ($n && in_array(STDIN, $r)) {
        // read a character, will call the callback when a newline is entered
        readline_callback_read_char();
    }
}

echo "Prompting disabled. All done.\n";
?>

See Also

  • readline_callback_handler_remove() - Removes a previously installed callback handler and restores terminal settings
  • readline_callback_read_char() - Reads a character and informs the readline callback interface when a line is received
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

readline_add_history
readline_callback_handler_remove
Readline Functions


Removes a previously installed callback handler and restores terminal settings

readline_callback_handler_install
readline_callback_read_char
Readline Functions
PHP Manual

readline_callback_handler_remove

(PHP 5 >= 5.1.0)

readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings

Description

bool readline_callback_handler_remove ( void )

Removes a previously installed callback handler and restores terminal settings.

Return Values

Returns TRUE if a previously installed callback handler was removed, or FALSE if one could not be found.

Examples

See readline_callback_handler_install() for an example of how to use the readline callback interface.

See Also

  • readline_callback_handler_install() - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
  • readline_callback_read_char() - Reads a character and informs the readline callback interface when a line is received

readline_callback_handler_install
readline_callback_read_char
Readline Functions


Reads a character and informs the readline callback interface when a line is received

readline_callback_handler_remove
readline_clear_history
Readline Functions
PHP Manual

readline_callback_read_char

(PHP 5 >= 5.1.0)

readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received

Description

void readline_callback_read_char ( void )

Reads a character of user input. When a line is received, this function informs the readline callback interface installed using readline_callback_handler_install() that a line is ready for input.

Return Values

No value is returned.

Examples

See readline_callback_handler_install() for an example of how to use the readline callback interface.

See Also

  • readline_callback_handler_install() - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
  • readline_callback_handler_remove() - Removes a previously installed callback handler and restores terminal settings

readline_callback_handler_remove
readline_clear_history
Readline Functions


Clears the history

readline_callback_read_char
readline_completion_function
Readline Functions
PHP Manual

readline_clear_history

(PHP 4, PHP 5)

readline_clear_history — Clears the history

Description

bool readline_clear_history ( void )

This function clears the entire command line history.

Return Values

Returns TRUE on success or FALSE on failure.

readline_callback_read_char
readline_completion_function
Readline Functions


Registers a completion function

readline_clear_history
readline_info
Readline Functions
PHP Manual

readline_completion_function

(PHP 4, PHP 5)

readline_completion_function — Registers a completion function

Description

bool readline_completion_function ( callback $function )

This function registers a completion function. This is the same kind of functionality you'd get if you hit your tab key while using Bash.

Parameters

function

You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches.

Return Values

Returns TRUE on success or FALSE on failure.

readline_clear_history
readline_info
Readline Functions


Gets/sets various internal readline variables

readline_completion_function
readline_list_history
Readline Functions
PHP Manual

readline_info

(PHP 4, PHP 5)

readline_info — Gets/sets various internal readline variables

Description

mixed readline_info ([ string $varname [, string $newvalue ]] )

Gets or sets various internal readline variables.

Parameters

varname

A variable name.

newvalue

If provided, this will be the new value of the setting.

Return Values

If called with no parameters, this function returns an array of values for all the setting readline uses. The elements will be indexed by the following values: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, and terminal_name.

If called with one or two parameters, the old value is returned.

readline_completion_function
readline_list_history
Readline Functions


Lists the history

readline_info
readline_on_new_line
Readline Functions
PHP Manual

readline_list_history

(PHP 4, PHP 5)

readline_list_history — Lists the history

Description

array readline_list_history ( void )

Gets the entire command line history.

Return Values

Returns an array of the entire command line history. The elements are indexed by integers starting at zero.

readline_info
readline_on_new_line
Readline Functions


Inform readline that the cursor has moved to a new line

readline_list_history
readline_read_history
Readline Functions
PHP Manual

readline_on_new_line

(PHP 5 >= 5.1.0)

readline_on_new_line — Inform readline that the cursor has moved to a new line

Description

void readline_on_new_line ( void )

Tells readline that the cursor has moved to a new line.

Return Values

No value is returned.

readline_list_history
readline_read_history
Readline Functions


Reads the history

readline_on_new_line
readline_redisplay
Readline Functions
PHP Manual

readline_read_history

(PHP 4, PHP 5)

readline_read_history — Reads the history

Description

bool readline_read_history ([ string $filename ] )

This function reads a command history from a file.

Parameters

filename

Path to the filename containing the command history.

Return Values

Returns TRUE on success or FALSE on failure.

readline_on_new_line
readline_redisplay
Readline Functions


Redraws the display

readline_read_history
readline_write_history
Readline Functions
PHP Manual

readline_redisplay

(PHP 5 >= 5.1.0)

readline_redisplay — Redraws the display

Description

void readline_redisplay ( void )

Redraws readline to redraw the display.

Return Values

No value is returned.

readline_read_history
readline_write_history
Readline Functions


Writes the history

readline_redisplay
readline
Readline Functions
PHP Manual

readline_write_history

(PHP 4, PHP 5)

readline_write_history — Writes the history

Description

bool readline_write_history ([ string $filename ] )

This function writes the command history to a file.

Parameters

filename

Path to the saved file.

Return Values

Returns TRUE on success or FALSE on failure.

readline_redisplay
readline
Readline Functions


Returns the target of a symbolic link

readfile
realpath_cache_get
Filesystem Functions
PHP Manual

readlink

(PHP 4, PHP 5)

readlink — Returns the target of a symbolic link

Description

string readlink ( string $path )

readlink() does the same as the readlink C function.

Parameters

path

The symbolic link path.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Return Values

Returns the contents of the symbolic link path or FALSE on error.

Examples

Example #1 readlink() example

<?php

// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');

?>

See Also

  • is_link() - Tells whether the filename is a symbolic link
  • symlink() - Creates a symbolic link
  • linkinfo() - Gets information about a link

readfile
realpath_cache_get
Filesystem Functions


Returns canonicalized absolute pathname

realpath_cache_size
rename
Filesystem Functions
PHP Manual

realpath

(PHP 4, PHP 5)

realpath — Returns canonicalized absolute pathname

Description

string realpath ( string $path )

realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and return the canonicalized absolute pathname.

Parameters

path

The path being checked.

Return Values

Returns the canonicalized absolute pathname on success. The resulting path will have no symbolic link, '/./' or '/../' components.

realpath() returns FALSE on failure, e.g. if the file does not exist.

Note: The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE.

Changelog

Version | Description
5.3.0 | Prior to this release realpath() would not fail on *BSD systems if only the last last path component did not exist.

Examples

Example #1 realpath() example

<?php
chdir('/var/www/');
echo realpath('./../../etc/passwd');
?>

The above example will output:

/etc/passwd

Example #2 realpath() on Windows

On windows realpath() will change unix style paths to windows style.

<?php
echo realpath('/windows/system32');
?>

The above example will output:

C:\WINDOWS\System32

See Also

  • basename() - Returns filename component of path
  • dirname() - Returns directory name component of path
  • pathinfo() - Returns information about a file path

realpath_cache_size
rename
Filesystem Functions


Get realpath cache entries

readlink
realpath_cache_size
Filesystem Functions
PHP Manual

realpath_cache_get

(No version information available, might only be in SVN)

realpath_cache_get — Get realpath cache entries

Description

array realpath_cache_get ( void )

Get the contents of the realpath cache.

Return Values

Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the cache.

Examples

Example #1 realpath_cache_get() example

<?php
var_dump(realpath_cache_get());
?>

The above example will output something similar to:

array(2) {
  ["/test"]=>
  array(4) {
    ["key"]=>
    int(123456789)
    ["is_dir"]=>
    bool(true)
    ["realpath"]=>
    string(5) "/test"
    ["expires"]=>
    int(1260318939)
  }
  ["/test/test.php"]=>
  array(4) {
    ["key"]=>
    int(987654321)
    ["is_dir"]=>
    bool(false)
    ["realpath"]=>
    string(12) "/root/test.php"
    ["expires"]=>
    int(1260318939)
  }
}

See Also

  • realpath_cache_size() - Get realpath cache size

readlink
realpath_cache_size
Filesystem Functions


Get realpath cache size

realpath_cache_get
realpath
Filesystem Functions
PHP Manual

realpath_cache_size

(No version information available, might only be in SVN)

realpath_cache_size — Get realpath cache size

Description

int realpath_cache_size ( void )

Get the amount of memory used by the realpath cache.

Return Values

Returns how much memory realpath cache is using.

Examples

Example #1 realpath_cache_size() example

<?php
var_dump(realpath_cache_size());
?>

The above example will output something similar to:

int(412)

See Also

  • realpath_cache_get() - Get realpath cache entries

realpath_cache_get
realpath
Filesystem Functions


Alias of recode_string

recode_string
Unicode
Recode Functions
PHP Manual

recode

(PHP 4, PHP 5)

recode — Alias of recode_string()

Description

This function is an alias of: recode_string().

recode_string
Unicode
Recode Functions


Recode from file to file according to recode request

Recode Functions
recode_string
Recode Functions
PHP Manual

recode_file

(PHP 4, PHP 5)

recode_file — Recode from file to file according to recode request

Description

bool recode_file ( string $request , resource $input , resource $output )

Recode the file referenced by file handle input into the file referenced by file handle output according to the recode request .

Parameters

request

The desired recode request type

input

A local file handle resource for the input

output

A local file handle resource for the output

Return Values

Returns FALSE, if unable to comply, TRUE otherwise.

Examples

Example #1 Basic recode_file() example

<?php
$input = fopen('input.txt', 'r');
$output = fopen('output.txt', 'w');
recode_file("us..flat", $input, $output);
?>

Notes

This function does not currently process file handles referencing remote files (URLs). Both file handles must refer to local files.

See Also

  • fopen() - Opens file or URL

Recode Functions
recode_string
Recode Functions


Recode a string according to a recode request

recode_file
recode
Recode Functions
PHP Manual

recode_string

(PHP 4, PHP 5)

recode_string — Recode a string according to a recode request

Description

string recode_string ( string $request , string $string )

Recode the string string according to the recode request request .

Parameters

request

The desired recode request type

string

The string to be recoded

Return Values

Returns the recoded string or FALSE, if unable to perform the recode request.

Examples

Example #1 Basic recode_string() example

<?php
echo recode_string("us..flat", "The following character has a diacritical mark: &aacute;");
?>

Notes

A simple recode request may be "lat1..iso646-de".

See Also

  • The GNU Recode documentation of your installation for detailed instructions about recode requests.

recode_file
recode
Recode Functions


Renames a file or directory

realpath
rewind
Filesystem Functions
PHP Manual

rename

(PHP 4, PHP 5)

rename — Renames a file or directory

Description

bool rename ( string $oldname , string $newname [, resource $context ] )

Attempts to rename oldname to newname .

Parameters

oldname

Note: The old name. The wrapper used in oldname must match the wrapper used in newname .

newname

The new name.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Stream Functions.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | rename() can now also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support rename().
4.3.3 | rename() is now able to rename files across partitions on *nix based systems.

Examples

Example #1 Example with rename()

<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

See Also

  • copy() - Copies file
  • unlink() - Deletes a file
  • move_uploaded_file() - Moves an uploaded file to a new location

realpath
rewind
Filesystem Functions


Renames orig_name to new_name in the global function table

override_function
bcompiler
APD Functions
PHP Manual

rename_function

(PECL apd >= 0.2)

rename_function — Renames orig_name to new_name in the global function table

Description

bool rename_function ( string $original_name , string $new_name )

Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.

Parameters

original_name

The original function name.

new_name

The new name for the original_name function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rename_function() example

<?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?>

override_function
bcompiler
APD Functions


require

return
include
Control Structures
PHP Manual

require()

require() is identical to include() except upon failure it will also produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

See the include() documentation for how this works.

return
include
Control Structures


require_once

include
include_once
Control Structures
PHP Manual

require_once()

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

See the include_once() documentation for information about the _once behaviour, and how it differs from its non _once siblings.

include
include_once
Control Structures


Restores the previous error handler function

error_reporting
restore_exception_handler
Error Handling Functions
PHP Manual

restore_error_handler

(PHP 4 >= 4.0.1, PHP 5)

restore_error_handler — Restores the previous error handler function

Description

bool restore_error_handler ( void )

Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function).

Return Values

This function always returns TRUE.

Examples

Example #1 restore_error_handler() example

Decide if unserialize() caused an error, then restore the original error handler.

<?php
function unserialize_handler($errno, $errstr)
{
    echo "Invalid serialized value.\n";
}

$serialized = 'foo';
set_error_handler('unserialize_handler');
$original = unserialize($serialized);
restore_error_handler();
?>

The above example will output:

Invalid serialized value.

Notes

Note: Calling restore_error_handler() from the error_handler function is ignored.

See Also

  • error_reporting() - Sets which PHP errors are reported
  • set_error_handler() - Sets a user-defined error handler function
  • restore_exception_handler() - Restores the previously defined exception handler function
  • trigger_error() - Generates a user-level error/warning/notice message

error_reporting
restore_exception_handler
Error Handling Functions


Restores the previously defined exception handler function

restore_error_handler
set_error_handler
Error Handling Functions
PHP Manual

restore_exception_handler

(PHP 5)

restore_exception_handler — Restores the previously defined exception handler function

Description

bool restore_exception_handler ( void )

Used after changing the exception handler function using set_exception_handler(), to revert to the previous exception handler (which could be the built-in or a user defined function).

Return Values

This function always returns TRUE.

Examples

Example #1 restore_exception_handler() example

<?php
    function exception_handler_1(Exception $e)
    {
        echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
    }

    function exception_handler_2(Exception $e)
    {
        echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
    }

    set_exception_handler('exception_handler_1');
    set_exception_handler('exception_handler_2');

    restore_exception_handler();

    throw new Exception('This triggers the first exception handler...');
?>

The above example will output:

[exception_handler_1] This triggers the first exception handler...

See Also

  • set_exception_handler() - Sets a user-defined exception handler function
  • set_error_handler() - Sets a user-defined error handler function
  • restore_error_handler() - Restores the previous error handler function
  • error_reporting() - Sets which PHP errors are reported

restore_error_handler
set_error_handler
Error Handling Functions


Restores the value of the include_path configuration option

putenv
set_include_path
PHP Options/Info Functions
PHP Manual

restore_include_path

(PHP 4 >= 4.3.0, PHP 5)

restore_include_path — Restores the value of the include_path configuration option

Description

void restore_include_path ( void )

Restores the include_path configuration option back to its original master value as set in php.ini

Return Values

No value is returned.

Examples

Example #1 restore_include_path() example

<?php

echo get_include_path();  // .:/usr/local/lib/php

set_include_path('/inc');

echo get_include_path();  // /inc

// Works as of PHP 4.3.0
restore_include_path();

// Works in all PHP versions
ini_restore('include_path');

echo get_include_path();  // .:/usr/local/lib/php

?>

See Also

  • ini_restore() - Restores the value of a configuration option
  • get_include_path() - Gets the current include_path configuration option
  • set_include_path() - Sets the include_path configuration option
  • include() - include

putenv
set_include_path
PHP Options/Info Functions


return

If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.

For more information, see Returning values.

Note: Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.

Note: If no parameter is supplied, then the parentheses must be omitted and NULL will be returned. Calling return() with parentheses but with no arguments will result in a parse error.

Note: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).

declare
require
Control Structures


Rewind the position of a file pointer

rename
rmdir
Filesystem Functions
PHP Manual

rewind

(PHP 4, PHP 5)

rewind — Rewind the position of a file pointer

Description

bool rewind ( resource $handle )

Sets the file position indicator for handle to the beginning of the file stream.

Note: If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rewind() overwriting example

<?php
$handle = fopen('output.txt', 'r+');

fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);

echo fread($handle, filesize('output.txt'));

fclose($handle);
?>

The above example will output something similar to:

Foolly long sentence.

See Also

  • fread() - Binary-safe file read
  • fseek() - Seeks on a file pointer
  • ftell() - Returns the current position of the file read/write pointer
  • fwrite() - Binary-safe file write

rename
rmdir
Filesystem Functions


Rewind directory handle

readdir
scandir
Directory Functions
PHP Manual

rewinddir

(PHP 4, PHP 5)

rewinddir — Rewind directory handle

Description

void rewinddir ([ resource $dir_handle ] )

Resets the directory stream indicated by dir_handle to the beginning of the directory.

Parameters

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

readdir
scandir
Directory Functions


Removes directory

rewind
set_file_buffer
Filesystem Functions
PHP Manual

rmdir

(PHP 4, PHP 5)

rmdir — Removes directory

Description

bool rmdir ( string $dirname [, resource $context ] )

Attempts to remove the directory named by dirname . The directory must be empty, and the relevant permissions must permit this.

Parameters

dirname

Path to the directory.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Stream Functions.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | As of PHP 5.0.0 rmdir() can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support rmdir().

Examples

Example #1 rmdir() example

<?php
if (!is_dir('examples')) {
    mkdir('examples');
}

rmdir('examples');
?>

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • is_dir() - Tells whether the filename is a directory
  • mkdir() - Makes directory
  • unlink() - Deletes a file

rewind
set_file_buffer
Filesystem Functions


Rounds a float

rand
sin
Math Functions
PHP Manual

round

(PHP 4, PHP 5)

round — Rounds a float

Description

float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

Note: PHP doesn't handle strings like "12,300.2" correctly by default. See converting from strings.

Parameters

val

The value to round

precision

The optional number of decimal digits to round to.

mode

One of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD.

Return Values

The rounded value

Examples

Example #1 round() examples

<?php
echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
?>

Example #2 mode() examples

<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP);   // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD);  // 9

echo round(8.5, 0, PHP_ROUND_HALF_UP);   // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD);  // 9
?>

Changelog

Version | Description
5.3.0 | The mode parameter was introduced.
5.2.7 | The inner workings of round() was changed to conform to the C99 standard.

See Also

  • ceil() - Round fractions up
  • floor() - Round fractions down
  • number_format() - Format a number with grouped thousands

rand
sin
Math Functions


Closes an RPM file

RPM Reader Functions
rpm_get_tag
RPM Reader Functions
PHP Manual

rpm_close

(PECL rpmreader >= 0.1.0)

rpm_close — Closes an RPM file

Description

bool rpm_close ( resource $rpmr )

rpm_close() will close an RPM file pointer.

Parameters

rpmr

A file pointer resource successfully opened by rpm_open().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rpm_close() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

See Also

  • rpm_open() - Opens an RPM file

RPM Reader Functions
rpm_get_tag
RPM Reader Functions


Retrieves a header tag from an RPM file

rpm_close
rpm_is_valid
RPM Reader Functions
PHP Manual

rpm_get_tag

(PECL rpmreader >= 0.1.0)

rpm_get_tag — Retrieves a header tag from an RPM file

Description

mixed rpm_get_tag ( resource $rpmr , int $tagnum )

rpm_get_tag() will retrieve a given tag from the RPM file's header and return it.

Parameters

rpmr

A file pointer resource successfully opened by rpm_open().

tagnum

The tag number to retrieve from the RPM header. This value can be specified using the list of constants defined by this module.

Return Values

The return value can be of various types depending on the tagnum supplied to the function.

Examples

Example #1 rpm_get_tag() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

$name = rpm_get_tag($rpmr, RPMREADER_NAME);
echo "$name<br>\n";

rpm_close($rpmr);

?>

See Also

  • rpm_open() - Opens an RPM file
  • rpm_close() - Closes an RPM file

rpm_close
rpm_is_valid
RPM Reader Functions


Tests a filename for validity as an RPM file

rpm_get_tag
rpm_open
RPM Reader Functions
PHP Manual

rpm_is_valid

(PECL rpmreader >= 0.1.0)

rpm_is_valid — Tests a filename for validity as an RPM file

Description

bool rpm_is_valid ( string $filename )

rpm_is_valid() will test an RPM file for validity as an RPM file. This is not the same as rpm_open() as it only checks the file for validity but does not return a file pointer to be used by further functions.

Parameters

filename

The filename of the RPM file you wish to check for validity.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rpm_is_valid() example

<?php

$file = "/path/to/file.rpm";

if (rpm_is_valid($file)) {
    echo "File is recognized as an RPM file.<br>\n";
}
else {
    echo "File is not recognized as an RPM file.<br>\n";
}

?>

rpm_get_tag
rpm_open
RPM Reader Functions


Opens an RPM file

rpm_is_valid
rpm_version
RPM Reader Functions
PHP Manual

rpm_open

(PECL rpmreader >= 0.1.0)

rpm_open — Opens an RPM file

Description

resource rpm_open ( string $filename )

rpm_open() will open an RPM file and will determine if the file is a valid RPM file.

Parameters

filename

The filename of the RPM file you wish to open.

Return Values

If the open succeeds, then rpm_open() will return a file pointer resource to the newly opened file. On error, the function will return FALSE.

Examples

Example #1 rpm_open() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

See Also

  • rpm_close() - Closes an RPM file

rpm_is_valid
rpm_version
RPM Reader Functions


Returns a string representing the current version of the rpmreader extension

rpm_open
SWF
RPM Reader Functions
PHP Manual

rpm_version

(PECL rpmreader >= 0.3.0)

rpm_version — Returns a string representing the current version of the rpmreader extension

Description

string rpm_version ( void )

rpm_version() will return the current version of the rpmreader extension.

Return Values

rpm_version() will return a string representing the rpmreader version currently loaded in PHP.

Examples

Example #1 rpm_version() example

<?php

$rpmr_ver = rpm_version();

echo "$rpmr_ver<br />\n";

?>

rpm_open
SWF
RPM Reader Functions


Convert a base class to an inherited class, add ancestral methods when appropriate

Runkit_Sandbox_Parent
runkit_class_emancipate
runkit Functions
PHP Manual

runkit_class_adopt

(PECL runkit >= 0.7.0)

runkit_class_adopt — Convert a base class to an inherited class, add ancestral methods when appropriate

Description

bool runkit_class_adopt ( string $classname , string $parentname )

Parameters

classname

Name of class to be adopted

parentname

Parent class which child class is extending

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A runkit_class_adopt() example

<?php
class myParent {
  function parentFunc() {
    echo "Parent Function Output\n";
  }
}

class myChild {
}

runkit_class_adopt('myChild','myParent');
myChild::parentFunc();
?>

The above example will output:

Parent Function Output

See Also

  • runkit_class_emancipate() - Convert an inherited class to a base class, removes any method whose scope is ancestral

Runkit_Sandbox_Parent
runkit_class_emancipate
runkit Functions


Convert an inherited class to a base class, removes any method whose scope is ancestral

runkit_class_adopt
runkit_constant_add
runkit Functions
PHP Manual

runkit_class_emancipate

(PECL runkit >= 0.7.0)

runkit_class_emancipate — Convert an inherited class to a base class, removes any method whose scope is ancestral

Description

bool runkit_class_emancipate ( string $classname )

Parameters

classname

Name of class to emancipate

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A runkit_class_emancipate() example

<?php
class myParent {
  function parentFunc () {
    echo "Parent Function Output\n";
  }
}
class myChild extends myParent {
}

myChild::parentFunc();
runkit_class_emancipate('myChild');
myChild::parentFunc();
?>

The above example will output:

Parent Function Output
Fatal error: Call to undefined function:  parentFunc() in example.php on line 12

See Also

  • runkit_class_adopt() - Convert a base class to an inherited class, add ancestral methods when appropriate

runkit_class_adopt
runkit_constant_add
runkit Functions


Similar to define(), but allows defining in class definitions as well

runkit_class_emancipate
runkit_constant_redefine
runkit Functions
PHP Manual

runkit_constant_add

(PECL runkit >= 0.7.0)

runkit_constant_add — Similar to define(), but allows defining in class definitions as well

Description

bool runkit_constant_add ( string $constname , mixed $value )

Parameters

constname

Name of constant to declare. Either a string to indicate a global constant, or classname::constname to indicate a class constant.

value

NULL, Bool, Long, Double, String, or Resource value to store in the new constant.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • define() - Defines a named constant
  • runkit_constant_redefine() - Redefine an already defined constant
  • runkit_constant_remove() - Remove/Delete an already defined constant

runkit_class_emancipate
runkit_constant_redefine
runkit Functions


Redefine an already defined constant

runkit_constant_add
runkit_constant_remove
runkit Functions
PHP Manual

runkit_constant_redefine

(PECL runkit >= 0.7.0)

runkit_constant_redefine — Redefine an already defined constant

Description

bool runkit_constant_redefine ( string $constname , mixed $newvalue )

Parameters

constname

Constant to redefine. Either string indicating global constant, or classname::constname indicating class constant.

newvalue

New value to assign to constant.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • runkit_constant_add() - Similar to define(), but allows defining in class definitions as well
  • runkit_constant_remove() - Remove/Delete an already defined constant

runkit_constant_add
runkit_constant_remove
runkit Functions


Remove/Delete an already defined constant

runkit_constant_redefine
runkit_function_add
runkit Functions
PHP Manual

runkit_constant_remove

(PECL runkit >= 0.7.0)

runkit_constant_remove — Remove/Delete an already defined constant

Description

bool runkit_constant_remove ( string $constname )

Parameters

constname

Name of constant to remove. Either a string indicating a global constant, or classname::constname indicating a class constant.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • define() - Defines a named constant
  • runkit_constant_add() - Similar to define(), but allows defining in class definitions as well
  • runkit_constant_redefine() - Redefine an already defined constant

runkit_constant_redefine
runkit_function_add
runkit Functions


Add a new function, similar to create_function

runkit_constant_remove
runkit_function_copy
runkit Functions
PHP Manual

runkit_function_add

(PECL runkit >= 0.7.0)

runkit_function_add — Add a new function, similar to create_function()

Description

bool runkit_function_add ( string $funcname , string $arglist , string $code )

Parameters

funcname

Name of function to be created

arglist

Comma separated argument list

code

Code making up the function

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A runkit_function_add() example

<?php
runkit_function_add('testme','$a,$b','echo "The value of a is $a\n"; echo "The value of b is $b\n";');
testme(1,2);
?>

The above example will output:

The value of a is 1
The value of b is 2

See Also

  • create_function() - Create an anonymous (lambda-style) function
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition
  • runkit_method_add() - Dynamically adds a new method to a given class

runkit_constant_remove
runkit_function_copy
runkit Functions


Copy a function to a new function name

runkit_function_add
runkit_function_redefine
runkit Functions
PHP Manual

runkit_function_copy

(PECL runkit >= 0.7.0)

runkit_function_copy — Copy a function to a new function name

Description

bool runkit_function_copy ( string $funcname , string $targetname )

Parameters

funcname

Name of existing function

targetname

Name of new function to copy definition to

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A runkit_function_copy() example

<?php
function original() {
  echo "In a function\n";
}
runkit_function_copy('original','duplicate');
original();
duplicate();
?>

The above example will output:

In a function
In a function

See Also

  • runkit_function_add() - Add a new function, similar to create_function
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition

runkit_function_add
runkit_function_redefine
runkit Functions


Replace a function definition with a new implementation

runkit_function_copy
runkit_function_remove
runkit Functions
PHP Manual

runkit_function_redefine

(PECL runkit >= 0.7.0)

runkit_function_redefine — Replace a function definition with a new implementation

Description

bool runkit_function_redefine ( string $funcname , string $arglist , string $code )

Note: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in php.ini.

Parameters

funcname

Name of function to redefine

arglist

New list of arguments to be accepted by function

code

New code implementation

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A runkit_function_redefine() example

<?php
function testme() {
  echo "Original Testme Implementation\n";
}
testme();
runkit_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?>

The above example will output:

Original Testme Implementation
New Testme Implementation

See Also

  • runkit_function_add() - Add a new function, similar to create_function
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition

runkit_function_copy
runkit_function_remove
runkit Functions


Remove a function definition

runkit_function_redefine
runkit_function_rename
runkit Functions
PHP Manual

runkit_function_remove

(PECL runkit >= 0.7.0)

runkit_function_remove — Remove a function definition

Description

bool runkit_function_remove ( string $funcname )

Note: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in php.ini.

Parameters

funcname

Name of function to be deleted

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • runkit_function_add() - Add a new function, similar to create_function
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_rename() - Change a function's name

runkit_function_redefine
runkit_function_rename
runkit Functions


Change a function's name

runkit_function_remove
runkit_import
runkit Functions
PHP Manual

runkit_function_rename

(PECL runkit >= 0.7.0)

runkit_function_rename — Change a function's name

Description

bool runkit_function_rename ( string $funcname , string $newname )

Note: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in php.ini.

Parameters

funcname

Current function name

newname

New function name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • runkit_function_add() - Add a new function, similar to create_function
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_remove() - Remove a function definition

runkit_function_remove
runkit_import
runkit Functions


Process a PHP file importing function and class definitions, overwriting where appropriate

runkit_function_rename
runkit_lint_file
runkit Functions
PHP Manual

runkit_import

(PECL runkit >= 0.7.0)

runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate

Description

bool runkit_import ( string $filename [, int $flags = RUNKIT_IMPORT_CLASS_METHODS ] )

Similar to include() however any code residing outside of a function or class is simply ignored. Additionally, depending on the value of flags , any functions or classes which already exist in the currently running environment will be automatically overwritten by their new definitions.

Parameters

filename

Filename to import function and class definitions from

flags

Bitwise OR of the RUNKIT_IMPORT_* family of constants.

Return Values

Returns TRUE on success or FALSE on failure.

runkit_function_rename
runkit_lint_file
runkit Functions


Check the PHP syntax of the specified php code

runkit_lint_file
runkit_method_add
runkit Functions
PHP Manual

runkit_lint

(PECL runkit >= 0.7.0)

runkit_lint — Check the PHP syntax of the specified php code

Description

bool runkit_lint ( string $code )

The runkit_lint() function performs a syntax (lint) check on the specified php code testing for scripting errors. This is similar to using php -l from the command line except runkit_lint() accepts actual code rather than a filename.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Parameters

code

PHP Code to be lint checked

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • runkit_lint_file() - Check the PHP syntax of the specified file

runkit_lint_file
runkit_method_add
runkit Functions


Check the PHP syntax of the specified file

runkit_import
runkit_lint
runkit Functions
PHP Manual

runkit_lint_file

(PECL runkit >= 0.7.0)

runkit_lint_file — Check the PHP syntax of the specified file

Description

bool runkit_lint_file ( string $filename )

The runkit_lint_file() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Parameters

filename

File containing PHP Code to be lint checked

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • runkit_lint() - Check the PHP syntax of the specified php code

runkit_import
runkit_lint
runkit Functions


Dynamically adds a new method to a given class

runkit_lint
runkit_method_copy
runkit Functions
PHP Manual

runkit_method_add

(PECL runkit >= 0.7.0)

runkit_method_add — Dynamically adds a new method to a given class

Description

bool runkit_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags = RUNKIT_ACC_PUBLIC ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

classname

The class to which this method will be added

methodname

The name of the method to add

args

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when methodname is called

flags

The type of method to create, can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE

Note: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 runkit_method_add() example

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
runkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    RUNKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

The above example will output:

16

See Also

  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_add() - Add a new function, similar to create_function

runkit_lint
runkit_method_copy
runkit Functions


Copies a method from class to another

runkit_method_add
runkit_method_redefine
runkit Functions
PHP Manual

runkit_method_copy

(PECL runkit >= 0.7.0)

runkit_method_copy — Copies a method from class to another

Description

bool runkit_method_copy ( string $dClass , string $dMethod , string $sClass [, string $sMethod ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

dClass

Destination class for copied method

dMethod

Destination method name

sClass

Source class of the method to copy

sMethod

Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 runkit_method_copy() example

<?php
class Foo {
    function example() {
        return "foo!\n";
    }
}

class Bar {
    // initially, no methods
}

// copy the example() method from the Foo class to the Bar class, as baz()
runkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

The above example will output:

foo!

See Also

  • runkit_method_add() - Dynamically adds a new method to a given class
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_copy() - Copy a function to a new function name

runkit_method_add
runkit_method_redefine
runkit Functions


Dynamically changes the code of the given method

runkit_method_copy
runkit_method_remove
runkit Functions
PHP Manual

runkit_method_redefine

(PECL runkit >= 0.7.0)

runkit_method_redefine — Dynamically changes the code of the given method

Description

bool runkit_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags = RUNKIT_ACC_PUBLIC ] )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

classname

The class in which to redefine the method

methodname

The name of the method to redefine

args

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when methodname is called

flags

The redefined method can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE

Note: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 runkit_method_redefine() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
runkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    RUNKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

The above example will output:

Before: foo!
After: bar!

See Also

  • runkit_method_add() - Dynamically adds a new method to a given class
  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_redefine() - Replace a function definition with a new implementation

runkit_method_copy
runkit_method_remove
runkit Functions


Dynamically removes the given method

runkit_method_redefine
runkit_method_rename
runkit Functions
PHP Manual

runkit_method_remove

(PECL runkit >= 0.7.0)

runkit_method_remove — Dynamically removes the given method

Description

bool runkit_method_remove ( string $classname , string $methodname )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

classname

The class in which to remove the method

methodname

The name of the method to remove

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 runkit_method_remove() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }

    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
runkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

The above example will output:

bar

See Also

  • runkit_method_add() - Dynamically adds a new method to a given class
  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_remove() - Remove a function definition

runkit_method_redefine
runkit_method_rename
runkit Functions


Dynamically changes the name of the given method

runkit_method_remove
runkit_return_value_used
runkit Functions
PHP Manual

runkit_method_rename

(PECL runkit >= 0.7.0)

runkit_method_rename — Dynamically changes the name of the given method

Description

bool runkit_method_rename ( string $classname , string $methodname , string $newname )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Parameters

classname

The class in which to rename the method

methodname

The name of the method to rename

newname

The new name to give to the renamed method

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 runkit_method_rename() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
runkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?>

The above example will output:

foo!

See Also

  • runkit_method_add() - Dynamically adds a new method to a given class
  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_function_rename() - Change a function's name

runkit_method_remove
runkit_return_value_used
runkit Functions


Determines if the current functions return value will be used

runkit_method_rename
runkit_sandbox_output_handler
runkit Functions
PHP Manual

runkit_return_value_used

(PECL runkit >= 0.8.0)

runkit_return_value_used — Determines if the current functions return value will be used

Description

bool runkit_return_value_used ( void )

Return Values

Returns TRUE if the function's return value is used by the calling scope, otherwise FALSE

Examples

Example #1 runkit_return_value_used() example

<?php
function foo() {
  var_dump(runkit_return_value_used());
}

foo();
$f = foo();
?>

The above example will output:

bool(false)
bool(true)

runkit_method_rename
runkit_sandbox_output_handler
runkit Functions


Specify a function to capture and/or process output from a runkit sandbox

runkit_return_value_used
runkit_superglobals
runkit Functions
PHP Manual

runkit_sandbox_output_handler

(PECL runkit >= 0.7.0)

runkit_sandbox_output_handler — Specify a function to capture and/or process output from a runkit sandbox

Description

mixed runkit_sandbox_output_handler ( object $sandbox [, mixed $callback ] )

Ordinarily, anything output (such as with echo() or print()) will be output as though it were printed from the parent's scope. Using runkit_sandbox_output_handler() however, output generated by the sandbox (including errors), can be captured by a function outside of the sandbox.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Note: Deprecated
As of runkit version 0.5, this function is deprecated and is scheduled to be removed from the package prior to a 1.0 release. The output handler for a given Runkit_Sandbox instance may be read/set using the array offset syntax shown on the Runkit_Sandbox class definition page.

Parameters

sandbox

Object instance of Runkit_Sandbox class on which to set output handling.

callback

Name of a function which expects one parameter. Output generated by sandbox will be passed to this callback. Anything returned by the callback will be displayed normally. If this parameter is not passed then output handling will not be changed. If a non-truth value is passed, output handling will be disabled and will revert to direct display.

Return Values

Returns the name of the previously defined output handler callback, or FALSE if no handler was previously defined.

Examples

Example #1 Feeding output to a variable

<?php
function capture_output($str) {
  $GLOBALS['sandbox_output'] .= $str;

  return '';
}

$sandbox_output = '';

$php = new Runkit_Sandbox();
runkit_sandbox_output_handler($php, 'capture_output');
$php->echo("Hello\n");
$php->eval('var_dump("Excuse me");');
$php->die("I lost myself.");
unset($php);

echo "Sandbox Complete\n\n";
echo $sandbox_output;
?>

The above example will output:

Sandbox Complete

Hello
string(9) "Excuse me"
I lost myself.

runkit_return_value_used
runkit_superglobals
runkit Functions


Return numerically indexed array of registered superglobals

runkit_sandbox_output_handler
scream
runkit Functions
PHP Manual

runkit_superglobals

(PECL runkit >= 0.7.0)

runkit_superglobals — Return numerically indexed array of registered superglobals

Description

array runkit_superglobals ( void )

Return Values

Returns a numerically indexed array of the currently registered superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER, _ENV, _FILES

See Also

  • Variable Scope

runkit_sandbox_output_handler
scream
runkit Functions


List files and directories inside the specified path

rewinddir
Fileinfo
Directory Functions
PHP Manual

scandir

(PHP 5)

scandir — List files and directories inside the specified path

Description

array scandir ( string $directory [, int $sorting_order = 0 [, resource $context ]] )

Returns an array of files and directories from the directory .

Parameters

directory

The directory that will be scanned.

sorting_order

By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is set to non-zero, then the sort order is alphabetical in descending order.

context

For a description of the context parameter, refer to the streams section of the manual.

Return Values

Returns an array of filenames on success, or FALSE on failure. If directory is not a directory, then boolean FALSE is returned, and an error of level E_WARNING is generated.

Examples

Example #1 A simple scandir() example

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

The above example will output something similar to:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Example #2 PHP 4 alternatives to scandir()

<?php
$dir = "/tmp";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

sort($files);

print_r($files);

rsort($files);

print_r($files);

?>

The above example will output something similar to:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Notes

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the List of Supported Protocols/Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

See Also

  • opendir() - Open directory handle
  • readdir() - Read entry from directory handle
  • glob() - Find pathnames matching a pattern
  • is_dir() - Tells whether the filename is a directory
  • sort() - Sort an array

rewinddir
Fileinfo
Directory Functions


Acquire a semaphore

msg_stat_queue
sem_get
Semaphore Functions
PHP Manual

sem_acquire

(PHP 4, PHP 5)

sem_acquire — Acquire a semaphore

Description

bool sem_acquire ( resource $sem_identifier )

sem_acquire() blocks (if necessary) until the semaphore can be acquired. A process attempting to acquire a semaphore which it has already acquired will block forever if acquiring the semaphore would cause its maximum number of semaphore to be exceeded.

After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated.

Parameters

sem_identifier

sem_identifier is a semaphore resource, obtained from sem_get().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore

msg_stat_queue
sem_get
Semaphore Functions


Get a semaphore id

sem_acquire
sem_release
Semaphore Functions
PHP Manual

sem_get

(PHP 4, PHP 5)

sem_get — Get a semaphore id

Description

resource sem_get ( int $key [, int $max_acquire = 1 [, int $perm = 0666 [, int $auto_release = 1 ]]] )

sem_get() returns an id that can be used to access the System V semaphore with the given key .

A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.

Parameters

key

max_acquire

The number of processes that can acquire the semaphore simultaneously is set to max_acquire .

perm

The semaphore permissions. Actually this value is set only if the process finds it is the only process currently attached to the semaphore.

auto_release

Specifies if the semaphore should be automatically released on request shutdown.

Return Values

Returns a positive semaphore identifier on success, or FALSE on error.

Changelog

Version | Description
4.3.0 | The auto_release parameter was added.

See Also

  • sem_acquire() - Acquire a semaphore
  • sem_release() - Release a semaphore
  • ftok() - Convert a pathname and a project identifier to a System V IPC key

sem_acquire
sem_release
Semaphore Functions


Release a semaphore

sem_get
sem_remove
Semaphore Functions
PHP Manual

sem_release

(PHP 4, PHP 5)

sem_release — Release a semaphore

Description

bool sem_release ( resource $sem_identifier )

sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated.

After releasing the semaphore, sem_acquire() may be called to re-acquire it.

Parameters

sem_identifier

A Semaphore resource handle as returned by sem_get().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sem_get() - Get a semaphore id
  • sem_acquire() - Acquire a semaphore

sem_get
sem_remove
Semaphore Functions


Remove a semaphore

sem_release
shm_attach
Semaphore Functions
PHP Manual

sem_remove

(PHP 4 >= 4.1.0, PHP 5)

sem_remove — Remove a semaphore

Description

bool sem_remove ( resource $sem_identifier )

sem_remove() removes the given semaphore.

After removing the semaphore, it is no more accessible.

Parameters

sem_identifier

A semaphore resource identifier as returned by sem_get().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore
  • sem_acquire() - Acquire a semaphore

sem_release
shm_attach
Semaphore Functions


Sets a user-defined error handler function

restore_exception_handler
set_exception_handler
Error Handling Functions
PHP Manual

set_error_handler

(PHP 4 >= 4.0.1, PHP 5)

set_error_handler — Sets a user-defined error handler function

Description

mixed set_error_handler ( callback $error_handler [, int $error_types = E_ALL | E_STRICT ] )

Sets a user function (error_handler ) to handle errors in a script.

This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).

It is important to remember that the standard PHP error handler is completely bypassed for the error types specified by error_types unless the callback function returns FALSE. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.

Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

If errors occur before the script is executed (e.g. on file uploads) the custom error handler cannot be called since it is not registered at that time.

Parameters

error_handler

The user function needs to accept two parameters: the error code, and a string describing the error. Then there are three optional parameters that may be supplied: the filename in which the error occurred, the line number in which the error occurred, and the context in which the error occurred (an array that points to the active symbol table at the point the error occurred). The function can be shown as:

handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] )

errno
The first parameter, errno , contains the level of the error raised, as an integer.
errstr
The second parameter, errstr , contains the error message, as a string.
errfile
The third parameter is optional, errfile , which contains the filename that the error was raised in, as a string.
errline
The fourth parameter is optional, errline , which contains the line number the error was raised at, as an integer.
errcontext
The fifth parameter is optional, errcontext , which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context.

If the function returns FALSE then the normal error handler continues.

error_types

Can be used to mask the triggering of the error_handler function just like the error_reporting ini setting controls which errors are shown. Without this mask set the error_handler will be called for every error regardless to the setting of the error_reporting setting.

Return Values

Returns a string containing the previously defined error handler (if any). If the built-in error handler is used NULL is returned. NULL is also returned in case of an error such as an invalid callback. If the previous error handler was a class method, this function will return an indexed array with the class and the method name.

Changelog

Version | Description
5.2.0 | The error handler must return FALSE to populate $php_errormsg.
5.0.0 | The error_types parameter was introduced.
4.3.0 | Instead of a function name, an array containing an object reference and a method name can also be supplied as the error_handler .
4.0.2 | Three optional parameters for the error_handler user function was introduced. These are the filename, the line number, and the context.

Examples

Example #1 Error handling with set_error_handler() and trigger_error()

The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

<?php
// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    switch ($errno) {
    case E_USER_ERROR:
        echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
        echo "  Fatal error on line $errline in file $errfile";
        echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
        echo "Aborting...<br />\n";
        exit(1);
        break;

    case E_USER_WARNING:
        echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
        break;

    case E_USER_NOTICE:
        echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
        break;

    default:
        echo "Unknown error type: [$errno] $errstr<br />\n";
        break;
    }

    /* Don't execute PHP internal error handler */
    return true;
}

// function to test the error handling
function scale_by_log($vect, $scale)
{
    if (!is_numeric($scale) || $scale <= 0) {
        trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
    }

    if (!is_array($vect)) {
        trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
        return null;
    }

    $temp = array();
    foreach($vect as $pos => $value) {
        if (!is_numeric($value)) {
            trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
            $value = 0;
        }
        $temp[$pos] = log($scale) * $value;
    }

    return $temp;
}

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2, 3, "foo", 5.5, 43.3, 21.11);
print_r($a);

// now generate second array
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Value at position $pos is not a number, using 0 (zero) */
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - a warning\n";
/* Incorrect input vector, array of values expected */
$c = scale_by_log("not array", 2.3);
var_dump($c); // NULL

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
/* log(x) for x <= 0 is undefined, you used: scale = $scale" */
$d = scale_by_log($a, -2.5);
var_dump($d); // Never reached
?>

The above example will output something similar to:

vector a
Array
(
    [0] => 2
    [1] => 3
    [2] => foo
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
vector b - a notice (b = log(PI) * a)
<b>My NOTICE</b> [1024] Value at position 2 is not a number, using 0 (zero)<br />
Array
(
    [0] => 2.2894597716988
    [1] => 3.4341896575482
    [2] => 0
    [3] => 6.2960143721717
    [4] => 49.566804057279
    [5] => 24.165247890281
)
----
vector c - a warning
<b>My WARNING</b> [512] Incorrect input vector, array of values expected<br />
NULL
----
vector d - fatal error
<b>My ERROR</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br />
  Fatal error on line 35 in file trigger_error.php, PHP 5.2.1 (FreeBSD)<br />
Aborting...<br />

See Also

  • ErrorException
  • error_reporting() - Sets which PHP errors are reported
  • restore_error_handler() - Restores the previous error handler function
  • trigger_error() - Generates a user-level error/warning/notice message
  • error level constants
  • information about the callback type

restore_exception_handler
set_exception_handler
Error Handling Functions


Sets a user-defined exception handler function

set_error_handler
trigger_error
Error Handling Functions
PHP Manual

set_exception_handler

(PHP 5)

set_exception_handler — Sets a user-defined exception handler function

Description

callback set_exception_handler ( callback $exception_handler )

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

Parameters

exception_handler

Name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.

Return Values

Returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.

Examples

Example #1 set_exception_handler() example

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

See Also

  • restore_exception_handler() - Restores the previously defined exception handler function
  • restore_error_handler() - Restores the previous error handler function
  • error_reporting() - Sets which PHP errors are reported
  • information about the callback type
  • PHP 5 Exceptions

set_error_handler
trigger_error
Error Handling Functions


Alias of stream_set_write_buffer

rmdir
stat
Filesystem Functions
PHP Manual

set_file_buffer

(PHP 4, PHP 5)

set_file_buffer — Alias of stream_set_write_buffer()

Description

This function is an alias of: stream_set_write_buffer().

rmdir
stat
Filesystem Functions


Sets the include_path configuration option

restore_include_path
set_magic_quotes_runtime
PHP Options/Info Functions
PHP Manual

set_include_path

(PHP 4 >= 4.3.0, PHP 5)

set_include_path — Sets the include_path configuration option

Description

string set_include_path ( string $new_include_path )

Sets the include_path configuration option for the duration of the script.

Parameters

new_include_path

The new value for the include_path

Return Values

Returns the old include_path on success or FALSE on failure.

Examples

Example #1 set_include_path() example

<?php
// Works as of PHP 4.3.0
set_include_path('/inc');

// Works in all PHP versions
ini_set('include_path', '/inc');
?>

Example #2 Adding to the include path

Making use of the PATH_SEPARATOR constant, it is possible to extend the include path regardless of the operating system.

In this example we add /usr/lib/pear to the end of the existing include_path.

<?php
$path = '/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
?>

See Also

  • ini_set() - Sets the value of a configuration option
  • get_include_path() - Gets the current include_path configuration option
  • restore_include_path() - Restores the value of the include_path configuration option
  • include() - include

restore_include_path
set_magic_quotes_runtime
PHP Options/Info Functions


Sets the current active configuration setting of magic_quotes_runtime

set_include_path
set_time_limit
PHP Options/Info Functions
PHP Manual

set_magic_quotes_runtime

(PHP 4, PHP 5)

set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime

Description

bool set_magic_quotes_runtime ( bool $new_setting )

Set the current active configuration setting of magic_quotes_runtime.

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

Parameters

new_setting

FALSE for off, TRUE for on.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 set_magic_quotes_runtime() example

<?php
// Create a temporary file pointer
$fp = tmpfile();

// Write some data to the pointer
fwrite($fp, '\'PHP\' is a Recursive acronym');

// Without magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(false);

echo 'Without magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;

// With magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(true);

echo 'With magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;

// Clean up
fclose($fp);
?>

The above example will output:

Without magic_quotes_runtime: 'PHP' is a Recursive acronym
With magic_quotes_runtime: \'PHP\' is a Recursive acronym

See Also

  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc
  • get_magic_quotes_runtime() - Gets the current active configuration setting of magic_quotes_runtime

set_include_path
set_time_limit
PHP Options/Info Functions


Limits the maximum execution time

set_magic_quotes_runtime
sys_get_temp_dir
PHP Options/Info Functions
PHP Manual

set_time_limit

(PHP 4, PHP 5)

set_time_limit — Limits the maximum execution time

Description

void set_time_limit ( int $seconds )

Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

Parameters

seconds

The maximum execution time, in seconds. If set to zero, no time limit is imposed.

Return Values

No value is returned.

Notes

Warning

This function has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.

Note: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.

See Also

  • max_execution_time
  • max_input_time

set_magic_quotes_runtime
sys_get_temp_dir
PHP Options/Info Functions


Execute command via shell and return the complete output as a string

proc_terminate
system
Program execution Functions
PHP Manual

shell_exec

(PHP 4, PHP 5)

shell_exec — Execute command via shell and return the complete output as a string

Description

string shell_exec ( string $cmd )

This function is identical to the backtick operator.

Parameters

cmd

The command that will be executed.

Return Values

The output from the executed command.

Examples

Example #1 A shell_exec() example

<?php
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
?>

Notes

Note: This function is disabled when PHP is running in safe mode.

See Also

  • exec() - Execute an external program
  • escapeshellcmd() - Escape shell metacharacters

proc_terminate
system
Program execution Functions


Creates or open a shared memory segment

sem_remove
shm_detach
Semaphore Functions
PHP Manual

shm_attach

(PHP 4, PHP 5)

shm_attach — Creates or open a shared memory segment

Description

resource shm_attach ( int $key [, int $memsize [, int $perm ]] )

shm_attach() returns an id that can be used to access the System V shared memory with the given key , the first call creates the shared memory segment with memsize and the optional perm-bits perm .

A second call to shm_attach() for the same key will return a different shared memory identifier, but both identifiers access the same underlying shared memory. memsize and perm will be ignored.

Parameters

key

A numeric shared memory segment ID

memsize

The memory size. If not provided, default to the sysvshm.init_mem in the php.ini, otherwise 10000 bytes.

perm

The optional permission bits. Default to 0666.

Return Values

Returns a shared memory segment identifier.

See Also

  • shm_detach() - Disconnects from shared memory segment
  • ftok() - Convert a pathname and a project identifier to a System V IPC key

sem_remove
shm_detach
Semaphore Functions


Disconnects from shared memory segment

shm_attach
shm_get_var
Semaphore Functions
PHP Manual

shm_detach

(PHP 4, PHP 5)

shm_detach — Disconnects from shared memory segment

Description

bool shm_detach ( resource $shm_identifier )

shm_detach() disconnects from the shared memory given by the shm_identifier created by shm_attach(). Remember, that shared memory still exist in the Unix system and the data is still present.

Parameters

shm_identifier

A shared memory resource handle as returned by shm_attach()

Return Values

shm_detach() always returns TRUE.

See Also

  • shm_attach() - Creates or open a shared memory segment
  • shm_remove() - Removes shared memory from Unix systems
  • shm_remove_var() - Removes a variable from shared memory

shm_attach
shm_get_var
Semaphore Functions


Returns a variable from shared memory

shm_detach
shm_has_var
Semaphore Functions
PHP Manual

shm_get_var

(PHP 4, PHP 5)

shm_get_var — Returns a variable from shared memory

Description

mixed shm_get_var ( resource $shm_identifier , int $variable_key )

shm_get_var() returns the variable with a given variable_key , in the given shared memory segment. The variable is still present in the shared memory.

Parameters

shm_identifier

Shared memory segment, obtained from shm_attach().

variable_key

The variable key.

Return Values

Returns the variable with the given key.

See Also

  • shm_has_var() - Check whether a specific entry exists
  • shm_put_var() - Inserts or updates a variable in shared memory

shm_detach
shm_has_var
Semaphore Functions


Check whether a specific entry exists

shm_get_var
shm_put_var
Semaphore Functions
PHP Manual

shm_has_var

(PHP 5 >= 5.3.0)

shm_has_var — Check whether a specific entry exists

Description

bool shm_has_var ( resource $shm_identifier , int $variable_key )

Checks whether a specific key exists inside a shared memory segment.

Parameters

shm_identifier

Shared memory segment, obtained from shm_attach().

variable_key

The variable key.

Return Values

Returns TRUE if the entry exists, otherwise FALSE

See Also

  • shm_get_var() - Returns a variable from shared memory
  • shm_put_var() - Inserts or updates a variable in shared memory

shm_get_var
shm_put_var
Semaphore Functions


Inserts or updates a variable in shared memory

shm_has_var
shm_remove_var
Semaphore Functions
PHP Manual

shm_put_var

(PHP 4, PHP 5)

shm_put_var — Inserts or updates a variable in shared memory

Description

bool shm_put_var ( resource $shm_identifier , int $variable_key , mixed $variable )

shm_put_var() inserts or updates the variable with the given variable_key .

Warnings (E_WARNING level) will be issued if shm_identifier is not a valid SysV shared memory index or if there was not enough shared memory remaining to complete your request.

Parameters

shm_identifier

A shared memory resource handle as returned by shm_attach()

variable_key

The variable key.

variable

The variable. All variable-types are supported.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • shm_get_var() - Returns a variable from shared memory
  • shm_has_var() - Check whether a specific entry exists

shm_has_var
shm_remove_var
Semaphore Functions


Removes shared memory from Unix systems

shm_remove_var
Shared Memory
Semaphore Functions
PHP Manual

shm_remove

(PHP 4, PHP 5)

shm_remove — Removes shared memory from Unix systems

Description

bool shm_remove ( resource $shm_identifier )

shm_remove() removes the shared memory shm_identifier . All data will be destroyed.

Parameters

shm_identifier

The shared memory identifier as returned by shm_attach()

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • shm_remove_var() - Removes a variable from shared memory

shm_remove_var
Shared Memory
Semaphore Functions


Removes a variable from shared memory

shm_put_var
shm_remove
Semaphore Functions
PHP Manual

shm_remove_var

(PHP 4, PHP 5)

shm_remove_var — Removes a variable from shared memory

Description

bool shm_remove_var ( resource $shm_identifier , int $variable_key )

Removes a variable with a given variable_key and frees the occupied memory.

Parameters

shm_identifier

The shared memory identifier as returned by shm_attach()

variable_key

The variable key.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • shm_remove() - Removes shared memory from Unix systems

shm_put_var
shm_remove
Semaphore Functions


Close shared memory block

Shared Memory Functions
shmop_delete
Shared Memory Functions
PHP Manual

shmop_close

(PHP 4 >= 4.0.4, PHP 5)

shmop_close — Close shared memory block

Description

void shmop_close ( int $shmid )

shmop_close() is used to close a shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

Return Values

No value is returned.

Examples

Example #1 Closing shared memory block

<?php
shmop_close($shm_id);
?>

This example will close shared memory block identified by $shm_id.

See Also

  • shmop_open() - Create or open shared memory block

Shared Memory Functions
shmop_delete
Shared Memory Functions


Delete shared memory block

shmop_close
shmop_open
Shared Memory Functions
PHP Manual

shmop_delete

(PHP 4 >= 4.0.4, PHP 5)

shmop_delete — Delete shared memory block

Description

bool shmop_delete ( int $shmid )

shmop_delete() is used to delete a shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Deleting shared memory block

<?php
shmop_delete($shm_id);
?>

This example will delete shared memory block identified by $shm_id.

shmop_close
shmop_open
Shared Memory Functions


Create or open shared memory block

shmop_delete
shmop_read
Shared Memory Functions
PHP Manual

shmop_open

(PHP 4 >= 4.0.4, PHP 5)

shmop_open — Create or open shared memory block

Description

int shmop_open ( int $key , string $flags , int $mode , int $size )

shmop_open() can create or open a shared memory block.

Parameters

key

System's id for the shared memory block. Can be passed as a decimal or hex.

flags

The flags that you can use:

  • "a" for access (sets SHM_RDONLY for shmat) use this flag when you need to open an existing shared memory segment for read only
  • "c" for create (sets IPC_CREATE) use this flag when you need to create a new shared memory segment or if a segment with the same key exists, try to open it for read and write
  • "w" for read & write access use this flag when you need to read and write to a shared memory segment, use this flag in most cases.
  • "n" create a new memory segment (sets IPC_CREATE|IPC_EXCL) use this flag when you want to create a new shared memory segment but if one already exists with the same flag, fail. This is useful for security purposes, using this you can prevent race condition exploits.

mode

The permissions that you wish to assign to your memory segment, those are the same as permission for a file. Permissions need to be passed in octal form, like for example 0644

size

The size of the shared memory block you wish to create in bytes

Note: Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment.

Return Values

On success shmop_open() will return an id that you can use to access the shared memory segment you've created. FALSE is returned on failure.

Examples

Example #1 Create a new shared memory block

<?php
$shm_key = ftok(__FILE__, 't');
$shm_id = shmop_open($shm_key, "c", 0644, 100);
?>

This example opened a shared memory block with a system id returned by ftok().

See Also

  • shmop_close() - Close shared memory block
  • shmop_delete() - Delete shared memory block

shmop_delete
shmop_read
Shared Memory Functions


Read data from shared memory block

shmop_open
shmop_size
Shared Memory Functions
PHP Manual

shmop_read

(PHP 4 >= 4.0.4, PHP 5)

shmop_read — Read data from shared memory block

Description

string shmop_read ( int $shmid , int $start , int $count )

shmop_read() will read a string from shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

start

Offset from which to start reading

count

The number of bytes to read

Return Values

Returns the data or FALSE on failure.

Examples

Example #1 Reading shared memory block

<?php
$shm_data = shmop_read($shm_id, 0, 50);
?>

This example will read 50 bytes from shared memory block and place the data inside $shm_data.

See Also

  • shmop_write() - Write data into shared memory block

shmop_open
shmop_size
Shared Memory Functions


Get size of shared memory block

shmop_read
shmop_write
Shared Memory Functions
PHP Manual

shmop_size

(PHP 4 >= 4.0.4, PHP 5)

shmop_size — Get size of shared memory block

Description

int shmop_size ( int $shmid )

shmop_size() is used to get the size, in bytes of the shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

Return Values

Returns an int, which represents the number of bytes the shared memory block occupies.

Examples

Example #1 Getting the size of the shared memory block

<?php
$shm_size = shmop_size($shm_id);
?>

This example will put the size of shared memory block identified by $shm_id into $shm_size.

shmop_read
shmop_write
Shared Memory Functions


Write data into shared memory block

shmop_size
Other Basic Extensions
Shared Memory Functions
PHP Manual

shmop_write

(PHP 4 >= 4.0.4, PHP 5)

shmop_write — Write data into shared memory block

Description

int shmop_write ( int $shmid , string $data , int $offset )

shmop_write() will write a string into shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

data

A string to write into shared memory block

offset

Specifies where to start writing data inside the shared memory segment.

Return Values

The size of the written data , or FALSE on failure.

Examples

Example #1 Writing to shared memory block

<?php
$shm_bytes_written = shmop_write($shm_id, $my_string, 0);
?>

This example will write data inside $my_string into shared memory block, $shm_bytes_written will contain the number of bytes written.

See Also

  • shmop_read() - Read data from shared memory block

shmop_size
Other Basic Extensions
Shared Memory Functions


Alias of highlight_file

php_strip_whitespace
sleep
Misc. Functions
PHP Manual

show_source

(PHP 4, PHP 5)

show_source — Alias of highlight_file()

Description

This function is an alias of: highlight_file().

php_strip_whitespace
sleep
Misc. Functions


Obtain the payment url (needs 2 arguments)

nthmac
Cryptography Extensions
SPPLUS Functions
PHP Manual

signeurlpaiement

(PECL spplus >= 1.0.0)

signeurlpaiement — Obtain the payment url (needs 2 arguments)

Description

string nthmac ( string $clent , string $data )
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

nthmac
Cryptography Extensions
SPPLUS Functions


Sine

round
sinh
Math Functions
PHP Manual

sin

(PHP 4, PHP 5)

sin — Sine

Description

float sin ( float $arg )

sin() returns the sine of the arg parameter. The arg parameter is in radians.

Parameters

arg

A value in radians

Return Values

The sine of arg

Examples

Example #1 sin() example

<?php

// Precision depends on your precision directive
echo sin(deg2rad(60));  //  0.866025403 ...
echo sin(60);           // -0.304810621 ...

?>

See Also

  • asin() - Arc sine
  • sinh() - Hyperbolic sine
  • cos() - Cosine
  • tan() - Tangent
  • deg2rad() - Converts the number in degrees to the radian equivalent

round
sinh
Math Functions


Hyperbolic sine

sin
sqrt
Math Functions
PHP Manual

sinh

(PHP 4 >= 4.1.0, PHP 5)

sinh — Hyperbolic sine

Description

float sinh ( float $arg )

Returns the hyperbolic sine of arg , defined as (exp(arg) - exp(-arg))/2.

Parameters

arg

The argument to process

Return Values

The hyperbolic sine of arg

See Also

  • sin() - Sine
  • asinh() - Inverse hyperbolic sine
  • cosh() - Hyperbolic cosine
  • tanh() - Hyperbolic tangent

sin
sqrt
Math Functions


Delay execution

show_source
sys_getloadavg
Misc. Functions
PHP Manual

sleep

(PHP 4, PHP 5)

sleep — Delay execution

Description

int sleep ( int $seconds )

Delays the program execution for the given number of seconds .

Parameters

seconds

Halt time in seconds.

Return Values

Returns zero on success, or FALSE on errors. If the call was interrupted by a signal, sleep() returns the number of seconds left to sleep.

Errors/Exceptions

If the specified number of seconds is negative, this function will generate a E_WARNING.

Examples

Example #1 sleep() example

<?php

// current time
echo date('h:i:s') . "\n";

// sleep for 10 seconds
sleep(10);

// wake up !
echo date('h:i:s') . "\n";

?>

This example will output (after 10 seconds)

05:31:23
05:31:33

See Also

  • usleep() - Delay execution in microseconds
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time

show_source
sys_getloadavg
Misc. Functions


Execute a query against a given database and returns an array

SQLite Functions
sqlite_busy_timeout
SQLite Functions
PHP Manual

sqlite_array_query

SQLiteDatabase->arrayQuery

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_array_query -- SQLiteDatabase->arrayQuery — Execute a query against a given database and returns an array

Description

array sqlite_array_query ( resource $dbhandle , string $query [, int $result_type [, bool $decode_binary ]] )
array sqlite_array_query ( string $query , resource $dbhandle [, int $result_type [, bool $decode_binary ]] )

Object oriented style (method):

SQLiteDatabase
array arrayQuery ( string $query [, int $result_type [, bool $decode_binary ]] )

sqlite_array_query() executes the given query and returns an array of the entire result set. It is similar to calling sqlite_query() and then sqlite_fetch_array() for each row in the result set. sqlite_array_query() is significantly faster than the aforementioned.

Tip

sqlite_array_query() is best suited to queries returning 45 rows or less. If you have more data than that, it is recommended that you write your scripts to use sqlite_unbuffered_query() instead for more optimal performance.

Parameters

query

The query to be executed.

Data inside the query should be properly escaped.

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

Returns an array of the entire result set; FALSE otherwise.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example #1 Procedural style

<?php
$dbhandle = sqlite_open('sqlitedb');
$result = sqlite_array_query($dbhandle, 'SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Example #2 Object-oriented style

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$result = $dbhandle->arrayQuery('SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

See Also

  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_fetch_array() - Fetches the next row from a result set as an array
  • sqlite_fetch_string() - Alias of sqlite_fetch_single

SQLite Functions
sqlite_busy_timeout
SQLite Functions


Set busy timeout duration, or disable busy handlers

sqlite_array_query
sqlite_changes
SQLite Functions
PHP Manual

sqlite_busy_timeout

SQLiteDatabase->busyTimeout

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_busy_timeout -- SQLiteDatabase->busyTimeout — Set busy timeout duration, or disable busy handlers

Description

void sqlite_busy_timeout ( resource $dbhandle , int $milliseconds )

Object oriented style (method):

SQLiteDatabase
void busyTimeout ( int $milliseconds )

Set the maximum time, in milliseconds, that SQLite will wait for a dbhandle to become ready for use.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

milliseconds

The number of milliseconds. When set to 0, busy handlers will be disabled and SQLite will return immediately with a SQLITE_BUSY status code if another process/thread has the database locked for an update.

PHP sets the default busy timeout to be 60 seconds when the database is opened.

Note: There are one thousand (1000) milliseconds in one second.

Return Values

No value is returned.

Examples

Example #1 Procedural style

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_busy_timeout($dbhandle, 10000); // set timeout to 10 seconds
sqlite_busy_timeout($dbhandle, 0); // disable busy handler
?>

Example #2 Object oriented style

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->busyTimeout(10000); // 10 seconds
$dbhandle->busyTimeout(0); // disable
?>

See Also

  • sqlite_open() - Opens a SQLite database and create the database if it does not exist

sqlite_array_query
sqlite_changes
SQLite Functions


Returns the number of rows that were changed by the most recent SQL statement

sqlite_busy_timeout
sqlite_close
SQLite Functions
PHP Manual

sqlite_changes

SQLiteDatabase->changes

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_changes -- SQLiteDatabase->changes — Returns the number of rows that were changed by the most recent SQL statement

Description

int sqlite_changes ( resource $dbhandle )

Object oriented style (method):

SQLiteDatabase
int changes ( void )

Returns the numbers of rows that were changed by the most recent SQL statement executed against the dbhandle database handle.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Return Values

Returns the number of changed rows.

Examples

Example #1 Procedural style

<?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_query($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>

Example #2 Object oriented style

<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->query("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', $dbhandle->changes();
}
?>

See Also

  • sqlite_open() - Opens a SQLite database and create the database if it does not exist

sqlite_busy_timeout
sqlite_close
SQLite Functions


Closes an open SQLite database

sqlite_changes
sqlite_column
SQLite Functions
PHP Manual

sqlite_close

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_close — Closes an open SQLite database

Description

void sqlite_close ( resource $dbhandle )

Closes the given database handle. If the database was persistent, it will be closed and removed from the persistent list.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally.

Return Values

No value is returned.

Examples

Example #1 sqlite_close() example

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_close($dbhandle);
?>

See Also

  • sqlite_open() - Opens a SQLite database and create the database if it does not exist
  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist

sqlite_changes
sqlite_column
SQLite Functions


Fetches a column from the current row of a result set

sqlite_close
sqlite_create_aggregate
SQLite Functions
PHP Manual

sqlite_column

SQLiteResult->column

SQLiteUnbuffered->column

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_column -- SQLiteResult->column -- SQLiteUnbuffered->column — Fetches a column from the current row of a result set

Description

mixed sqlite_column ( resource $result , mixed $index_or_name [, bool $decode_binary = true ] )
SQLiteResult
mixed column ( mixed $index_or_name [, bool $decode_binary = true ] )
SQLiteUnbuffered
mixed column ( mixed $index_or_name [, bool $decode_binary = true ] )

Fetches the value of a column named index_or_name (if it is a string), or of the ordinal column numbered index_or_name (if it is an integer) from the current row of the query result handle result .

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

index_or_name

The column index or name to fetch.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns the column value.

Notes

Note: Use this function when you are iterating a large result set with many columns, or with columns that contain large amounts of data.

See Also

  • sqlite_fetch_string() - Alias of sqlite_fetch_single

sqlite_close
sqlite_create_aggregate
SQLite Functions


Register an aggregating UDF for use in SQL statements

sqlite_column
sqlite_create_function
SQLite Functions
PHP Manual

sqlite_create_aggregate

SQLiteDatabase->createAggregate

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_create_aggregate -- SQLiteDatabase->createAggregate — Register an aggregating UDF for use in SQL statements

Description

void sqlite_create_aggregate ( resource $dbhandle , string $function_name , callback $step_func , callback $finalize_func [, int $num_args = -1 ] )

Object oriented style (method):

SQLiteDatabase
void createAggregate ( string $function_name , callback $step_func , callback $finalize_func [, int $num_args = -1 ] )

sqlite_create_aggregate() is similar to sqlite_create_function() except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this function and sqlite_create_function() is that two functions are required to manage the aggregate; step_func is called for each row of the result set. Your PHP function should accumulate the result and store it into the aggregation context. Once all the rows have been processed, finalize_func will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set.

finalize_func

Callback function to aggregate the "stepped" data from each row.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Return Values

No value is returned.

Examples

Example #1 max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$dbhandle = sqlite_open(':memory:');
sqlite_query($dbhandle, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($dbhandle, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&$context, $string)
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$context)
{
    return $context;
}

sqlite_create_aggregate($dbhandle, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($dbhandle, 'SELECT max_len(a) from strings'));

?>

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the context . In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Note: The example above will not work correctly if the column contains binary data. Take a look at the manual page for sqlite_udf_decode_binary() for an explanation of why this is so, and an example of how to make it respect the binary encoding.

Tip

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Tip

You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

See Also

  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF
  • sqlite_udf_decode_binary() - Decode binary data passed as parameters to an UDF

sqlite_column
sqlite_create_function
SQLite Functions


Registers a "regular" User Defined Function for use in SQL statements

sqlite_create_aggregate
sqlite_current
SQLite Functions
PHP Manual

sqlite_create_function

SQLiteDatabase->createFunction

(PHP 5, sqlite >= 1.0.0)

sqlite_create_function -- SQLiteDatabase->createFunction — Registers a "regular" User Defined Function for use in SQL statements

Description

void sqlite_create_function ( resource $dbhandle , string $function_name , callback $callback [, int $num_args = -1 ] )

Object oriented style (method):

SQLiteDatabase
void createFunction ( string $function_name , callback $callback [, int $num_args = -1 ] )

sqlite_create_function() allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

Note: Callback functions should return a type understood by SQLite (i.e. scalar type).

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

No value is returned.

Examples

Example #1 sqlite_create_function() example

<?php
function md5_and_reverse($string)
{
    return strrev(md5($string));
}

if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {

    sqlite_create_function($dbhandle, 'md5rev', 'md5_and_reverse', 1);

    $sql  = 'SELECT md5rev(filename) FROM files';
    $rows = sqlite_array_query($dbhandle, $sql);
} else {
    echo 'Error opening sqlite db: ' . $sqliteerror;
    exit;
}
?>

In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that you do not need to process the result using a foreach loop after you have queried for the data.

PHP registers a special function named php when the database is first opened. The php function can be used to call any PHP function without having to register it first.

Example #2 Example of using the PHP function

<?php
$rows = sqlite_array_query($dbhandle, "SELECT php('md5', filename) from files");
?>

This example will call the md5() on each filename column in the database and return the result into $rows

Note: For performance reasons, PHP will not automatically encode/decode binary data passed to and from your UDF's. You need to manually encode/decode the parameters and return values if you need to process binary data in this way. Take a look at sqlite_udf_encode_binary() and sqlite_udf_decode_binary() for more details.

Tip

It is not recommended to use UDF's to handle processing of binary data, unless high performance is not a key requirement of your application.

Tip

You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

See Also

  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

sqlite_create_aggregate
sqlite_current
SQLite Functions


Fetches the current row from a result set as an array

sqlite_create_function
sqlite_error_string
SQLite Functions
PHP Manual

sqlite_current

SQLiteResult->current

SQLiteUnbuffered->current

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_current -- SQLiteResult->current -- SQLiteUnbuffered->current — Fetches the current row from a result set as an array

Description

array sqlite_current ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Object oriented style (method):

SQLiteResult
array current ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
SQLiteUnbuffered
array current ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

sqlite_current() is identical to sqlite_fetch_array() except that it does not advance to the next row prior to returning the data; it returns the data from the current position only.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the current row from a result set; FALSE if the current position is beyond the final row.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

See Also

  • sqlite_seek() - Seek to a particular row number of a buffered result set
  • sqlite_next() - Seek to the next row number
  • sqlite_fetch_array() - Fetches the next row from a result set as an array

sqlite_create_function
sqlite_error_string
SQLite Functions


Returns the textual description of an error code

sqlite_current
sqlite_escape_string
SQLite Functions
PHP Manual

sqlite_error_string

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_error_string — Returns the textual description of an error code

Description

string sqlite_error_string ( int $error_code )

Returns a human readable description of the error_code returned from sqlite_last_error().

Parameters

error_code

The error code being used, which might be passed in from sqlite_last_error().

Return Values

Returns a human readable description of the error_code , as a string.

See Also

  • sqlite_last_error() - Returns the error code of the last error for a database

sqlite_current
sqlite_escape_string
SQLite Functions


Escapes a string for use as a query parameter

sqlite_error_string
sqlite_exec
SQLite Functions
PHP Manual

sqlite_escape_string

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_escape_string — Escapes a string for use as a query parameter

Description

string sqlite_escape_string ( string $item )

sqlite_escape_string() will correctly quote the string specified by item for use in an SQLite SQL statement. This includes doubling up single-quote characters (') and checking for binary-unsafe characters in the query string.

Although the encoding makes it safe to insert the data, it will render simple text comparisons and LIKE clauses in your queries unusable for the columns that contain the binary data. In practice, this shouldn't be a problem, as your schema should be such that you don't use such things on binary columns (in fact, it might be better to store binary data using other means, such as in files).

Parameters

item

The string being quoted.

If the item contains a NUL character, or if it begins with a character whose ordinal value is 0x01, PHP will apply a binary encoding scheme so that you can safely store and retrieve binary data.

Return Values

Returns an escaped string for use in an SQLite SQL statement.

Notes

Note:

    Do not use this function to encode the return values from UDF's created
    using sqlite_create_function() or
    sqlite_create_aggregate() - use
    sqlite_udf_encode_binary() instead.

Warning

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

See Also

  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF

sqlite_error_string
sqlite_exec
SQLite Functions


Executes a result-less query against a given database

sqlite_escape_string
sqlite_factory
SQLite Functions
PHP Manual

sqlite_exec

SQLiteDatabase->exec

(PHP 5, PECL sqlite >= 1.0.3)

sqlite_exec -- SQLiteDatabase->exec — Executes a result-less query against a given database

Description

bool sqlite_exec ( resource $dbhandle , string $query [, string &$error_msg ] )
bool sqlite_exec ( string $query , resource $dbhandle )

Object oriented style (method):

SQLiteDatabase
bool queryExec ( string $query [, string &$error_msg ] )

Executes an SQL statement given by the query against a given database handle (specified by the dbhandle parameter).

Warning

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

This function will return a boolean result; TRUE for success or FALSE for failure. If you need to run a query that returns rows, see sqlite_query().

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Changelog

Version | Description
5.1.0 | Added the error_msg parameter

Examples

Example #1 Procedural example

<?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_exec($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
    exit("Error in query: '$error'");
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>

Example #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->queryExec("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
    exit("Error in query: '$error'");
} else {
    echo 'Number of rows modified: ', $dbhandle->changes();
}
?>

See Also

  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_unbuffered_query() - Execute a query that does not prefetch and buffer all data
  • sqlite_array_query() - Execute a query against a given database and returns an array

sqlite_escape_string
sqlite_factory
SQLite Functions


Opens a SQLite database and returns a SQLiteDatabase object

sqlite_exec
sqlite_fetch_all
SQLite Functions
PHP Manual

sqlite_factory

(PHP 5)

sqlite_factory — Opens a SQLite database and returns a SQLiteDatabase object

Description

SQLiteDatabase sqlite_factory ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

sqlite_factory() behaves similarly to sqlite_open() in that it opens an SQLite database or attempts to create it if it does not exist. However, a SQLiteDatabase object is returned rather than a resource. Please see the sqlite_open() reference page for further usage and caveats.

Parameters

filename

The filename of the SQLite database.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns a SQLiteDatabase object on success, NULL on error.

Examples

Example #1 sqlite_factory() example

<?php
$dbhandle = sqlite_factory('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

/* functionally equivalent to: */

$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

?>

See Also

  • sqlite_open() - Opens a SQLite database and create the database if it does not exist
  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist

sqlite_exec
sqlite_fetch_all
SQLite Functions


Fetches all rows from a result set as an array of arrays

sqlite_factory
sqlite_fetch_array
SQLite Functions
PHP Manual

sqlite_fetch_all

SQLiteResult->fetchAll

SQLiteUnbuffered->fetchAll

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_fetch_all -- SQLiteResult->fetchAll -- SQLiteUnbuffered->fetchAll — Fetches all rows from a result set as an array of arrays

Description

array sqlite_fetch_all ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Object oriented style (method):

SQLiteResult
array fetchAll ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
SQLiteUnbuffered
array fetchAll ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

sqlite_fetch_all() returns an array of the entire result set from the result resource. It is similar to calling sqlite_query() (or sqlite_unbuffered_query()) and then sqlite_fetch_array() for each row in the result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the remaining rows in a result set. If called right after sqlite_query(), it returns all rows. If called after sqlite_fetch_array(), it returns the rest. If there are no rows in a result set, it returns an empty array.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example #1 Procedural example

<?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Example #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

$result = $query->fetchAll(SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

See Also

  • sqlite_fetch_array() - Fetches the next row from a result set as an array

sqlite_factory
sqlite_fetch_array
SQLite Functions


Fetches the next row from a result set as an array

sqlite_fetch_all
sqlite_fetch_column_types
SQLite Functions
PHP Manual

sqlite_fetch_array

SQLiteResult->fetch

SQLiteUnbuffered->fetch

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_fetch_array -- SQLiteResult->fetch -- SQLiteUnbuffered->fetch — Fetches the next row from a result set as an array

Description

array sqlite_fetch_array ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Object oriented style (method):

SQLiteResult
array fetch ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
SQLiteUnbuffered
array fetch ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Fetches the next row from the given result handle. If there are no more rows, returns FALSE, otherwise returns an associative array representing the row data.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the next row from a result set; FALSE if the next position is beyond the final row.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example #1 Procedural example

<?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
while ($entry = sqlite_fetch_array($query, SQLITE_ASSOC)) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Example #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

while ($entry = $query->fetch(SQLITE_ASSOC)) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

See Also

  • sqlite_array_query() - Execute a query against a given database and returns an array
  • sqlite_fetch_string() - Alias of sqlite_fetch_single

sqlite_fetch_all
sqlite_fetch_column_types
SQLite Functions


Return an array of column types from a particular table

sqlite_fetch_array
sqlite_fetch_object
SQLite Functions
PHP Manual

sqlite_fetch_column_types

SQLiteDatabase->fetchColumnTypes

(PHP 5)

sqlite_fetch_column_types -- SQLiteDatabase->fetchColumnTypes — Return an array of column types from a particular table

Description

array sqlite_fetch_column_types ( string $table_name , resource $dbhandle [, int $result_type ] )

Object oriented style (method):

SQLiteDatabase
array fetchColumnTypes ( string $table_name [, int $result_type ] )

sqlite_fetch_column_types() returns an array of column data types from the specified table_name table.

Parameters

table_name

The table name to query.

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_ASSOC is the default for this function.

Return Values

Returns an array of column data types; FALSE on error.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Changelog

Version | Description
5.1.0 | Added result_type

Examples

Example #1 Procedural example

<?php
$db = sqlite_open('mysqlitedb');
sqlite_query($db, 'CREATE TABLE foo (bar varchar(10), arf text)');
$cols = sqlite_fetch_column_types('foo', $db, SQLITE_ASSOC);

foreach ($cols as $column => $type) {
    echo "Column: $column  Type: $type";
}
?>

Example #2 Object-oriented example

<?php
$db = new SQLiteDatabase('mysqlitedb');
$db->query('CREATE TABLE foo (bar varchar(10), arf text)');
$cols = $db->fetchColumnTypes('foo', SQLITE_ASSOC);

foreach ($cols as $column => $type) {
    echo "Column: $column  Type: $type";
}
?>

The above example will output:

Column: bar  Type: VARCHAR
Column: arf  Type: TEXT

sqlite_fetch_array
sqlite_fetch_object
SQLite Functions


Fetches the next row from a result set as an object

sqlite_fetch_column_types
sqlite_fetch_single
SQLite Functions
PHP Manual

sqlite_fetch_object

SQLiteResult->fetchObject

SQLiteUnbuffered->fetchObject

(PHP 5)

sqlite_fetch_object -- SQLiteResult->fetchObject -- SQLiteUnbuffered->fetchObject — Fetches the next row from a result set as an object

Description

object sqlite_fetch_object ( resource $result [, string $class_name [, array $ctor_params [, bool $decode_binary = true ]]] )

Object oriented style (method):

SQLiteResult
object fetchObject ([ string $class_name [, array $ctor_params [, bool $decode_binary = true ]]] )
SQLiteUnbuffered
object fetchObject ([ string $class_name [, array $ctor_params [, bool $decode_binary = true ]]] )
Warning

This function is currently not documented; only its argument list is available.

sqlite_fetch_column_types
sqlite_fetch_single
SQLite Functions


Fetches the first column of a result set as a string

sqlite_fetch_object
sqlite_fetch_string
SQLite Functions
PHP Manual

sqlite_fetch_single

SQLiteResult->fetchSingle

SQLiteUnbuffered->fetchSingle

(PHP 5, PECL sqlite >= 1.0.1)

sqlite_fetch_single -- SQLiteResult->fetchSingle -- SQLiteUnbuffered->fetchSingle — Fetches the first column of a result set as a string

Description

string sqlite_fetch_single ( resource $result [, bool $decode_binary = true ] )

Object oriented style (method):

SQLiteResult
string fetchSingle ([ bool $decode_binary = true ] )
SQLiteUnbuffered
string fetchSingle ([ bool $decode_binary = true ] )

sqlite_fetch_single() is identical to sqlite_fetch_array() except that it returns the value of the first column of the rowset.

This is the most optimal way to retrieve data when you are only interested in the values from a single column of data.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns the first column value, as a string.

Examples

Example #1 A sqlite_fetch_single() example

<?php
if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {

    $sql = "SELECT id FROM sometable WHERE id = 42";
    $res = sqlite_query($dbhandle, $sql);

    if (sqlite_num_rows($res) > 0) {
        echo sqlite_fetch_single($res); // 42
    }

    sqlite_close($dbhandle);
}
?>

See Also

  • sqlite_fetch_array() - Fetches the next row from a result set as an array

sqlite_fetch_object
sqlite_fetch_string
SQLite Functions


Alias of sqlite_fetch_single

sqlite_fetch_single
sqlite_field_name
SQLite Functions
PHP Manual

sqlite_fetch_string

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_fetch_string — Alias of sqlite_fetch_single()

Description

This function is an alias of: sqlite_fetch_single().

sqlite_fetch_single
sqlite_field_name
SQLite Functions


Returns the name of a particular field

sqlite_fetch_string
sqlite_has_more
SQLite Functions
PHP Manual

sqlite_field_name

SQLiteResult->fieldName

SQLiteUnbuffered->fieldName

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_field_name -- SQLiteResult->fieldName -- SQLiteUnbuffered->fieldName — Returns the name of a particular field

Description

string sqlite_field_name ( resource $result , int $field_index )

Object oriented style (method):

SQLiteResult
string fieldName ( int $field_index )
SQLiteUnbuffered
string fieldName ( int $field_index )

Given the ordinal column number, field_index , sqlite_field_name() returns the name of that field in the result set result .

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

field_index

The ordinal column number in the result set.

Return Values

Returns the name of a field in an SQLite result set, given the ordinal column number; FALSE on error.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

sqlite_fetch_string
sqlite_has_more
SQLite Functions


Finds whether or not more rows are available

sqlite_field_name
sqlite_has_prev
SQLite Functions
PHP Manual

sqlite_has_more

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_has_more — Finds whether or not more rows are available

Description

bool sqlite_has_more ( resource $result )

Finds whether more rows are available from the given result set.

Parameters

result

The SQLite result resource.

Return Values

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

See Also

  • sqlite_num_rows() - Returns the number of rows in a buffered result set
  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement

sqlite_field_name
sqlite_has_prev
SQLite Functions


Returns whether or not a previous row is available

sqlite_has_more
sqlite_key
SQLite Functions
PHP Manual

sqlite_has_prev

SQLiteResult->hasPrev

(PHP 5)

sqlite_has_prev -- SQLiteResult->hasPrev — Returns whether or not a previous row is available

Description

bool sqlite_has_prev ( resource $result )

Object oriented style (method):

SQLiteResult
bool hasPrev ( void )

Find whether there are more previous rows from the given result handle.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE if there are more previous rows available from the result handle, or FALSE otherwise.

See Also

  • sqlite_prev() - Seek to the previous row number of a result set
  • sqlite_has_more() - Finds whether or not more rows are available
  • sqlite_num_rows() - Returns the number of rows in a buffered result set

sqlite_has_more
sqlite_key
SQLite Functions


Returns the current row index

sqlite_has_prev
sqlite_last_error
SQLite Functions
PHP Manual

sqlite_key

SQLiteResult->key

(PHP 5 >= 5.1.0)

sqlite_key -- SQLiteResult->key — Returns the current row index

Description

int sqlite_key ( resource $result )

Object oriented style (method):

SQLiteResult
int key ( void )

sqlite_key() returns the current row index of the buffered result set result .

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns the current row index of the buffered result set result .

Changelog

Version | Description
5.0.4 | Prior to PHP 5.0.4, sqlite_key() was only able to be called as a method on a SQLiteResult object, not procedurally.

See Also

  • sqlite_next() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number

sqlite_has_prev
sqlite_last_error
SQLite Functions


Returns the error code of the last error for a database

sqlite_key
sqlite_last_insert_rowid
SQLite Functions
PHP Manual

sqlite_last_error

SQLiteDatabase->lastError

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_last_error -- SQLiteDatabase->lastError — Returns the error code of the last error for a database

Description

int sqlite_last_error ( resource $dbhandle )

Object oriented style (method):

SQLiteDatabase
int lastError ( void )

Returns the error code from the last operation performed on dbhandle (the database handle), or 0 when no error occurred. A human readable description of the error code can be retrieved using sqlite_error_string().

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Return Values

Returns an error code, or 0 if no error occurred.

See Also

  • sqlite_error_string() - Returns the textual description of an error code

sqlite_key
sqlite_last_insert_rowid
SQLite Functions


Returns the rowid of the most recently inserted row

sqlite_last_error
sqlite_libencoding
SQLite Functions
PHP Manual

sqlite_last_insert_rowid

SQLiteDatabase->lastInsertRowid

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_last_insert_rowid -- SQLiteDatabase->lastInsertRowid — Returns the rowid of the most recently inserted row

Description

int sqlite_last_insert_rowid ( resource $dbhandle )

Object oriented style (method):

SQLiteDatabase
int lastInsertRowid ( void )

Returns the rowid of the row that was most recently inserted into the database dbhandle , if it was created as an auto-increment field.

Tip

You can create auto-increment fields in SQLite by declaring them as INTEGER PRIMARY KEY in your table schema.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Return Values

Returns the row id, as an integer.

sqlite_last_error
sqlite_libencoding
SQLite Functions


Returns the encoding of the linked SQLite library

sqlite_last_insert_rowid
sqlite_libversion
SQLite Functions
PHP Manual

sqlite_libencoding

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_libencoding — Returns the encoding of the linked SQLite library

Description

string sqlite_libencoding ( void )

The SQLite library may be compiled in either ISO-8859-1 or UTF-8 compatible modes. This function allows you to determine which encoding scheme is used by your version of the library.

Warning

The default PHP distribution builds libsqlite in ISO-8859-1 encoding mode. However, this is a misnomer; rather than handling ISO-8859-1, it operates according to your current locale settings for string comparisons and sort ordering. So, rather than ISO-8859-1, you should think of it as being '8-bit' instead.

When compiled with UTF-8 support, sqlite handles encoding and decoding of UTF-8 multi-byte character sequences, but does not yet do a complete job when working with the data (no normalization is performed for example), and some comparison operations may still not be carried out correctly.

Warning

It is not recommended that you use PHP in a web-server configuration with a version of the SQLite library compiled with UTF-8 support, since libsqlite will abort the process if it detects a problem with the UTF-8 encoding.

Return Values

Returns the library encoding.

See Also

  • sqlite_lib_version()

sqlite_last_insert_rowid
sqlite_libversion
SQLite Functions


Returns the version of the linked SQLite library

sqlite_libencoding
sqlite_next
SQLite Functions
PHP Manual

sqlite_libversion

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_libversion — Returns the version of the linked SQLite library

Description

string sqlite_libversion ( void )

Returns the version of the linked SQLite library.

Return Values

Returns the librart version, as a string.

See Also

  • sqlite_libencoding() - Returns the encoding of the linked SQLite library

sqlite_libencoding
sqlite_next
SQLite Functions


Seek to the next row number

sqlite_libversion
sqlite_num_fields
SQLite Functions
PHP Manual

sqlite_next

SQLiteResult->next

SQLiteUnbuffered->next

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_next -- SQLiteResult->next -- SQLiteUnbuffered->next — Seek to the next row number

Description

bool sqlite_next ( resource $result )

Object oriented style (method):

SQLiteResult
bool next ( void )
SQLiteUnbuffered
bool next ( void )

sqlite_next() advances the result handle result to the next row.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Return Values

Returns TRUE on success, or FALSE if there are no more rows.

See Also

  • sqlite_seek() - Seek to a particular row number of a buffered result set
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number

sqlite_libversion
sqlite_num_fields
SQLite Functions


Returns the number of fields in a result set

sqlite_next
sqlite_num_rows
SQLite Functions
PHP Manual

sqlite_num_fields

SQLiteResult->numFields

SQLiteUnbuffered->numFields

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_num_fields -- SQLiteResult->numFields -- SQLiteUnbuffered->numFields — Returns the number of fields in a result set

Description

int sqlite_num_fields ( resource $result )

Object oriented style (method):

SQLiteResult
int numFields ( void )
SQLiteUnbuffered
int numFields ( void )

Returns the number of fields in the result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Return Values

Returns the number of fields, as an integer.

See Also

  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_num_rows() - Returns the number of rows in a buffered result set

sqlite_next
sqlite_num_rows
SQLite Functions


Returns the number of rows in a buffered result set

sqlite_num_fields
sqlite_open
SQLite Functions
PHP Manual

sqlite_num_rows

SQLiteResult->numRows

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_num_rows -- SQLiteResult->numRows — Returns the number of rows in a buffered result set

Description

int sqlite_num_rows ( resource $result )

Object oriented style (method):

SQLiteResult
int numRows ( void )

Returns the number of rows in the buffered result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns the number of rows, as an integer.

Examples

Example #1 Procedural example

<?php
$db = sqlite_open('mysqlitedb');
$result = sqlite_query($db, "SELECT * FROM mytable WHERE name='John Doe'");
$rows = sqlite_num_rows($result);

echo "Number of rows: $rows";
?>

Example #2 Object-oriented example

<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();

echo "Number of rows: $rows";
?>

See Also

  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_num_fields() - Returns the number of fields in a result set

sqlite_num_fields
sqlite_open
SQLite Functions


Opens a SQLite database and create the database if it does not exist

sqlite_num_rows
sqlite_popen
SQLite Functions
PHP Manual

sqlite_open

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_open — Opens a SQLite database and create the database if it does not exist

Description

resource sqlite_open ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

Object oriented style (constructor):

SQLiteDatabase
__construct ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

Opens a SQLite database or creates the database if it does not exist.

Parameters

filename

The filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns a resource (database handle) on success, FALSE on error.

Examples

Example #1 sqlite_open() example

<?php
if ($db = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {
    sqlite_query($db, 'CREATE TABLE foo (bar varchar(10))');
    sqlite_query($db, "INSERT INTO foo VALUES ('fnord')");
    $result = sqlite_query($db, 'select bar from foo');
    var_dump(sqlite_fetch_array($result));
} else {
    die($sqliteerror);
}
?>

Notes

Tip

On Unix platforms, SQLite is sensitive to scripts that use the fork() system call. If you do have such a script, it is recommended that you close the handle prior to forking and then re-open it in the child and/or parent. For more information on this issue, see » The C language interface to the SQLite library in the section entitled Multi-Threading And SQLite.

Tip

It is not recommended to work with SQLite databases mounted on NFS partitions. Since NFS is notoriously bad when it comes to locking you may find that you cannot even open the database at all, and if it succeeds, the locking behaviour may be undefined.

Note: Starting with SQLite library version 2.8.2, you can specify :memory: as the filename to create a database that lives only in the memory of the computer. This is useful mostly for temporary processing, as the in-memory database will be destroyed when the process ends. It can also be useful when coupled with the ATTACH DATABASE SQL statement to load other databases and move and query data between them.

Note: SQLite is safe mode and open_basedir aware.

See Also

  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist
  • sqlite_close() - Closes an open SQLite database
  • sqlite_factory() - Opens a SQLite database and returns a SQLiteDatabase object

sqlite_num_rows
sqlite_popen
SQLite Functions


Opens a persistent handle to an SQLite database and create the database if it does not exist

sqlite_open
sqlite_prev
SQLite Functions
PHP Manual

sqlite_popen

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist

Description

resource sqlite_popen ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

This function behaves identically to sqlite_open() except that is uses the persistent resource mechanism of PHP. For information about the meaning of the parameters, read the sqlite_open() manual page.

sqlite_popen() will first check to see if a persistent handle has already been opened for the given filename . If it finds one, it returns that handle to your script, otherwise it opens a fresh handle to the database.

The benefit of this approach is that you don't incur the performance cost of re-reading the database and index schema on each page hit served by persistent web server SAPI's (any SAPI except for regular CGI or CLI).

Note: If you use persistent handles and have the database updated by a background process (perhaps via a crontab), and that process re-creates the database by overwriting it (either by unlinking and rebuilding, or moving the updated version to replace the current version), you may experience undefined behaviour when a persistent handle on the old version of the database is recycled. To avoid this situation, have your background processes open the same database file and perform their updates in a transaction.

Parameters

filename

The filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns a resource (database handle) on success, FALSE on error.

See Also

  • sqlite_open() - Opens a SQLite database and create the database if it does not exist
  • sqlite_close() - Closes an open SQLite database
  • sqlite_factory() - Opens a SQLite database and returns a SQLiteDatabase object

sqlite_open
sqlite_prev
SQLite Functions


Seek to the previous row number of a result set

sqlite_popen
sqlite_query
SQLite Functions
PHP Manual

sqlite_prev

SQLiteResult->prev

(PHP 5)

sqlite_prev -- SQLiteResult->prev — Seek to the previous row number of a result set

Description

bool sqlite_prev ( resource $result )

Object oriented style (method):

SQLiteResult
bool prev ( void )

sqlite_prev() seeks back the result handle to the previous row.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE on success, or FALSE if there are no more previous rows.

See Also

  • sqlite_has_prev() - Returns whether or not a previous row is available
  • sqlite_rewind() - Seek to the first row number
  • sqlite_next() - Seek to the next row number

sqlite_popen
sqlite_query
SQLite Functions


Executes a query against a given database and returns a result handle

sqlite_prev
sqlite_rewind
SQLite Functions
PHP Manual

sqlite_query

SQLiteDatabase->query

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_query -- SQLiteDatabase->query — Executes a query against a given database and returns a result handle

Description

resource sqlite_query ( resource $dbhandle , string $query [, int $result_type [, string &$error_msg ]] )
resource sqlite_query ( string $query , resource $dbhandle [, int $result_type [, string &$error_msg ]] )

Object oriented style (method):

SQLiteDatabase
SQLiteResult query ( string $query [, int $result_type [, string &$error_msg ]] )

Executes an SQL statement given by the query against a given database handle.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

This function will return a result handle or FALSE on failure. For queries that return rows, the result handle can then be used with functions such as sqlite_fetch_array() and sqlite_seek().

Regardless of the query type, this function will return FALSE if the query failed.

sqlite_query() returns a buffered, seekable result handle. This is useful for reasonably small queries where you need to be able to randomly access the rows. Buffered result handles will allocate memory to hold the entire result and will not return until it has been fetched. If you only need sequential access to the data, it is recommended that you use the much higher performance sqlite_unbuffered_query() instead.

Changelog

Version | Description
5.1.0 | Added the error_msg parameter

Notes

Warning

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script. However, this works only when the result of the function is not used - if it is used, only the first SQL statement would be executed. Function sqlite_exec() will always execute multiple SQL statements.

When executing multiple queries, the return value of this function will be FALSE if there was an error, but undefined otherwise (it might be TRUE for success or it might return a result handle).

See Also

  • sqlite_unbuffered_query() - Execute a query that does not prefetch and buffer all data
  • sqlite_array_query() - Execute a query against a given database and returns an array

sqlite_prev
sqlite_rewind
SQLite Functions


Seek to the first row number

sqlite_query
sqlite_seek
SQLite Functions
PHP Manual

sqlite_rewind

SQLiteResult->rewind

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_rewind -- SQLiteResult->rewind — Seek to the first row number

Description

bool sqlite_rewind ( resource $result )

Object oriented style (method):

SQLiteResult
bool rewind ( void )

sqlite_rewind() seeks back to the first row in the given result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns FALSE if there are no rows in the result set, TRUE otherwise.

See Also

  • sqlite_next() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_seek() - Seek to a particular row number of a buffered result set

sqlite_query
sqlite_seek
SQLite Functions


Seek to a particular row number of a buffered result set

sqlite_rewind
sqlite_single_query
SQLite Functions
PHP Manual

sqlite_seek

SQLiteResult->seek

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_seek -- SQLiteResult->seek — Seek to a particular row number of a buffered result set

Description

bool sqlite_seek ( resource $result , int $rownum )

Object oriented style (method):

SQLiteResult
bool seek ( int $rownum )

sqlite_seek() seeks to the row given by the parameter rownum .

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

rownum

The ordinal row number to seek to. The row number is zero-based (0 is the first row).

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns FALSE if the row does not exist, TRUE otherwise.

See Also

  • sqlite_next() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number

sqlite_rewind
sqlite_single_query
SQLite Functions


Executes a query and returns either an array for one single column or the value of the first row

sqlite_seek
sqlite_udf_decode_binary
SQLite Functions
PHP Manual

sqlite_single_query

SQLiteDatabase->singleQuery

(PHP 5, PECL sqlite >= 1.0.1)

sqlite_single_query -- SQLiteDatabase->singleQuery — Executes a query and returns either an array for one single column or the value of the first row

Description

array sqlite_single_query ( resource $db , string $query [, bool $first_row_only [, bool $decode_binary ]] )

Object oriented style (method):

SQLiteDatabase
array singleQuery ( string $query [, bool $first_row_only [, bool $decode_binary ]] )
Warning

This function is currently not documented; only its argument list is available.

sqlite_seek
sqlite_udf_decode_binary
SQLite Functions


Decode binary data passed as parameters to an UDF

sqlite_single_query
sqlite_udf_encode_binary
SQLite Functions
PHP Manual

sqlite_udf_decode_binary

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF

Description

string sqlite_udf_decode_binary ( string $data )

Decodes binary data passed as parameters to a UDF.

You must call this function on parameters passed to your UDF if you need them to handle binary data, as the binary encoding employed by PHP will obscure the content and of the parameter in its natural, non-coded form.

PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.

Parameters

data

The encoded data that will be decoded, data that was applied by either sqlite_udf_encode_binary() or sqlite_escape_string().

Return Values

The decoded string.

Examples

Example #1 binary-safe max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = sqlite_open(':memory:');
sqlite_query($db, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($db, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&$context, $string)
{
    $string = sqlite_udf_decode_binary($string);
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$context)
{
    return $context;
}

sqlite_create_aggregate($db, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($db, 'SELECT max_len(a) from strings'));

?>

See Also

  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

sqlite_single_query
sqlite_udf_encode_binary
SQLite Functions


Encode binary data before returning it from an UDF

sqlite_udf_decode_binary
sqlite_unbuffered_query
SQLite Functions
PHP Manual

sqlite_udf_encode_binary

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_udf_encode_binary — Encode binary data before returning it from an UDF

Description

string sqlite_udf_encode_binary ( string $data )

sqlite_udf_encode_binary() applies a binary encoding to the data so that it can be safely returned from queries (since the underlying libsqlite API is not binary safe).

If there is a chance that your data might be binary unsafe (e.g.: it contains a NUL byte in the middle rather than at the end, or if it has and 0x01 byte as the first character) then you must call this function to encode the return value from your UDF.

PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.

Note: Do not use sqlite_escape_string() to quote strings returned from UDF's as it will lead to double-quoting of the data. Use sqlite_udf_encode_binary() instead!

Parameters

data

The string being encoded.

Return Values

The encoded string.

See Also

  • sqlite_udf_decode_binary() - Decode binary data passed as parameters to an UDF
  • sqlite_escape_string() - Escapes a string for use as a query parameter
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

sqlite_udf_decode_binary
sqlite_unbuffered_query
SQLite Functions


Execute a query that does not prefetch and buffer all data

sqlite_udf_encode_binary
sqlite_valid
SQLite Functions
PHP Manual

sqlite_unbuffered_query

SQLiteDatabase->unbufferedQuery

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_unbuffered_query -- SQLiteDatabase->unbufferedQuery — Execute a query that does not prefetch and buffer all data

Description

resource sqlite_unbuffered_query ( resource $dbhandle , string $query [, int $result_type [, string &$error_msg ]] )
resource sqlite_unbuffered_query ( string $query , resource $dbhandle [, int $result_type [, string &$error_msg ]] )

Object oriented style (method):

SQLiteDatabase
SQLiteUnbuffered unbufferedQuery ( string $query [, int $result_type [, string &$error_msg ]] )

sqlite_unbuffered_query() is identical to sqlite_query() except that the result that is returned is a sequential forward-only result set that can only be used to read each row, one after the other.

This function is ideal for generating things such as HTML tables where you only need to process one row at a time and don't need to randomly access the row data.

Note:

    Functions such as sqlite_seek(),
    sqlite_rewind(), sqlite_next(),
    sqlite_current(), and
    sqlite_num_rows() do not work on result handles
    returned from sqlite_unbuffered_query().

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

Returns a result handle or FALSE on failure.

sqlite_unbuffered_query() returns a sequential forward-only result set that can only be used to read each row, one after the other.

Changelog

Version | Description
5.1.0 | Added the error_msg parameter

See Also

  • sqlite_query() - Executes a query against a given database and returns a result handle

sqlite_udf_encode_binary
sqlite_valid
SQLite Functions


Returns whether more rows are available

sqlite_unbuffered_query
SQLite3
SQLite Functions
PHP Manual

sqlite_valid

SQLiteResult->valid

SQLiteUnbuffered->valid

(PHP 5)

sqlite_valid -- SQLiteResult->valid -- SQLiteUnbuffered->valid — Returns whether more rows are available

Description

bool sqlite_valid ( resource $result )

Object oriented style (method):

SQLiteResult
bool valid ( void )
SQLiteUnbuffered
bool valid ( void )

Finds whether more rows are available from the given result handle.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note: This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

See Also

  • sqlite_num_rows() - Returns the number of rows in a buffered result set
  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement

sqlite_unbuffered_query
SQLite3
SQLite Functions


Square root

sinh
srand
Math Functions
PHP Manual

sqrt

(PHP 4, PHP 5)

sqrt — Square root

Description

float sqrt ( float $arg )

Returns the square root of arg .

Parameters

arg

The argument to process

Return Values

The square root of arg or the special value NAN for negative numbers.

Examples

Example #1 sqrt() example

<?php
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>

See Also

  • pow() - Exponential expression

sinh
srand
Math Functions


Seed the random number generator

sqrt
tan
Math Functions
PHP Manual

srand

(PHP 4, PHP 5)

srand — Seed the random number generator

Description

void srand ([ int $seed ] )

Seeds the random number generator with seed or with a random value if no seed is given.

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

Parameters

seed

Optional seed value

Return Values

No value is returned.

Changelog

Version | Description
Since 4.2.0 | The seed becomes optional and defaults to a random value if omitted.

Examples

Example #1 srand() example

<?php
// seed with microseconds
function make_seed()
{
  list($usec, $sec) = explode(' ', microtime());
  return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand();
?>

See Also

  • rand() - Generate a random integer
  • getrandmax() - Show largest possible random value
  • mt_srand() - Seed the better random number generator

sqrt
tan
Math Functions


Gives information about a file

set_file_buffer
symlink
Filesystem Functions
PHP Manual

stat

(PHP 4, PHP 5)

stat — Gives information about a file

Description

array stat ( string $filename )

Gathers the statistics of the file named by filename . If filename is a symbolic link, statistics are from the file itself, not the symlink.

lstat() is identical to stat() except it would instead be based off the symlinks status.

Parameters

filename

Path to the file.

Return Values

stat() and fstat() result format
Numeric | Associative (since PHP 4.0.6) | Description
0 | dev | device number
1 | ino | inode number *
2 | mode | inode protection mode
3 | nlink | number of links
4 | uid | userid of owner *
5 | gid | groupid of owner *
6 | rdev | device type, if inode device
7 | size | size in bytes
8 | atime | time of last access (Unix timestamp)
9 | mtime | time of last modification (Unix timestamp)
10 | ctime | time of last inode change (Unix timestamp)
11 | blksize | blocksize of filesystem IO **
12 | blocks | number of 512-byte blocks allocated **

* On Windows this will always be 0.

** Only valid on systems supporting the st_blksize type - other systems (e.g. Windows) return -1.

In case of error, stat() returns FALSE.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Changelog

Version | Description
4.0.6 | In addition to returning these attributes in a numeric array, they can be accessed with associative indices, as noted next to each parameter

Examples

Example #1 stat() example

<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');

/*
 * Print file access time, this is the same
 * as calling fileatime()
 */
echo 'Access time: ' . $stat['atime'];

/*
 * Print file modification time, this is the
 * same as calling filemtime()
 */
echo 'Modification time: ' . $stat['mtime'];

/* Print the device number */
echo 'Device number: ' . $stat['dev'];
?>

Example #2 Using stat() information together with touch()

<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');

/* Did we failed to get stat information? */
if (!$stat) {
    echo 'stat() call failed...';
} else {
    /*
     * We want the access time to be 1 week
     * before the current access time.
     */
    $atime = $stat['atime'] + 604800;

    /* Touch the file */
    if (!touch('some_file.txt', time(), $atime)) {
        echo 'Failed to touch file...';
    } else {
        echo 'touch() returned success...';
    }
}
?>

Notes

Note: Note that time resolution may differ from one file system to another.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

See Also

  • lstat() - Gives information about a file or symbolic link
  • fstat() - Gets information about a file using an open file pointer
  • filemtime() - Gets file modification time
  • filegroup() - Gets file group

set_file_buffer
symlink
Filesystem Functions


Returns the absolute deviation of an array of values

Statistic Functions
stats_cdf_beta
Statistic Functions
PHP Manual

stats_absolute_deviation

(PECL stats >= 1.0.0)

stats_absolute_deviation — Returns the absolute deviation of an array of values

Description

float stats_absolute_deviation ( array $a )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

Return Values

Statistic Functions
stats_cdf_beta
Statistic Functions


CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.

stats_absolute_deviation
stats_cdf_binomial
Statistic Functions
PHP Manual

stats_cdf_beta

(PECL stats >= 1.0.0)

stats_cdf_beta — CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.

Description

float stats_cdf_beta ( float $par1 , float $par2 , float $par3 , int $which )

Method Cumulative distribution function (P) is calculated directly by code associated with the following reference. DiDinato, A. R. and Morris, A. H. Algorithm 708: Significant Digit Computation of the Incomplete Beta Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373. Computation of other parameters involve a search for a value that produces the desired value of P. The search relies on the monotonicity of P with the other parameter. Note The beta density is proportional to t^(A-1) * (1-t)^(B-1) Arguments P -- The integral from 0 to X of the chi-square distribution. Input range: [0, 1]. Q -- 1-P. Input range: [0, 1]. P + Q = 1.0. X -- Upper limit of integration of beta density. Input range: [0,1]. Search range: [0,1] Y -- 1-X. Input range: [0,1]. Search range: [0,1] X + Y = 1.0. A -- The first parameter of the beta density. Input range: (0, +infinity). Search range: [1D-100,1D100] B -- The second parameter of the beta density. Input range: (0, +infinity). Search range: [1D-100,1D100] STATUS -- 0 if calculation completed correctly -I if input parameter number I is out of range 1 if answer appears to be lower than lowest search bound 2 if answer appears to be higher than greatest search bound 3 if P + Q .ne. 1 4 if X + Y .ne. 1 BOUND -- Undefined if STATUS is 0 Bound exceeded by parameter number I if STATUS is negative. Lower search bound if STATUS is 1. Upper search bound if STATUS is 2.

Parameters

par1

par2

par3

which

Integer indicating which of the next four argument values is to be calculated from the others. Legal range: 1..4 which = 1 : Calculate P and Q from X,Y,A and B which = 2 : Calculate X and Y from P,Q,A and B which = 3 : Calculate A from P,Q,X,Y and B which = 4 : Calculate B from P,Q,X,Y and A

Return Values

STATUS -- 0 if calculation completed correctly -I if input parameter number I is out of range 1 if answer appears to be lower than lowest search bound 2 if answer appears to be higher than greatest search bound 3 if P + Q .ne. 1 4 if X + Y .ne. 1

stats_absolute_deviation
stats_cdf_binomial
Statistic Functions


Calculates any one parameter of the binomial distribution given values for the others.

stats_cdf_beta
stats_cdf_cauchy
Statistic Functions
PHP Manual

stats_cdf_binomial

(PECL stats >= 1.0.0)

stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others.

Description

float stats_cdf_binomial ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_cdf_beta
stats_cdf_cauchy
Statistic Functions


Not documented

stats_cdf_binomial
stats_cdf_chisquare
Statistic Functions
PHP Manual

stats_cdf_cauchy

(PECL stats >= 1.0.0)

stats_cdf_cauchy — Not documented

Description

float stats_cdf_cauchy ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_cdf_binomial
stats_cdf_chisquare
Statistic Functions


Calculates any one parameter of the chi-square distribution given values for the others.

stats_cdf_cauchy
stats_cdf_exponential
Statistic Functions
PHP Manual

stats_cdf_chisquare

(PECL stats >= 1.0.0)

stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others.

Description

float stats_cdf_chisquare ( float $par1 , float $par2 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

which

Return Values

stats_cdf_cauchy
stats_cdf_exponential
Statistic Functions


Not documented

stats_cdf_chisquare
stats_cdf_f
Statistic Functions
PHP Manual

stats_cdf_exponential

(PECL stats >= 1.0.0)

stats_cdf_exponential — Not documented

Description

float stats_cdf_exponential ( float $par1 , float $par2 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

which

Return Values

stats_cdf_chisquare
stats_cdf_f
Statistic Functions


Calculates any one parameter of the F distribution given values for the others.

stats_cdf_exponential
stats_cdf_gamma
Statistic Functions
PHP Manual

stats_cdf_f

(PECL stats >= 1.0.0)

stats_cdf_f — Calculates any one parameter of the F distribution given values for the others.

Description

float stats_cdf_f ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_cdf_exponential
stats_cdf_gamma
Statistic Functions


Calculates any one parameter of the gamma distribution given values for the others.

stats_cdf_f
stats_cdf_laplace
Statistic Functions
PHP Manual

stats_cdf_gamma

(PECL stats >= 1.0.0)

stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others.

Description

float stats_cdf_gamma ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_cdf_f
stats_cdf_laplace
Statistic Functions


Not documented

stats_cdf_gamma
stats_cdf_logistic
Statistic Functions
PHP Manual

stats_cdf_laplace

(PECL stats >= 1.0.0)

stats_cdf_laplace — Not documented

Description

float stats_cdf_laplace ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_cdf_gamma
stats_cdf_logistic
Statistic Functions


Not documented

stats_cdf_laplace
stats_cdf_negative_binomial
Statistic Functions
PHP Manual

stats_cdf_logistic

(PECL stats >= 1.0.0)

stats_cdf_logistic — Not documented

Description

float stats_cdf_logistic ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_cdf_laplace
stats_cdf_negative_binomial
Statistic Functions


Calculates any one parameter of the negative binomial distribution given values for the others.

stats_cdf_logistic
stats_cdf_noncentral_chisquare
Statistic Functions
PHP Manual

stats_cdf_negative_binomial

(PECL stats >= 1.0.0)

stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others.

Description

float stats_cdf_negative_binomial ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_cdf_logistic
stats_cdf_noncentral_chisquare
Statistic Functions


Calculates any one parameter of the non-central chi-square distribution given values for the others.

stats_cdf_negative_binomial
stats_cdf_noncentral_f
Statistic Functions
PHP Manual

stats_cdf_noncentral_chisquare

(PECL stats >= 1.0.0)

stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others.

Description

float stats_cdf_noncentral_chisquare ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_cdf_negative_binomial
stats_cdf_noncentral_f
Statistic Functions


Calculates any one parameter of the Non-central F distribution given values for the others.

stats_cdf_noncentral_chisquare
stats_cdf_poisson
Statistic Functions
PHP Manual

stats_cdf_noncentral_f

(PECL stats >= 1.0.0)

stats_cdf_noncentral_f — Calculates any one parameter of the Non-central F distribution given values for the others.

Description

float stats_cdf_noncentral_f ( float $par1 , float $par2 , float $par3 , float $par4 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

par4

which

Return Values

stats_cdf_noncentral_chisquare
stats_cdf_poisson
Statistic Functions


Calculates any one parameter of the Poisson distribution given values for the others.

stats_cdf_noncentral_f
stats_cdf_t
Statistic Functions
PHP Manual

stats_cdf_poisson

(PECL stats >= 1.0.0)

stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others.

Description

float stats_cdf_poisson ( float $par1 , float $par2 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

which

Return Values

stats_cdf_noncentral_f
stats_cdf_t
Statistic Functions


Calculates any one parameter of the T distribution given values for the others.

stats_cdf_poisson
stats_cdf_uniform
Statistic Functions
PHP Manual

stats_cdf_t

(PECL stats >= 1.0.0)

stats_cdf_t — Calculates any one parameter of the T distribution given values for the others.

Description

float stats_cdf_t ( float $par1 , float $par2 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

which

Return Values

stats_cdf_poisson
stats_cdf_uniform
Statistic Functions


Not documented

stats_cdf_t
stats_cdf_weibull
Statistic Functions
PHP Manual

stats_cdf_uniform

(PECL stats >= 1.0.0)

stats_cdf_uniform — Not documented

Description

float stats_cdf_uniform ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_cdf_t
stats_cdf_weibull
Statistic Functions


Not documented

stats_cdf_uniform
stats_covariance
Statistic Functions
PHP Manual

stats_cdf_weibull

(PECL stats >= 1.0.0)

stats_cdf_weibull — Not documented

Description

float stats_cdf_weibull ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_cdf_uniform
stats_covariance
Statistic Functions


Computes the covariance of two data sets

stats_cdf_weibull
stats_den_uniform
Statistic Functions
PHP Manual

stats_covariance

(PECL stats >= 1.0.0)

stats_covariance — Computes the covariance of two data sets

Description

float stats_covariance ( array $a , array $b )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

b

Return Values

stats_cdf_weibull
stats_den_uniform
Statistic Functions


Not documented

stats_covariance
stats_dens_beta
Statistic Functions
PHP Manual

stats_den_uniform

(PECL stats >= 1.0.0)

stats_den_uniform — Not documented

Description

float stats_den_uniform ( float $x , float $a , float $b )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

a

b

Return Values

stats_covariance
stats_dens_beta
Statistic Functions


Not documented

stats_den_uniform
stats_dens_cauchy
Statistic Functions
PHP Manual

stats_dens_beta

(PECL stats >= 1.0.0)

stats_dens_beta — Not documented

Description

float stats_dens_beta ( float $x , float $a , float $b )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

a

b

Return Values

stats_den_uniform
stats_dens_cauchy
Statistic Functions


Not documented

stats_dens_beta
stats_dens_chisquare
Statistic Functions
PHP Manual

stats_dens_cauchy

(PECL stats >= 1.0.0)

stats_dens_cauchy — Not documented

Description

float stats_dens_cauchy ( float $x , float $ave , float $stdev )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

ave

stdev

Return Values

stats_dens_beta
stats_dens_chisquare
Statistic Functions


Not documented

stats_dens_cauchy
stats_dens_exponential
Statistic Functions
PHP Manual

stats_dens_chisquare

(PECL stats >= 1.0.0)

stats_dens_chisquare — Not documented

Description

float stats_dens_chisquare ( float $x , float $dfr )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

dfr

Return Values

stats_dens_cauchy
stats_dens_exponential
Statistic Functions


Not documented

stats_dens_chisquare
stats_dens_f
Statistic Functions
PHP Manual

stats_dens_exponential

(PECL stats >= 1.0.0)

stats_dens_exponential — Not documented

Description

float stats_dens_exponential ( float $x , float $scale )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

scale

Return Values

stats_dens_chisquare
stats_dens_f
Statistic Functions


stats_dens_exponential
stats_dens_gamma
Statistic Functions
PHP Manual

stats_dens_f

(PECL stats >= 1.0.0)

stats_dens_f —

Description

float stats_dens_f ( float $x , float $dfr1 , float $dfr2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

dfr1

dfr2

Return Values

stats_dens_exponential
stats_dens_gamma
Statistic Functions


Not documented

stats_dens_f
stats_dens_laplace
Statistic Functions
PHP Manual

stats_dens_gamma

(PECL stats >= 1.0.0)

stats_dens_gamma — Not documented

Description

float stats_dens_gamma ( float $x , float $shape , float $scale )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

shape

scale

Return Values

stats_dens_f
stats_dens_laplace
Statistic Functions


Not documented

stats_dens_gamma
stats_dens_logistic
Statistic Functions
PHP Manual

stats_dens_laplace

(PECL stats >= 1.0.0)

stats_dens_laplace — Not documented

Description

float stats_dens_laplace ( float $x , float $ave , float $stdev )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

ave

stdev

Return Values

stats_dens_gamma
stats_dens_logistic
Statistic Functions


Not documented

stats_dens_laplace
stats_dens_negative_binomial
Statistic Functions
PHP Manual

stats_dens_logistic

(PECL stats >= 1.0.0)

stats_dens_logistic — Not documented

Description

float stats_dens_logistic ( float $x , float $ave , float $stdev )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

ave

stdev

Return Values

stats_dens_laplace
stats_dens_negative_binomial
Statistic Functions


Not documented

stats_dens_logistic
stats_dens_normal
Statistic Functions
PHP Manual

stats_dens_negative_binomial

(PECL stats >= 1.0.0)

stats_dens_negative_binomial — Not documented

Description

float stats_dens_negative_binomial ( float $x , float $n , float $pi )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

n

pi

Return Values

stats_dens_logistic
stats_dens_normal
Statistic Functions


Not documented

stats_dens_negative_binomial
stats_dens_pmf_binomial
Statistic Functions
PHP Manual

stats_dens_normal

(PECL stats >= 1.0.0)

stats_dens_normal — Not documented

Description

float stats_dens_normal ( float $x , float $ave , float $stdev )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

ave

stdev

Return Values

stats_dens_negative_binomial
stats_dens_pmf_binomial
Statistic Functions


Not documented

stats_dens_normal
stats_dens_pmf_hypergeometric
Statistic Functions
PHP Manual

stats_dens_pmf_binomial

(PECL stats >= 1.0.0)

stats_dens_pmf_binomial — Not documented

Description

float stats_dens_pmf_binomial ( float $x , float $n , float $pi )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

n

pi

Return Values

stats_dens_normal
stats_dens_pmf_hypergeometric
Statistic Functions


stats_dens_pmf_binomial
stats_dens_pmf_poisson
Statistic Functions
PHP Manual

stats_dens_pmf_hypergeometric

(PECL stats >= 1.0.0)

stats_dens_pmf_hypergeometric —

Description

float stats_dens_pmf_hypergeometric ( float $n1 , float $n2 , float $N1 , float $N2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

n1

n2

N1

N2

Return Values

stats_dens_pmf_binomial
stats_dens_pmf_poisson
Statistic Functions


Not documented

stats_dens_pmf_hypergeometric
stats_dens_t
Statistic Functions
PHP Manual

stats_dens_pmf_poisson

(PECL stats >= 1.0.0)

stats_dens_pmf_poisson — Not documented

Description

float stats_dens_pmf_poisson ( float $x , float $lb )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

lb

Return Values

stats_dens_pmf_hypergeometric
stats_dens_t
Statistic Functions


Not documented

stats_dens_pmf_poisson
stats_dens_weibull
Statistic Functions
PHP Manual

stats_dens_t

(PECL stats >= 1.0.0)

stats_dens_t — Not documented

Description

float stats_dens_t ( float $x , float $dfr )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

dfr

Return Values

stats_dens_pmf_poisson
stats_dens_weibull
Statistic Functions


Not documented

stats_dens_t
stats_harmonic_mean
Statistic Functions
PHP Manual

stats_dens_weibull

(PECL stats >= 1.0.0)

stats_dens_weibull — Not documented

Description

float stats_dens_weibull ( float $x , float $a , float $b )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

a

b

Return Values

stats_dens_t
stats_harmonic_mean
Statistic Functions


Returns the harmonic mean of an array of values

stats_dens_weibull
stats_kurtosis
Statistic Functions
PHP Manual

stats_harmonic_mean

(PECL stats >= 1.0.0)

stats_harmonic_mean — Returns the harmonic mean of an array of values

Description

number stats_harmonic_mean ( array $a )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

Return Values

stats_dens_weibull
stats_kurtosis
Statistic Functions


Computes the kurtosis of the data in the array

stats_harmonic_mean
stats_rand_gen_beta
Statistic Functions
PHP Manual

stats_kurtosis

(PECL stats >= 1.0.0)

stats_kurtosis — Computes the kurtosis of the data in the array

Description

float stats_kurtosis ( array $a )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

Return Values

stats_harmonic_mean
stats_rand_gen_beta
Statistic Functions


Generates beta random deviate

stats_kurtosis
stats_rand_gen_chisquare
Statistic Functions
PHP Manual

stats_rand_gen_beta

(PECL stats >= 1.0.0)

stats_rand_gen_beta — Generates beta random deviate

Description

float stats_rand_gen_beta ( float $a , float $b )

Returns a random deviate from the beta distribution with parameters A and B. The density of the beta is x^(a-1) * (1-x)^(b-1) / B(a,b) for 0 < x <. Method R. C. H. Cheng.

Parameters

a

b

Return Values

stats_kurtosis
stats_rand_gen_chisquare
Statistic Functions


Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.

stats_rand_gen_beta
stats_rand_gen_exponential
Statistic Functions
PHP Manual

stats_rand_gen_chisquare

(PECL stats >= 1.0.0)

stats_rand_gen_chisquare — Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.

Description

float stats_rand_gen_chisquare ( float $df )
Warning

This function is currently not documented; only its argument list is available.

Parameters

df

Return Values

stats_rand_gen_beta
stats_rand_gen_exponential
Statistic Functions


Generates a single random deviate from an exponential distribution with mean "av"

stats_rand_gen_chisquare
stats_rand_gen_f
Statistic Functions
PHP Manual

stats_rand_gen_exponential

(PECL stats >= 1.0.0)

stats_rand_gen_exponential — Generates a single random deviate from an exponential distribution with mean "av"

Description

float stats_rand_gen_exponential ( float $av )
Warning

This function is currently not documented; only its argument list is available.

Parameters

av

Return Values

stats_rand_gen_chisquare
stats_rand_gen_f
Statistic Functions


Generates a random deviate

stats_rand_gen_exponential
stats_rand_gen_funiform
Statistic Functions
PHP Manual

stats_rand_gen_f

(PECL stats >= 1.0.0)

stats_rand_gen_f — Generates a random deviate

Description

float stats_rand_gen_f ( float $dfn , float $dfd )

Generates a random deviate from the F (variance ratio) distribution with "dfn" degrees of freedom in the numerator and "dfd" degrees of freedom in the denominator. Method : directly generates ratio of chisquare variates.

Parameters

dfn

dfd

Return Values

stats_rand_gen_exponential
stats_rand_gen_funiform
Statistic Functions


Generates uniform float between low (exclusive) and high (exclusive)

stats_rand_gen_f
stats_rand_gen_gamma
Statistic Functions
PHP Manual

stats_rand_gen_funiform

(PECL stats >= 1.0.0)

stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)

Description

float stats_rand_gen_funiform ( float $low , float $high )
Warning

This function is currently not documented; only its argument list is available.

Parameters

low

high

Return Values

stats_rand_gen_f
stats_rand_gen_gamma
Statistic Functions


Generates random deviates from a gamma distribution

stats_rand_gen_funiform
stats_rand_gen_ibinomial_negative
Statistic Functions
PHP Manual

stats_rand_gen_gamma

(PECL stats >= 1.0.0)

stats_rand_gen_gamma — Generates random deviates from a gamma distribution

Description

float stats_rand_gen_gamma ( float $a , float $r )

Generates random deviates from the gamma distribution whose density is (A**R)/Gamma(R) * X**(R-1) * Exp(-A*X).

Parameters

a

location parameter of Gamma distribution (a > 0).

r

shape parameter of Gamma distribution (r > 0).

Return Values

stats_rand_gen_funiform
stats_rand_gen_ibinomial_negative
Statistic Functions


Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE

stats_rand_gen_ibinomial_negative
stats_rand_gen_int
Statistic Functions
PHP Manual

stats_rand_gen_ibinomial

(PECL stats >= 1.0.0)

stats_rand_gen_ibinomial — Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE

Description

int stats_rand_gen_ibinomial ( int $n , float $pp )
Warning

This function is currently not documented; only its argument list is available.

Parameters

n

pp

Return Values

stats_rand_gen_ibinomial_negative
stats_rand_gen_int
Statistic Functions


Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0

stats_rand_gen_gamma
stats_rand_gen_ibinomial
Statistic Functions
PHP Manual

stats_rand_gen_ibinomial_negative

(PECL stats >= 1.0.0)

stats_rand_gen_ibinomial_negative — Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).

Description

int stats_rand_gen_ibinomial_negative ( int $n , float $p )
Warning

This function is currently not documented; only its argument list is available.

Parameters

n

p

Return Values

stats_rand_gen_gamma
stats_rand_gen_ibinomial
Statistic Functions


Generates random integer between 1 and 2147483562

stats_rand_gen_ibinomial
stats_rand_gen_ipoisson
Statistic Functions
PHP Manual

stats_rand_gen_int

(PECL stats >= 1.0.0)

stats_rand_gen_int — Generates random integer between 1 and 2147483562

Description

int stats_rand_gen_int ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

stats_rand_gen_ibinomial
stats_rand_gen_ipoisson
Statistic Functions


Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).

stats_rand_gen_int
stats_rand_gen_iuniform
Statistic Functions
PHP Manual

stats_rand_gen_ipoisson

(PECL stats >= 1.0.0)

stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).

Description

int stats_rand_gen_ipoisson ( float $mu )
Warning

This function is currently not documented; only its argument list is available.

Parameters

mu

Return Values

stats_rand_gen_int
stats_rand_gen_iuniform
Statistic Functions


Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

stats_rand_gen_ipoisson
stats_rand_gen_noncenral_chisquare
Statistic Functions
PHP Manual

stats_rand_gen_iuniform

(PECL stats >= 1.0.0)

stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

Description

int stats_rand_gen_iuniform ( int $low , int $high )
Warning

This function is currently not documented; only its argument list is available.

Parameters

low

high

Return Values

stats_rand_gen_ipoisson
stats_rand_gen_noncenral_chisquare
Statistic Functions


Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0

stats_rand_gen_iuniform
stats_rand_gen_noncentral_f
Statistic Functions
PHP Manual

stats_rand_gen_noncenral_chisquare

(PECL stats >= 1.0.0)

stats_rand_gen_noncenral_chisquare — Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0

Description

float stats_rand_gen_noncenral_chisquare ( float $df , float $xnonc )
Warning

This function is currently not documented; only its argument list is available.

Parameters

df

xnonc

Return Values

stats_rand_gen_iuniform
stats_rand_gen_noncentral_f
Statistic Functions


Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central 

stats_rand_gen_noncenral_chisquare
stats_rand_gen_noncentral_t
Statistic Functions
PHP Manual

stats_rand_gen_noncentral_f

(PECL stats >= 1.0.0)

stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central denominator chisquare variate.

Description

float stats_rand_gen_noncentral_f ( float $dfn , float $dfd , float $xnonc )
Warning

This function is currently not documented; only its argument list is available.

Parameters

dfn

dfd

xnonc

Return Values

stats_rand_gen_noncenral_chisquare
stats_rand_gen_noncentral_t
Statistic Functions


Generates a single random deviate from a noncentral T distribution

stats_rand_gen_noncentral_f
stats_rand_gen_normal
Statistic Functions
PHP Manual

stats_rand_gen_noncentral_t

(PECL stats >= 1.0.0)

stats_rand_gen_noncentral_t — Generates a single random deviate from a noncentral T distribution

Description

float stats_rand_gen_noncentral_t ( float $df , float $xnonc )
Warning

This function is currently not documented; only its argument list is available.

Parameters

df

xnonc

Return Values

stats_rand_gen_noncentral_f
stats_rand_gen_normal
Statistic Functions


Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.

stats_rand_gen_noncentral_t
stats_rand_gen_t
Statistic Functions
PHP Manual

stats_rand_gen_normal

(PECL stats >= 1.0.0)

stats_rand_gen_normal — Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.

Description

float stats_rand_gen_normal ( float $av , float $sd )
Warning

This function is currently not documented; only its argument list is available.

Parameters

av

sd

Return Values

stats_rand_gen_noncentral_t
stats_rand_gen_t
Statistic Functions


Generates a single random deviate from a T distribution

stats_rand_gen_normal
stats_rand_get_seeds
Statistic Functions
PHP Manual

stats_rand_gen_t

(PECL stats >= 1.0.0)

stats_rand_gen_t — Generates a single random deviate from a T distribution

Description

float stats_rand_gen_t ( float $df )
Warning

This function is currently not documented; only its argument list is available.

Parameters

df

Return Values

stats_rand_gen_normal
stats_rand_get_seeds
Statistic Functions


Not documented

stats_rand_gen_t
stats_rand_phrase_to_seeds
Statistic Functions
PHP Manual

stats_rand_get_seeds

(PECL stats >= 1.0.0)

stats_rand_get_seeds — Not documented

Description

array stats_rand_get_seeds ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

stats_rand_gen_t
stats_rand_phrase_to_seeds
Statistic Functions


generate two seeds for the RGN random number generator

stats_rand_get_seeds
stats_rand_ranf
Statistic Functions
PHP Manual

stats_rand_phrase_to_seeds

(PECL stats >= 1.0.0)

stats_rand_phrase_to_seeds — generate two seeds for the RGN random number generator

Description

array stats_rand_phrase_to_seeds ( string $phrase )
Warning

This function is currently not documented; only its argument list is available.

Parameters

phrase

Return Values

stats_rand_get_seeds
stats_rand_ranf
Statistic Functions


Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator

stats_rand_phrase_to_seeds
stats_rand_setall
Statistic Functions
PHP Manual

stats_rand_ranf

(PECL stats >= 1.0.0)

stats_rand_ranf — Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator

Description

float stats_rand_ranf ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

stats_rand_phrase_to_seeds
stats_rand_setall
Statistic Functions


Not documented

stats_rand_ranf
stats_skew
Statistic Functions
PHP Manual

stats_rand_setall

(PECL stats >= 1.0.0)

stats_rand_setall — Not documented

Description

void stats_rand_setall ( int $iseed1 , int $iseed2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

iseed1

iseed2

Return Values

stats_rand_ranf
stats_skew
Statistic Functions


Computes the skewness of the data in the array

stats_rand_setall
stats_standard_deviation
Statistic Functions
PHP Manual

stats_skew

(PECL stats >= 1.0.0)

stats_skew — Computes the skewness of the data in the array

Description

float stats_skew ( array $a )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

Return Values

stats_rand_setall
stats_standard_deviation
Statistic Functions


Returns the standard deviation

stats_skew
stats_stat_binomial_coef
Statistic Functions
PHP Manual

stats_standard_deviation

(PECL stats >= 1.0.0)

stats_standard_deviation — Returns the standard deviation

Description

float stats_standard_deviation ( array $a [, bool $sample = false ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

sample

Return Values

stats_skew
stats_stat_binomial_coef
Statistic Functions


Not documented

stats_standard_deviation
stats_stat_correlation
Statistic Functions
PHP Manual

stats_stat_binomial_coef

(PECL stats >= 1.0.0)

stats_stat_binomial_coef — Not documented

Description

float stats_stat_binomial_coef ( int $x , int $n )
Warning

This function is currently not documented; only its argument list is available.

Parameters

x

n

Return Values

stats_standard_deviation
stats_stat_correlation
Statistic Functions


Not documented

stats_stat_binomial_coef
stats_stat_gennch
Statistic Functions
PHP Manual

stats_stat_correlation

(PECL stats >= 1.0.0)

stats_stat_correlation — Not documented

Description

float stats_stat_correlation ( array $arr1 , array $arr2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

arr1

arr2

Return Values

stats_stat_binomial_coef
stats_stat_gennch
Statistic Functions


Not documented

stats_stat_correlation
stats_stat_independent_t
Statistic Functions
PHP Manual

stats_stat_gennch

(PECL stats >= 1.0.0)

stats_stat_gennch — Not documented

Description

float stats_stat_gennch ( int $n )
Warning

This function is currently not documented; only its argument list is available.

Parameters

n

Return Values

stats_stat_correlation
stats_stat_independent_t
Statistic Functions


Not documented

stats_stat_gennch
stats_stat_innerproduct
Statistic Functions
PHP Manual

stats_stat_independent_t

(PECL stats >= 1.0.0)

stats_stat_independent_t — Not documented

Description

float stats_stat_independent_t ( array $arr1 , array $arr2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

arr1

arr2

Return Values

stats_stat_gennch
stats_stat_innerproduct
Statistic Functions


stats_stat_independent_t
stats_stat_noncentral_t
Statistic Functions
PHP Manual

stats_stat_innerproduct

(PECL stats >= 1.0.0)

stats_stat_innerproduct —

Description

float stats_stat_innerproduct ( array $arr1 , array $arr2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

arr1

arr2

Return Values

stats_stat_independent_t
stats_stat_noncentral_t
Statistic Functions


Calculates any one parameter of the noncentral t distribution give values for the others.

stats_stat_innerproduct
stats_stat_paired_t
Statistic Functions
PHP Manual

stats_stat_noncentral_t

(PECL stats >= 1.0.0)

stats_stat_noncentral_t — Calculates any one parameter of the noncentral t distribution give values for the others.

Description

float stats_stat_noncentral_t ( float $par1 , float $par2 , float $par3 , int $which )
Warning

This function is currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_stat_innerproduct
stats_stat_paired_t
Statistic Functions


Not documented

stats_stat_noncentral_t
stats_stat_percentile
Statistic Functions
PHP Manual

stats_stat_paired_t

(PECL stats >= 1.0.0)

stats_stat_paired_t — Not documented

Description

float stats_stat_paired_t ( array $arr1 , array $arr2 )
Warning

This function is currently not documented; only its argument list is available.

Parameters

arr1

arr2

Return Values

stats_stat_noncentral_t
stats_stat_percentile
Statistic Functions


Not documented

stats_stat_paired_t
stats_stat_powersum
Statistic Functions
PHP Manual

stats_stat_percentile

(PECL stats >= 1.0.0)

stats_stat_percentile — Not documented

Description

float stats_stat_percentile ( float $df , float $xnonc )
Warning

This function is currently not documented; only its argument list is available.

Parameters

df

xnonc

Return Values

stats_stat_paired_t
stats_stat_powersum
Statistic Functions


Not documented

stats_stat_percentile
stats_variance
Statistic Functions
PHP Manual

stats_stat_powersum

(PECL stats >= 1.0.0)

stats_stat_powersum — Not documented

Description

float stats_stat_powersum ( array $arr , float $power )
Warning

This function is currently not documented; only its argument list is available.

Parameters

arr

power

Return Values

stats_stat_percentile
stats_variance
Statistic Functions


Returns the population variance

stats_stat_powersum
Non-Text MIME Output
Statistic Functions
PHP Manual

stats_variance

(PECL stats >= 1.0.0)

stats_variance — Returns the population variance

Description

float stats_variance ( array $a [, bool $sample = false ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

sample

Return Values

stats_stat_powersum
Non-Text MIME Output
Statistic Functions


Format a local time/date according to locale settings

mktime
strptime
Date/Time Functions
PHP Manual

strftime

(PHP 4, PHP 5)

strftime — Format a local time/date according to locale settings

Description

string strftime ( string $format [, int $timestamp = time() ] )

Format the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

Not all conversion specifiers may be supported by your C library, in which case they will not be supported by PHP's strftime(). Additionally, not all platforms support negative timestamps, so your date range may be limited to no earlier than the Unix epoch. This means that %e, %T, %R and, %D (and possibly others) - as well as dates prior to Jan 1, 1970 - will not work on Windows, some Linux distributions, and a few other operating systems. For Windows systems, a complete overview of supported conversion specifiers can be found at » MSDN.

Parameters

format

The following characters are recognized in the format parameter string
format | Description | Example returned values
Day --- ---
%a | An abbreviated textual representation of the day | Sun through Sat
%A | A full textual representation of the day | Sunday through Saturday
%d | Two-digit day of the month (with leading zeros) | 01 to 31
%e | Day of the month, with a space preceding single digits | 1 to 31
%j | Day of the year, 3 digits with leading zeros | 001 to 366
%u | ISO-8601 numeric representation of the day of the week | 1 (for Monday) though 7 (for Sunday)
%w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday)
Week --- ---
%U | Week number of the given year, starting with the first Sunday as the first week | 13 (for the 13th full week of the year)
%V | ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week | 01 through 53 (where 53 accounts for an overlapping week)
%W | A numeric representation of the week of the year, starting with the first Monday as the first week | 46 (for the 46th week of the year beginning with a Monday)
Month --- ---
%b | Abbreviated month name, based on the locale | Jan through Dec
%B | Full month name, based on the locale | January through December
%h | Abbreviated month name, based on the locale (an alias of %b) | Jan through Dec
%m | Two digit representation of the month | 01 (for January) through 12 (for December)
Year --- ---
%C | Two digit representation of the century (year divided by 100, truncated to an integer) | 19 for the 20th Century
%g | Two digit representation of the year going by ISO-8601:1988 standards (see %V) | Example: 09 for the week of January 6, 2009
%G | The full four-digit version of %g | Example: 2008 for the week of January 3, 2009
%y | Two digit representation of the year | Example: 09 for 2009, 79 for 1979
%Y | Four digit representation for the year | Example: 2038
Time --- ---
%H | Two digit representation of the hour in 24-hour format | 00 through 23
%I | Two digit representation of the hour in 12-hour format | 01 through 12
%l (lower-case 'L') | Hour in 12-hour format, with a space preceeding single digits | 1 through 12
%M | Two digit representation of the minute | 00 through 59
%p | UPPER-CASE 'AM' or 'PM' based on the given time | Example: AM for 00:31, PM for 22:23
%P | lower-case 'am' or 'pm' based on the given time | Example: am for 00:31, pm for 22:23
%r | Same as "%I:%M:%S %p" | Example: 09:34:17 PM for 21:34:17
%R | Same as "%H:%M" | Example: 00:35 for 12:35 AM, 16:44 for 4:44 PM
%S | Two digit representation of the second | 00 through 59
%T | Same as "%H:%M:%S" | Example: 21:34:17 for 09:34:17 PM
%X | Preferred time representation based on locale, without the date | Example: 03:59:16 or 15:59:16
%z | Either the time zone offset from UTC or the abbreviation (depends on operating system) | Example: -0500 or EST for Eastern Time
%Z | The time zone offset/abbreviation option NOT given by %z (depends on operating system) | Example: -0500 or EST for Eastern Time
Time and Date Stamps --- ---
%c | Preferred date and time stamp based on local | Example: Tue Feb 5 00:45:10 2009 for February 4, 2009 at 12:45:10 AM
%D | Same as "%m/%d/%y" | Example: 02/05/09 for February 5, 2009
%F | Same as "%Y-%m-%d" (commonly used in database datestamps) | Example: 2009-02-05 for February 5, 2009
%s | Unix Epoch Time timestamp (same as the time() function) | Example: 305815200 for September 10, 1979 08:40:00 AM
%x | Preferred date representation based on locale, without the time | Example: 02/05/09 for February 5, 2009
Miscellaneous --- ---
%n A newline character ("\n") ---
%t A Tab character ("\t") ---
%% A literal percentage character ("%") ---

Maximum length of this parameter is 1023 characters.

Warning

Contrary to ISO-9899:1999, Sun Solaris starts with Sunday as 1. As a result, %u may not function as described in this manual.

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a string formatted according format using the given timestamp or the current local time if no timestamp is given. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

As the output is dependent upon the underlying C library, some conversion specifiers are not supported. On Windows, supplying unknown conversion specifiers will result in 5 E_WARNING messages and return FALSE. On other operating systems you may not get any E_WARNING messages and the output may contain the conversion specifiers unconverted.

Changelog

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

This example will work if you have the respective locales installed in your system.

Example #1 strftime() locale examples

<?php
setlocale(LC_TIME, "C");
echo strftime("%A");
setlocale(LC_TIME, "fi_FI");
echo strftime(" in Finnish is %A,");
setlocale(LC_TIME, "fr_FR");
echo strftime(" in French %A and");
setlocale(LC_TIME, "de_DE");
echo strftime(" in German %A.\n");
?>

Example #2 ISO 8601:1988 week number example

<?php
/*     December 2002 / January 2003
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     16  17  18  19  20  21  22
52     23  24  25  26  27  28  29
1      30  31   1   2   3   4   5
2       6   7   8   9  10  11  12
3      13  14  15  16  17  18  19   */

// Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/28/2002")) . "\n";

// Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/30/2002")) . "\n";

// Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";

// Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";

/*     December 2004 / January 2005
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     13  14  15  16  17  18  19
52     20  21  22  23  24  25  26
53     27  28  29  30  31   1   2
1       3   4   5   6   7   8   9
2      10  11  12  13  14  15  16   */

// Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";

// Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";

// Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";

// Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";

?>

Notes

Note: %G and %V, which are based on ISO 8601:1988 week numbers can give unexpected (albeit correct) results if the numbering system is not thoroughly understood. See %V examples in this manual page.

See Also

  • setlocale() - Set locale information
  • mktime() - Get Unix timestamp for a date
  • strptime() - Parse a time/date generated with strftime
  • gmstrftime() - Format a GMT/UTC time/date according to locale settings
  • » Open Group specification of strftime()

mktime
strptime
Date/Time Functions


Parse a time/date generated with strftime

strftime
strtotime
Date/Time Functions
PHP Manual

strptime

(PHP 5 >= 5.1.0)

strptime — Parse a time/date generated with strftime()

Description

array strptime ( string $date , string $format )

strptime() returns an array with the date parsed, or FALSE on error.

Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME).

Parameters

date (string)

The string to parse (e.g. returned from strftime())

format (string)

The format used in date (e.g. the same as used in strftime()).

For more information about the format options, read the strftime() page.

Return Values

Returns an array or FALSE on failure.

The following parameters are returned in the array
parameters | Description
"tm_sec" | Seconds after the minute (0-61)
"tm_min" | Minutes after the hour (0-59)
"tm_hour" | Hour since midnight (0-23)
"tm_mday" | Day of the month (1-31)
"tm_mon" | Months since January (0-11)
"tm_year" | Years since 1900
"tm_wday" | Days since Sunday (0-6)
"tm_yday" | Days since January 1 (0-365)
"unparsed" | the date part which was not recognized using the specified format

Examples

Example #1 strptime() example

<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);

echo "$strf\n";

print_r(strptime($strf, $format));
?>

The above example will output something similar to:

03/10/2004 15:54:19

Array
(
    [tm_sec] => 19
    [tm_min] => 54
    [tm_hour] => 15
    [tm_mday] => 3
    [tm_mon] => 9
    [tm_year] => 104
    [tm_wday] => 0
    [tm_yday] => 276
    [unparsed] =>
)

Notes

Note: This function is not implemented on Windows platforms.

Note: "tm_sec" includes any leap seconds (currently upto 2 a year). For more information on leap seconds, see the » Wikipedia article on leap seconds.

See Also

  • strftime() - Format a local time/date according to locale settings

strftime
strtotime
Date/Time Functions


Parse about any English textual datetime description into a Unix timestamp

strptime
time
Date/Time Functions
PHP Manual

strtotime

(PHP 4, PHP 5)

strtotime — Parse about any English textual datetime description into a Unix timestamp

Description

int strtotime ( string $time [, int $now ] )

The function expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now , or the current time if now is not supplied.

This function will use the TZ environment variable (if available) to calculate the timestamp. Since PHP 5.1.0 there are easier ways to define the timezone that is used across all date/time functions. That process is explained in the date_default_timezone_get() function page.

Parameters

time

The string to parse. Before PHP 5.0.0, microseconds weren't allowed in the time, since PHP 5.0.0 they are allowed but ignored.

now

The timestamp which is used as a base for the calculation of relative dates.

Return Values

Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.3.0 | Prior to PHP 5.3.0, 24:00 was not a valid format and strtotime() returned FALSE.
5.2.7 | In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.
5.1.0 | Now returns FALSE on failure, instead of -1.
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.
5.0.2 | In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. This differs from other versions where it is correctly computed from current time.
4.4.0 | In PHP versions prior to 4.4.0, "next" is incorrectly computed as +2. A typical solution to this is to use "+1".

Examples

Example #1 A strtotime() example

<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>

Example #2 Checking for failure

<?php
$str = 'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($str)) === false) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}
?>

Notes

Note: If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07).

Note: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.

See Also

  • strptime() - Parse a time/date generated with strftime

strptime
time
Date/Time Functions


Get a URL from a Shockwave Flash movie

SWF Functions
swf_actiongotoframe
SWF Functions
PHP Manual

swf_actiongeturl

(PHP 4)

swf_actiongeturl — Get a URL from a Shockwave Flash movie

Description

void swf_actiongeturl ( string $url , string $target )

Gets the URL specified by the parameter url with the given target .

Parameters

url

The URL, as a string.

target

The target, as a string.

Return Values

No value is returned.

SWF Functions
swf_actiongotoframe
SWF Functions


Play a frame and then stop

swf_actiongeturl
swf_actiongotolabel
SWF Functions
PHP Manual

swf_actiongotoframe

(PHP 4)

swf_actiongotoframe — Play a frame and then stop

Description

void swf_actiongotoframe ( int $framenumber )

The swf_actiongotoframe() function will go to the frame specified by framenumber , play it, and then stop.

Parameters

framenumber

The frame number.

Return Values

No value is returned.

swf_actiongeturl
swf_actiongotolabel
SWF Functions


Display a frame with the specified label

swf_actiongotoframe
swf_actionnextframe
SWF Functions
PHP Manual

swf_actiongotolabel

(PHP 4)

swf_actiongotolabel — Display a frame with the specified label

Description

void swf_actiongotolabel ( string $label )

The swf_actiongotolabel() function displays the frame with the label given by the label parameter and then stops.

Parameters

label

The frame label.

Return Values

No value is returned.

swf_actiongotoframe
swf_actionnextframe
SWF Functions


Go forward one frame

swf_actiongotolabel
swf_actionplay
SWF Functions
PHP Manual

swf_actionnextframe

(PHP 4)

swf_actionnextframe — Go forward one frame

Description

void swf_actionnextframe ( void )

Go forward one frame.

Return Values

No value is returned.

See Also

  • swf_actionprevframe() - Go backwards one frame

swf_actiongotolabel
swf_actionplay
SWF Functions


Start playing the flash movie from the current frame

swf_actionnextframe
swf_actionprevframe
SWF Functions
PHP Manual

swf_actionplay

(PHP 4)

swf_actionplay — Start playing the flash movie from the current frame

Description

void swf_actionplay ( void )

Start playing the flash movie from the current frame.

Return Values

No value is returned.

See Also

  • swf_actionstop() - Stop playing the flash movie at the current frame

swf_actionnextframe
swf_actionprevframe
SWF Functions


Go backwards one frame

swf_actionplay
swf_actionsettarget
SWF Functions
PHP Manual

swf_actionprevframe

(PHP 4)

swf_actionprevframe — Go backwards one frame

Description

void swf_actionprevframe ( void )

Go backwards one frame.

Return Values

No value is returned.

See Also

  • swf_actionnextframe() - Go forward one frame

swf_actionplay
swf_actionsettarget
SWF Functions


Set the context for actions

swf_actionprevframe
swf_actionstop
SWF Functions
PHP Manual

swf_actionsettarget

(PHP 4)

swf_actionsettarget — Set the context for actions

Description

void swf_actionsettarget ( string $target )

Sets the context for all actions. You can use this to control other flash movies that are currently playing.

Parameters

target

The target, as a string.

Return Values

No value is returned.

swf_actionprevframe
swf_actionstop
SWF Functions


Stop playing the flash movie at the current frame

swf_actionsettarget
swf_actiontogglequality
SWF Functions
PHP Manual

swf_actionstop

(PHP 4)

swf_actionstop — Stop playing the flash movie at the current frame

Description

void swf_actionstop ( void )

Stop playing the flash movie at the current frame.

Return Values

No value is returned.

See Also

  • swf_actionplay() - Start playing the flash movie from the current frame

swf_actionsettarget
swf_actiontogglequality
SWF Functions


Toggle between low and high quality

swf_actionstop
swf_actionwaitforframe
SWF Functions
PHP Manual

swf_actiontogglequality

(PHP 4)

swf_actiontogglequality — Toggle between low and high quality

Description

void swf_actiontogglequality ( void )

Toggle the flash movie between high and low quality.

Return Values

No value is returned.

swf_actionstop
swf_actionwaitforframe
SWF Functions


Skip actions if a frame has not been loaded

swf_actiontogglequality
swf_addbuttonrecord
SWF Functions
PHP Manual

swf_actionwaitforframe

(PHP 4)

swf_actionwaitforframe — Skip actions if a frame has not been loaded

Description

void swf_actionwaitforframe ( int $framenumber , int $skipcount )

The swf_actionwaitforframe() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.

Parameters

framenumber

The frame number.

skipcount

The number of actions to skip.

Return Values

No value is returned.

swf_actiontogglequality
swf_addbuttonrecord
SWF Functions


Controls location, appearance and active area of the current button

swf_actionwaitforframe
swf_addcolor
SWF Functions
PHP Manual

swf_addbuttonrecord

(PHP 4)

swf_addbuttonrecord — Controls location, appearance and active area of the current button

Description

void swf_addbuttonrecord ( int $states , int $shapeid , int $depth )

Allow you to define the specifics of using a button.

Parameters

states

Defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp.

shapeid

The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button.

depth

This parameter is the placement of the button in the current frame.

Return Values

No value is returned.

Examples

Example #1 swf_addbuttonrecord() example

<?php
swf_startButton($objid, TYPE_MENUBUTTON);
swf_addButtonRecord(BSDown|BSOver, $buttonImageId, 340);
swf_onCondition(MenuEnter);
swf_actionGetUrl("http://www.example.com", "_level1");
swf_onCondition(MenuExit);
swf_actionGetUrl("", "_level1");
swf_endButton();
?>

swf_actionwaitforframe
swf_addcolor
SWF Functions


Set the global add color to the rgba value specified

swf_addbuttonrecord
swf_closefile
SWF Functions
PHP Manual

swf_addcolor

(PHP 4)

swf_addcolor — Set the global add color to the rgba value specified

Description

void swf_addcolor ( float $r , float $g , float $b , float $a )

Sets the global add color to the specified color. This color is then
implicitly used by the swf_placeobject(),
swf_modifyobject() and
swf_addbuttonrecord() functions.

The color of the object will be add by the given values when the object is written to the screen.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

These parameters can be either positive or negative.

Return Values

No value is returned.

swf_addbuttonrecord
swf_closefile
SWF Functions


Close the current Shockwave Flash file

swf_addcolor
swf_definebitmap
SWF Functions
PHP Manual

swf_closefile

(PHP 4)

swf_closefile — Close the current Shockwave Flash file

Description

void swf_closefile ([ int $return_file ] )

Close a file that was opened by the swf_openfile() function.

Parameters

return_file

If set then the contents of the SWF file are returned from the function.

Return Values

No value is returned.

Examples

Example #1 Creating a simple flash file based on user input and outputting it and saving it in a database

<?php

// The $text variable is submitted by the
// user

// Global variables for database
// access (used in the swf_savedata() function)
$DBHOST = "localhost";
$DBUSER = "sterling";
$DBPASS = "secret";

swf_openfile("php://stdout", 256, 256, 30, 1, 1, 1);

    swf_definefont(10, "Ligon-Bold");
        swf_fontsize(12);
        swf_fontslant(10);

    swf_definetext(11, $text, 1);

    swf_pushmatrix();
        swf_translate(-50, 80, 0);
        swf_placeobject(11, 60);
    swf_popmatrix();

    swf_showframe();

    swf_startdoaction();
        swf_actionstop();
    swf_enddoaction();

$data = swf_closefile(1);

$data ?
  swf_savedata($data) :
  die("Error could not save SWF file");

// void swf_savedata(string data)
// Save the generated file a database
// for later retrieval
function swf_savedata($data)
{
    global $DBHOST,
           $DBUSER,
           $DBPASS;

    $dbh = @mysql_connect($DBHOST, $DBUSER, $DBPASS);

    if (!$dbh) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    $stmt = "INSERT INTO swf_files (file) VALUES ('$data')";

    $sth = @mysql_query($stmt, $dbh);

    if (!$sth) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    @mysql_free_result($sth);
    @mysql_close($dbh);
}
?>

See Also

  • swf_openfile() - Open a new Shockwave Flash file

swf_addcolor
swf_definebitmap
SWF Functions


Define a bitmap

swf_closefile
swf_definefont
SWF Functions
PHP Manual

swf_definebitmap

(PHP 4)

swf_definebitmap — Define a bitmap

Description

void swf_definebitmap ( int $objid , string $image_name )

The swf_definebitmap() function defines a bitmap given an image.

Parameters

objid

An SWF object id.

image_name

A GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.

Return Values

No value is returned.

swf_closefile
swf_definefont
SWF Functions


Defines a font

swf_definebitmap
swf_defineline
SWF Functions
PHP Manual

swf_definefont

(PHP 4)

swf_definefont — Defines a font

Description

void swf_definefont ( int $fontid , string $fontname )

The swf_definefont() function defines a font parameter and gives it the specified id. It then sets the font given by fontname to the current font.

Parameters

fontid

The id to be given to the font.

fontname

The font so be set as current font.

Return Values

No value is returned.

See Also

  • swf_definetext() - Define a text string

swf_definebitmap
swf_defineline
SWF Functions


Define a line

swf_definefont
swf_definepoly
SWF Functions
PHP Manual

swf_defineline

(PHP 4)

swf_defineline — Define a line

Description

void swf_defineline ( int $objid , float $x1 , float $y1 , float $x2 , float $y2 , float $width )

Defines a line.

Parameters

objid

The object id.

x1

x-coordinate of start point.

y1

y-coordinate of start point.

x2

x-coordinate of end point.

y2

y-coordinate of end point.

width

The line width.

Return Values

No value is returned.

swf_definefont
swf_definepoly
SWF Functions


Define a polygon

swf_defineline
swf_definerect
SWF Functions
PHP Manual

swf_definepoly

(PHP 4)

swf_definepoly — Define a polygon

Description

void swf_definepoly ( int $objid , array $coords , int $npoints , float $width )

Defines a polygon given an array of x, y coordinates.

Parameters

objid

The object id.

coords

An array of x, y coordinates.

npoints

The number of overall points that are contained in the array given by coords

width

The width of the polygon's border, if set to 0.0 the polygon is filled.

Return Values

No value is returned.

swf_defineline
swf_definerect
SWF Functions


Define a rectangle

swf_definepoly
swf_definetext
SWF Functions
PHP Manual

swf_definerect

(PHP 4)

swf_definerect — Define a rectangle

Description

void swf_definerect ( int $objid , float $x1 , float $y1 , float $x2 , float $y2 , float $width )

Defines a rectangle with an upper left hand coordinate and a lower right hand coordinate.

Parameters

objid

The object id.

x1

x-coordinate of upper left point.

y1

y-coordinate of upper left point.

x2

x-coordinate of lower right point.

y2

y-coordinate of lower right point.

width

Width of the rectangles border, if the width is 0.0 then the rectangle is filled.

Return Values

No value is returned.

swf_definepoly
swf_definetext
SWF Functions


Define a text string

swf_definerect
swf_endbutton
SWF Functions
PHP Manual

swf_definetext

(PHP 4)

swf_definetext — Define a text string

Description

void swf_definetext ( int $objid , string $str , int $docenter )

Defines a text string using the current font and font size.

Parameters

objid

The object id.

str

The text, as a string.

docenter

The docenter is where the word is centered, if docenter is 1, then the word is centered in x.

Return Values

No value is returned.

Examples

Example #1 Horizontal text example

<?php

$Xposition = 50;
$Yposition = 50;
$Zposition = 0;
$Obj_depth = 1;

$char = 'THIS IS THE TEXT';

swf_pushmatrix();

swf_definefont (swf_nextid(), "Mod");
swf_fontsize(10);

$secondid = swf_nextid();
swf_definetext($secondid, $char, 1);
swf_translate($Xposition, $Yposition, Zposition);
swf_placeobject($secondid, $Obj_depth);
swf_popmatrix();

?>

See Also

  • swf_definefont() - Defines a font

swf_definerect
swf_endbutton
SWF Functions


End the definition of the current button

swf_definetext
swf_enddoaction
SWF Functions
PHP Manual

swf_endbutton

(PHP 4)

swf_endbutton — End the definition of the current button

Description

void swf_endbutton ( void )

The swf_endbutton() function ends the definition of the current button.

Return Values

No value is returned.

See Also

  • swf_startbutton() - Start the definition of a button

swf_definetext
swf_enddoaction
SWF Functions


End the current action

swf_endbutton
swf_endshape
SWF Functions
PHP Manual

swf_enddoaction

(PHP 4)

swf_enddoaction — End the current action

Description

void swf_enddoaction ( void )

Ends the current action started by the swf_startdoaction() function.

Return Values

No value is returned.

See Also

  • swf_startdoaction() - Start a description of an action list for the current frame

swf_endbutton
swf_endshape
SWF Functions


Completes the definition of the current shape

swf_enddoaction
swf_endsymbol
SWF Functions
PHP Manual

swf_endshape

(PHP 4)

swf_endshape — Completes the definition of the current shape

Description

void swf_endshape ( void )

The swf_endshape() completes the definition of the current shape.

Return Values

No value is returned.

See Also

  • swf_startshape() - Start a complex shape

swf_enddoaction
swf_endsymbol
SWF Functions


End the definition of a symbol

swf_endshape
swf_fontsize
SWF Functions
PHP Manual

swf_endsymbol

(PHP 4)

swf_endsymbol — End the definition of a symbol

Description

void swf_endsymbol ( void )

Ends the definition of a symbol that was started by the swf_startsymbol() function.

Return Values

No value is returned.

See Also

  • swf_startsymbol() - Define a symbol

swf_endshape
swf_fontsize
SWF Functions


Change the font size

swf_endsymbol
swf_fontslant
SWF Functions
PHP Manual

swf_fontsize

(PHP 4)

swf_fontsize — Change the font size

Description

void swf_fontsize ( float $size )

Changes the font size to the value given by the size parameter.

Parameters

size

The font size, as an integer.

Return Values

No value is returned.

swf_endsymbol
swf_fontslant
SWF Functions


Set the font slant

swf_fontsize
swf_fonttracking
SWF Functions
PHP Manual

swf_fontslant

(PHP 4)

swf_fontslant — Set the font slant

Description

void swf_fontslant ( float $slant )

Set the current font slant to the angle indicated by the slant parameter.

Parameters

slant

Positive values create a forward slant, negative values create a negative slant.

Return Values

No value is returned.

swf_fontsize
swf_fonttracking
SWF Functions


Set the current font tracking

swf_fontslant
swf_getbitmapinfo
SWF Functions
PHP Manual

swf_fonttracking

(PHP 4)

swf_fonttracking — Set the current font tracking

Description

void swf_fonttracking ( float $tracking )

Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.

Parameters

tracking

The font tracking.

Return Values

No value is returned.

swf_fontslant
swf_getbitmapinfo
SWF Functions


Get information about a bitmap

swf_fonttracking
swf_getfontinfo
SWF Functions
PHP Manual

swf_getbitmapinfo

(PHP 4)

swf_getbitmapinfo — Get information about a bitmap

Description

array swf_getbitmapinfo ( int $bitmapid )

Returns information about a bitmap.

Parameters

bitmapid

The bitmap id.

Return Values

Returns an array with the following elements:

  • "size" - The size in bytes of the bitmap.
  • "width" - The width in pixels of the bitmap.
  • "height" - The height in pixels of the bitmap.

swf_fonttracking
swf_getfontinfo
SWF Functions


Gets font information

swf_getbitmapinfo
swf_getframe
SWF Functions
PHP Manual

swf_getfontinfo

(PHP 4)

swf_getfontinfo — Gets font information

Description

array swf_getfontinfo ( void )

Gets information about the font by giving the height in pixels of a capital A and a lowercase x.

Return Values

Returns an associative array with the following parameters:

  • Aheight - The height in pixels of a capital A.
  • xheight - The height in pixels of a lowercase x.

swf_getbitmapinfo
swf_getframe
SWF Functions


Get the frame number of the current frame

swf_getfontinfo
swf_labelframe
SWF Functions
PHP Manual

swf_getframe

(PHP 4)

swf_getframe — Get the frame number of the current frame

Description

int swf_getframe ( void )

The swf_getframe() function gets the number of the current frame.

Return Values

Returns the current frame number, as an integer.

See Also

  • swf_setframe() - Switch to a specified frame

swf_getfontinfo
swf_labelframe
SWF Functions


Label the current frame

swf_getframe
swf_lookat
SWF Functions
PHP Manual

swf_labelframe

(PHP 4)

swf_labelframe — Label the current frame

Description

void swf_labelframe ( string $name )

Labels the current frame with the given name .

Parameters

name

The frame label.

Return Values

No value is returned.

swf_getframe
swf_lookat
SWF Functions


Define a viewing transformation

swf_labelframe
swf_modifyobject
SWF Functions
PHP Manual

swf_lookat

(PHP 4)

swf_lookat — Define a viewing transformation

Description

void swf_lookat ( float $view_x , float $view_y , float $view_z , float $reference_x , float $reference_y , float $reference_z , float $twist )

Defines a viewing transformation by giving the viewing position and the coordinates of a reference point in the scene.

Parameters

view_x

x-coordinate for the viewing position

view_y

y-coordinate for the viewing position

view_z

z-coordinate for the viewing position

reference_x

x-coordinate for the reference point

reference_y

y-coordinate for the reference point

reference_z

z-coordinate for the reference point

twist

Controls the rotation along with viewer's z axis.

Return Values

No value is returned.

Examples

Example #1 A simple 3D-rotation around a text

<?php

header('Content-type: application/x-shockwave-flash');

swf_openfile("php://stdout", 320, 200, 25, 1, 1, 1);

swf_ortho(-100, 100, -100, 100, -100, 100); // create 3D coordinates

swf_definefont(0, "Pix3");
swf_addcolor(0, 0, 0, 1);
swf_fontsize(10);
swf_fonttracking(0.2);

for ($i = 0; $i < 628; $i += 8) {
    $j = $i / 100;
    swf_pushmatrix();
    swf_translate(0, 0, 0);
    swf_perspective(100, 1, 0, 10);
    swf_lookat(sin($j) * 60, 50, cos($j) * 60, 0, 0, 0, 0);

    swf_definetext (1, 'HotKey@', 0);
    swf_translate(-50,0,0);

    swf_placeobject(1,10);

    swf_definetext(2, 'example.com', 0);
    swf_translate(55, 0, 0);
    swf_placeobject(2, 11);

    swf_showframe();
    swf_removeobject(10);
    swf_removeobject(11);
    swf_popmatrix();
}

swf_closefile();
?>

swf_labelframe
swf_modifyobject
SWF Functions


Modify an object

swf_lookat
swf_mulcolor
SWF Functions
PHP Manual

swf_modifyobject

(PHP 4)

swf_modifyobject — Modify an object

Description

void swf_modifyobject ( int $depth , int $how )

Updates the position and/or color of the object at the specified depth .

Parameters

depth

The depth, as an integer.

how

Determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both.

MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.

Return Values

No value is returned.

swf_lookat
swf_mulcolor
SWF Functions


Sets the global multiply color to the rgba value specified

swf_modifyobject
swf_nextid
SWF Functions
PHP Manual

swf_mulcolor

(PHP 4)

swf_mulcolor — Sets the global multiply color to the rgba value specified

Description

void swf_mulcolor ( float $r , float $g , float $b , float $a )

Sets the global multiply color to the given one. This color is then
implicitly used by the swf_placeobject(),
swf_modifyobject() and
swf_addbuttonrecord() functions.

The color of the object will be multiplied by the given color values when the object is written to the screen.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

These parameters can be either positive or negative.

Return Values

No value is returned.

swf_modifyobject
swf_nextid
SWF Functions


Returns the next free object id

swf_mulcolor
swf_oncondition
SWF Functions
PHP Manual

swf_nextid

(PHP 4)

swf_nextid — Returns the next free object id

Description

int swf_nextid ( void )

The swf_nextid() function returns the next available object id.

Return Values

Returns the id, as an integer.

swf_mulcolor
swf_oncondition
SWF Functions


Describe a transition used to trigger an action list

swf_nextid
swf_openfile
SWF Functions
PHP Manual

swf_oncondition

(PHP 4)

swf_oncondition — Describe a transition used to trigger an action list

Description

void swf_oncondition ( int $transition )

The swf_oncondition() function describes a transition that will trigger an action list.

Parameters

transition

There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:

  • IdletoOverUp
  • OverUptoIdle
  • OverUptoOverDown
  • OverDowntoOverUp
  • IdletoOverDown
  • OutDowntoIdle
  • MenuEnter (IdletoOverUp|IdletoOverDown)
  • MenuExit (OverUptoIdle|OverDowntoIdle)

For TYPE_PUSHBUTTON there are the following options:

  • IdletoOverUp
  • OverUptoIdle
  • OverUptoOverDown
  • OverDowntoOverUp
  • OverDowntoOutDown
  • OutDowntoOverDown
  • OutDowntoIdle
  • ButtonEnter (IdletoOverUp|OutDowntoOverDown)
  • ButtonExit (OverUptoIdle|OverDowntoOutDown)

Return Values

No value is returned.

swf_nextid
swf_openfile
SWF Functions


Open a new Shockwave Flash file

swf_oncondition
swf_ortho2
SWF Functions
PHP Manual

swf_openfile

(PHP 4)

swf_openfile — Open a new Shockwave Flash file

Description

void swf_openfile ( string $filename , float $width , float $height , float $framerate , float $r , float $g , float $b )

Opens a new file. This must be the first function you call, otherwise your script will not work.

Parameters

filename

The path to the SWF file. If you want to send your output to the screen, set this to php://stdout.

width

The movie width

height

The movie height

framerate

The frame rate.

r

Red value for the background.

g

Green value for the background.

b

Blue value for the background.

Return Values

No value is returned.

Changelog

Version | Description
4.0.1 | Support for php://stdout was added.

See Also

  • swf_closefile() - Close the current Shockwave Flash file

swf_oncondition
swf_ortho2
SWF Functions


Defines an orthographic mapping of user coordinates onto the current viewport

swf_ortho2
swf_perspective
SWF Functions
PHP Manual

swf_ortho

(PHP 4 >= 4.0.1)

swf_ortho — Defines an orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho ( float $xmin , float $xmax , float $ymin , float $ymax , float $zmin , float $zmax )

Defines an 3D orthographic mapping of user coordinates onto the current viewport.

Parameters

xmin

xmax

ymin

ymax

zmin

zmax

Return Values

No value is returned.

See Also

  • swf_ortho2() - Defines 2D orthographic mapping of user coordinates onto the current viewport

swf_ortho2
swf_perspective
SWF Functions


Defines 2D orthographic mapping of user coordinates onto the current viewport

swf_openfile
swf_ortho
SWF Functions
PHP Manual

swf_ortho2

(PHP 4)

swf_ortho2 — Defines 2D orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho2 ( float $xmin , float $xmax , float $ymin , float $ymax )

Defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie.

If a perspective transformation is desired, swf_perspective() can be used.

Parameters

xmin

xmax

ymin

ymax

Return Values

No value is returned.

See Also

  • swf_ortho() - Defines an orthographic mapping of user coordinates onto the current viewport

swf_openfile
swf_ortho
SWF Functions


Define a perspective projection transformation

swf_ortho
swf_placeobject
SWF Functions
PHP Manual

swf_perspective

(PHP 4)

swf_perspective — Define a perspective projection transformation

Description

void swf_perspective ( float $fovy , float $aspect , float $near , float $far )

Defines a perspective projection transformation.

Note: Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.

Parameters

fovy

A field-of-view angle in the y direction.

aspect

The aspect ratio of the viewport that is being drawn onto.

near

The near clipping plane.

far

The far clipping plane.

Return Values

No value is returned.

swf_ortho
swf_placeobject
SWF Functions


Place an object onto the screen

swf_perspective
swf_polarview
SWF Functions
PHP Manual

swf_placeobject

(PHP 4)

swf_placeobject — Place an object onto the screen

Description

void swf_placeobject ( int $objid , int $depth )

Places the object in the current frame at a specified depth .

This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.

Parameters

objid

The object id.

depth

Must be between 1 and 65535.

Return Values

No value is returned.

swf_perspective
swf_polarview
SWF Functions


Define the viewer's position with polar coordinates

swf_placeobject
swf_popmatrix
SWF Functions
PHP Manual

swf_polarview

(PHP 4)

swf_polarview — Define the viewer's position with polar coordinates

Description

void swf_polarview ( float $dist , float $azimuth , float $incidence , float $twist )

The swf_polarview() function defines the viewer's position in polar coordinates.

Parameters

dist

The distance between the viewpoint to the world space origin.

azimuth

Defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis.

incidence

Defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis.

twist

Specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.

Return Values

No value is returned.

swf_placeobject
swf_popmatrix
SWF Functions


Restore a previous transformation matrix

swf_polarview
swf_posround
SWF Functions
PHP Manual

swf_popmatrix

(PHP 4)

swf_popmatrix — Restore a previous transformation matrix

Description

void swf_popmatrix ( void )

Pushes the current transformation matrix back onto the stack.

Return Values

No value is returned.

See Also

  • swf_pushmatrix() - Push the current transformation matrix back unto the stack

swf_polarview
swf_posround
SWF Functions


Enables or Disables the rounding of the translation when objects are placed or moved

swf_popmatrix
swf_pushmatrix
SWF Functions
PHP Manual

swf_posround

(PHP 4)

swf_posround — Enables or Disables the rounding of the translation when objects are placed or moved

Description

void swf_posround ( int $round )

Enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled.

Parameters

round

Whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.

Return Values

No value is returned.

swf_popmatrix
swf_pushmatrix
SWF Functions


Push the current transformation matrix back unto the stack

swf_posround
swf_removeobject
SWF Functions
PHP Manual

swf_pushmatrix

(PHP 4)

swf_pushmatrix — Push the current transformation matrix back unto the stack

Description

void swf_pushmatrix ( void )

Pushes the current transformation matrix back onto the stack.

Return Values

No value is returned.

See Also

  • swf_popmatrix() - Restore a previous transformation matrix

swf_posround
swf_removeobject
SWF Functions


Remove an object

swf_pushmatrix
swf_rotate
SWF Functions
PHP Manual

swf_removeobject

(PHP 4)

swf_removeobject — Remove an object

Description

void swf_removeobject ( int $depth )

Removes the last object drawn at the depth specified by depth .

Parameters

depth

The depth, as an integer.

Return Values

No value is returned.

swf_pushmatrix
swf_rotate
SWF Functions


Rotate the current transformation

swf_removeobject
swf_scale
SWF Functions
PHP Manual

swf_rotate

(PHP 4)

swf_rotate — Rotate the current transformation

Description

void swf_rotate ( float $angle , string $axis )

Rotates the current transformation by a given angle around the given axis .

Parameters

angle

The rotation angle.

axis

The axis. Valid values axis are x (the x axis), y (the y axis) or z (the z axis).

Return Values

No value is returned.

swf_removeobject
swf_scale
SWF Functions


Scale the current transformation

swf_rotate
swf_setfont
SWF Functions
PHP Manual

swf_scale

(PHP 4)

swf_scale — Scale the current transformation

Description

void swf_scale ( float $x , float $y , float $z )

The swf_scale() scales curve coordinates by the given value.

Parameters

x

x scale factor.

y

y scale factor.

z

z scale factor.

Return Values

No value is returned.

swf_rotate
swf_setfont
SWF Functions


Change the current font

swf_scale
swf_setframe
SWF Functions
PHP Manual

swf_setfont

(PHP 4)

swf_setfont — Change the current font

Description

void swf_setfont ( int $fontid )

The swf_setfont() sets the current font to the value given by the fontid parameter.

Parameters

fontid

The font identifier.

Return Values

No value is returned.

swf_scale
swf_setframe
SWF Functions


Switch to a specified frame

swf_setfont
swf_shapearc
SWF Functions
PHP Manual

swf_setframe

(PHP 4)

swf_setframe — Switch to a specified frame

Description

void swf_setframe ( int $framenumber )

Changes the active frame to the specified on.

Parameters

framenumber

The frame number to be set.

Return Values

No value is returned.

See Also

  • swf_getframe() - Get the frame number of the current frame

swf_setfont
swf_shapearc
SWF Functions


Draw a circular arc

swf_setframe
swf_shapecurveto3
SWF Functions
PHP Manual

swf_shapearc

(PHP 4)

swf_shapearc — Draw a circular arc

Description

void swf_shapearc ( float $x , float $y , float $r , float $ang1 , float $ang2 )

Draws a circular arc.

Parameters

x

x-coordinate of the center.

y

y-coordinate of the center.

r

The arc radius.

ang1

The start angle.

ang2

The end angle.

Return Values

No value is returned.

swf_setframe
swf_shapecurveto3
SWF Functions


Draw a quadratic bezier curve between two points

swf_shapecurveto3
swf_shapefillbitmapclip
SWF Functions
PHP Manual

swf_shapecurveto

(PHP 4)

swf_shapecurveto — Draw a quadratic bezier curve between two points

Description

void swf_shapecurveto ( float $x1 , float $y1 , float $x2 , float $y2 )

Draws a quadratic bezier curve from the current location, though the two given points.

The current position is then set to the point defined by the x2 and y2 parameters.

Parameters

x1

x-coordinate of the first point.

y1

y-coordinate of the first point.

x2

x-coordinate of the second point.

y2

y-coordinate of the second point.

Return Values

No value is returned.

See Also

  • swf_shapecurveto3() - Draw a cubic bezier curve

swf_shapecurveto3
swf_shapefillbitmapclip
SWF Functions


Draw a cubic bezier curve

swf_shapearc
swf_shapecurveto
SWF Functions
PHP Manual

swf_shapecurveto3

(PHP 4)

swf_shapecurveto3 — Draw a cubic bezier curve

Description

void swf_shapecurveto3 ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Draw a cubic bezier curve using the given coordinates.

The current position is then set to the x3 ,y3 coordinate.

Parameters

x1

x-coordinate of the first off curve control point.

y1

y-coordinate of the first off curve control point.

x2

x-coordinate of the second off curve control point.

y2

y-coordinate of the second off curve control point.

x3

x-coordinate of the endpoint.

y3

y-coordinate of the endpoint.

Return Values

No value is returned.

See Also

  • swf_shapecurveto() - Draw a quadratic bezier curve between two points

swf_shapearc
swf_shapecurveto
SWF Functions


Set current fill mode to clipped bitmap

swf_shapecurveto
swf_shapefillbitmaptile
SWF Functions
PHP Manual

swf_shapefillbitmapclip

(PHP 4)

swf_shapefillbitmapclip — Set current fill mode to clipped bitmap

Description

void swf_shapefillbitmapclip ( int $bitmapid )

Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap.

Parameters

bitmapid

The bitmap id.

Return Values

No value is returned.

See Also

  • swf_shapefillbitmaptile() - Set current fill mode to tiled bitmap

swf_shapecurveto
swf_shapefillbitmaptile
SWF Functions


Set current fill mode to tiled bitmap

swf_shapefillbitmapclip
swf_shapefilloff
SWF Functions
PHP Manual

swf_shapefillbitmaptile

(PHP 4)

swf_shapefillbitmaptile — Set current fill mode to tiled bitmap

Description

void swf_shapefillbitmaptile ( int $bitmapid )

Sets the fill to bitmap tile, empty spaces will be filled by the bitmap.

Parameters

bitmapid

The bitmap id.

Return Values

No value is returned.

See Also

  • swf_shapefillbitmapclip() - Set current fill mode to clipped bitmap

swf_shapefillbitmapclip
swf_shapefilloff
SWF Functions


Turns off filling

swf_shapefillbitmaptile
swf_shapefillsolid
SWF Functions
PHP Manual

swf_shapefilloff

(PHP 4)

swf_shapefilloff — Turns off filling

Description

void swf_shapefilloff ( void )

Turns off filling for the current shape.

Return Values

No value is returned.

swf_shapefillbitmaptile
swf_shapefillsolid
SWF Functions


Set the current fill style to the specified color

swf_shapefilloff
swf_shapelinesolid
SWF Functions
PHP Manual

swf_shapefillsolid

(PHP 4)

swf_shapefillsolid — Set the current fill style to the specified color

Description

void swf_shapefillsolid ( float $r , float $g , float $b , float $a )

Sets the current fill style to solid, and then sets the fill color to the given color.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

Return Values

No value is returned.

swf_shapefilloff
swf_shapelinesolid
SWF Functions


Set the current line style

swf_shapefillsolid
swf_shapelineto
SWF Functions
PHP Manual

swf_shapelinesolid

(PHP 4)

swf_shapelinesolid — Set the current line style

Description

void swf_shapelinesolid ( float $r , float $g , float $b , float $a , float $width )

Sets the current line style to the given color and width.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

width

The line width. If 0.0 is given then no lines are drawn.

Return Values

No value is returned.

swf_shapefillsolid
swf_shapelineto
SWF Functions


Draw a line

swf_shapelinesolid
swf_shapemoveto
SWF Functions
PHP Manual

swf_shapelineto

(PHP 4)

swf_shapelineto — Draw a line

Description

void swf_shapelineto ( float $x , float $y )

Draws a line to the x and y coordinates. The current position is then set to that point.

Parameters

x

x-coordinate of the target.

y

y-coordinate of the target.

Return Values

No value is returned.

swf_shapelinesolid
swf_shapemoveto
SWF Functions


Move the current position

swf_shapelineto
swf_showframe
SWF Functions
PHP Manual

swf_shapemoveto

(PHP 4)

swf_shapemoveto — Move the current position

Description

void swf_shapemoveto ( float $x , float $y )

Moves the current position to the given point.

Parameters

x

x-coordinate of the target.

y

y-coordinate of the target.

Return Values

No value is returned.

swf_shapelineto
swf_showframe
SWF Functions


Display the current frame

swf_shapemoveto
swf_startbutton
SWF Functions
PHP Manual

swf_showframe

(PHP 4)

swf_showframe — Display the current frame

Description

void swf_showframe ( void )

Outputs the current frame.

Return Values

No value is returned.

swf_shapemoveto
swf_startbutton
SWF Functions


Start the definition of a button

swf_showframe
swf_startdoaction
SWF Functions
PHP Manual

swf_startbutton

(PHP 4)

swf_startbutton — Start the definition of a button

Description

void swf_startbutton ( int $objid , int $type )

Starts the definition of a button.

Parameters

objid

The object id.

type

Can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.

Return Values

No value is returned.

See Also

  • swf_endbutton() - End the definition of the current button

swf_showframe
swf_startdoaction
SWF Functions


Start a description of an action list for the current frame

swf_startbutton
swf_startshape
SWF Functions
PHP Manual

swf_startdoaction

(PHP 4)

swf_startdoaction — Start a description of an action list for the current frame

Description

void swf_startdoaction ( void )

Starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.

Return Values

No value is returned.

See Also

  • swf_enddoaction() - End the current action

swf_startbutton
swf_startshape
SWF Functions


Start a complex shape

swf_startdoaction
swf_startsymbol
SWF Functions
PHP Manual

swf_startshape

(PHP 4)

swf_startshape — Start a complex shape

Description

void swf_startshape ( int $objid )

Starts a complex shape.

Parameters

objid

The object id.

Return Values

No value is returned.

See Also

  • swf_endshape() - Completes the definition of the current shape

swf_startdoaction
swf_startsymbol
SWF Functions


Define a symbol

swf_startshape
swf_textwidth
SWF Functions
PHP Manual

swf_startsymbol

(PHP 4)

swf_startsymbol — Define a symbol

Description

void swf_startsymbol ( int $objid )

Defines an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously.

Parameters

objid

The object id you want to define as a symbol.

Return Values

No value is returned.

See Also

  • swf_endsymbol() - End the definition of a symbol

swf_startshape
swf_textwidth
SWF Functions


Get the width of a string

swf_startsymbol
swf_translate
SWF Functions
PHP Manual

swf_textwidth

(PHP 4)

swf_textwidth — Get the width of a string

Description

float swf_textwidth ( string $str )

Gives the width of the string in pixels, using the current font and font size.

Parameters

str

The string.

Return Values

Returns the line width, as a float.

swf_startsymbol
swf_translate
SWF Functions


Translate the current transformations

swf_textwidth
swf_viewport
SWF Functions
PHP Manual

swf_translate

(PHP 4)

swf_translate — Translate the current transformations

Description

void swf_translate ( float $x , float $y , float $z )

Translates the current transformation by the given values.

Parameters

x

x value.

y

y value.

z

z value.

Return Values

No value is returned.

swf_textwidth
swf_viewport
SWF Functions


Select an area for future drawing

swf_translate
Process Control Extensions
SWF Functions
PHP Manual

swf_viewport

(PHP 4)

swf_viewport — Select an area for future drawing

Description

void swf_viewport ( float $xmin , float $xmax , float $ymin , float $ymax )

Selects an area for future drawing for xmin to xmax and ymin to ymax , if this function is not called the area defaults to the size of the screen.

Parameters

xmin

xmax

ymin

ymax

Return Values

No value is returned.

swf_translate
Process Control Extensions
SWF Functions


Creates a new SWFAction

SWFAction
SWFBitmap
SWFAction
PHP Manual

SWFAction->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFAction->__construct — Creates a new SWFAction

Description

SWFAction
SWFAction __construct ( string $script )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Creates a new SWFAction and compiles the given script in it.

Parameters

script

An ActionScript snippet to associate with the SWFAction. See SWFAction for more details.

SWFAction
SWFBitmap
SWFAction


Loads Bitmap object

SWFBitmap
SWFBitmap->getHeight
SWFBitmap
PHP Manual

SWFBitmap->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFBitmap->__construct — Loads Bitmap object

Description

SWFBitmap
SWFBitmap __construct ( mixed $file [, mixed $alphafile ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Creates the new SWFBitmap object from the given file .

Parameters

For both parameters you can provide a file pointer returned by fopen() or the image data, as a binary string.

file

Note: We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!

You can't import png images directly, though- have to use the png2dbl utility to make a dbl ("define bits lossless") file from the png. The reason for this is that I don't want a dependency on the png library in ming- autoconf should solve this, but that's not set up yet.

alphafile

An MSK file to be used as an alpha mask for a JPEG image.

Examples

Example #1 Importing a DBL file

<?php
$s = new SWFShape();
$f = $s->addFill(new SWFBitmap(file_get_contents("image.dbl")));
$s->setRightFill($f);

$s->drawLine(32, 0);
$s->drawLine(0, 32);
$s->drawLine(-32, 0);
$s->drawLine(0, -32);

$m = new SWFMovie();
$m->setDimension(32, 32);
$m->add($s);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

Example #2 Using an alpha mask

<?php

$s = new SWFShape();

// .msk file generated with "gif2mask" utility
$f = $s->addFill(new SWFBitmap(file_get_contents("alphafill.jpg"), file_get_contents("alphafill.msk")));
$s->setRightFill($f);

$s->drawLine(640, 0);
$s->drawLine(0, 480);
$s->drawLine(-640, 0);
$s->drawLine(0, -480);

$c = new SWFShape();
$c->setRightFill($c->addFill(0x99, 0x99, 0x99));
$c->drawLine(40, 0);
$c->drawLine(0, 40);
$c->drawLine(-40, 0);
$c->drawLine(0, -40);

$m = new SWFMovie();
$m->setDimension(640, 480);
$m->setBackground(0xcc, 0xcc, 0xcc);

// draw checkerboard background
for ($y=0; $y<480; $y+=40) {
  for ($x=0; $x<640; $x+=80) {
    $i = $m->add($c);
    $i->moveTo($x, $y);
  }

  $y+=40;

  for ($x=40; $x<640; $x+=80) {
    $i = $m->add($c);
    $i->moveTo($x, $y);
  }
}

$m->add($s);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFBitmap
SWFBitmap->getHeight
SWFBitmap


Returns the bitmap's height

SWFBitmap->__construct
SWFBitmap->getWidth
SWFBitmap
PHP Manual

SWFBitmap->getHeight

(PHP 4 >= 4.0.5)

SWFBitmap->getHeight — Returns the bitmap's height

Description

SWFBitmap
float getHeight ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the bitmap's height.

Return Values

Returns the bitmap height in pixels.

See Also

  • SWFBitmap->getWidth

SWFBitmap->__construct
SWFBitmap->getWidth
SWFBitmap


Returns the bitmap's width

SWFBitmap->getHeight
SWFButton
SWFBitmap
PHP Manual

SWFBitmap->getWidth

(PHP 4 >= 4.0.5)

SWFBitmap->getWidth — Returns the bitmap's width

Description

SWFBitmap
float getWidth ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the bitmap's width.

Return Values

Returns the bitmap width in pixels.

See Also

  • SWFBitmap->getHeight

SWFBitmap->getHeight
SWFButton
SWFBitmap


Adds an action

SWFButton
SWFButton->addASound
SWFButton
PHP Manual

SWFButton->addAction

(PHP 4 >= 4.0.5)

SWFButton->addAction — Adds an action

Description

SWFButton
void addAction ( SWFAction $action , int $flags )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Adds the given action to the button for the given conditions.

Parameters

action

An SWFAction, returned by SWFAction->__construct.

flags

The following flags are valid: SWFBUTTON_MOUSEOVER, SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, SWFBUTTON_MOUSEUPOUTSIDE, SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and SWFBUTTON_DRAGOVER.

Return Values

No value is returned.

See Also

  • SWFButton->addShape
  • SWFAction

SWFButton
SWFButton->addASound
SWFButton


Associates a sound with a button transition

SWFButton->addAction
SWFButton->addShape
SWFButton
PHP Manual

SWFButton->addASound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton->addASound — Associates a sound with a button transition

Description

SWFButton
SWFSoundInstance addASound ( SWFSound $sound , int $flags )
Warning

This function is currently not documented; only its argument list is available.

SWFButton->addAction
SWFButton->addShape
SWFButton


Adds a shape to a button

SWFButton->addASound
SWFButton->__construct
SWFButton
PHP Manual

SWFButton->addShape

(PHP 4 >= 4.0.5)

SWFButton->addShape — Adds a shape to a button

Description

SWFButton
void addShape ( SWFShape $shape , int $flags )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Adds the given shape to the button.

Parameters

shape

An SWFShape instance

flags

The following flags are valid: SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_DOWN and SWFBUTTON_HIT.

SWFBUTTON_HIT isn't ever displayed, it defines the hit region for the button. That is, everywhere the hit shape would be drawn is considered a "touchable" part of the button.

Return Values

No value is returned.

SWFButton->addASound
SWFButton->__construct
SWFButton


Creates a new Button

SWFButton->addShape
SWFButton->setAction
SWFButton
PHP Manual

SWFButton->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton->__construct — Creates a new Button

Description

SWFButton
SWFButton __construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Creates a new Button.

Examples

This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.

Example #1 Usual interactions with buttons

<?php

$f = new SWFFont("_serif");

$p = new SWFSprite();

function label($string)
{
  global $f;

  $t = new SWFTextField();
  $t->setFont($f);
  $t->addString($string);
  $t->setHeight(200);
  $t->setBounds(3200, 200);
  return $t;
}

function addLabel($string)
{
  global $p;

  $i = $p->add(label($string));
  $p->nextFrame();
  $p->remove($i);
}

$p->add(new SWFAction("stop();"));
addLabel("NO ACTION");
addLabel("SWFBUTTON_MOUSEUP");
addLabel("SWFBUTTON_MOUSEDOWN");
addLabel("SWFBUTTON_MOUSEOVER");
addLabel("SWFBUTTON_MOUSEOUT");
addLabel("SWFBUTTON_MOUSEUPOUTSIDE");
addLabel("SWFBUTTON_DRAGOVER");
addLabel("SWFBUTTON_DRAGOUT");

function rect($r, $g, $b)
{
  $s = new SWFShape();
  $s->setRightFill($s->addFill($r, $g, $b));
  $s->drawLine(600, 0);
  $s->drawLine(0, 600);
  $s->drawLine(-600, 0);
  $s->drawLine(0, -600);

  return $s;
}

$b = new SWFButton();
$b->addShape(rect(0xff, 0, 0), SWFBUTTON_UP | SWFBUTTON_HIT);
$b->addShape(rect(0, 0xff, 0), SWFBUTTON_OVER);
$b->addShape(rect(0, 0, 0xff), SWFBUTTON_DOWN);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(1);"),
          SWFBUTTON_MOUSEUP);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(2);"),
      SWFBUTTON_MOUSEDOWN);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(3);"),
      SWFBUTTON_MOUSEOVER);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(4);"),
      SWFBUTTON_MOUSEOUT);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(5);"),
      SWFBUTTON_MOUSEUPOUTSIDE);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(6);"),
      SWFBUTTON_DRAGOVER);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(7);"),
      SWFBUTTON_DRAGOUT);

$m = new SWFMovie();
$m->setDimension(4000, 3000);

$i = $m->add($p);
$i->setName("label");
$i->moveTo(400, 1900);

$i = $m->add($b);
$i->moveTo(400, 900);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.

Example #2 Drag example

<?php

$s = new SWFShape();
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->drawLine(1000,0);
$s->drawLine(0,1000);
$s->drawLine(-1000,0);
$s->drawLine(0,-1000);

$b = new SWFButton();
$b->addShape($s, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);

$b->addAction(new SWFAction("startDrag('/test', 0);"), // '0' means don't lock to mouse
      SWFBUTTON_MOUSEDOWN);

$b->addAction(new SWFAction("stopDrag();"),
      SWFBUTTON_MOUSEUP | SWFBUTTON_MOUSEUPOUTSIDE);

$p = new SWFSprite();
$p->add($b);
$p->nextFrame();

$m = new SWFMovie();
$i = $m->add($p);
$i->setName('test');
$i->moveTo(1000,1000);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFButton->addShape
SWFButton->setAction
SWFButton


Sets the action

SWFButton->__construct
SWFButton->setDown
SWFButton
PHP Manual

SWFButton->setAction

(PHP 4 >= 4.0.5)

SWFButton->setAction — Sets the action

Description

SWFButton
void setAction ( SWFAction $action )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets the action to be performed when the button is clicked.

This is a shortcut for SWFButton->addAction called with the SWFBUTTON_MOUSEUP flag.

Parameters

action

An SWFAction, returned by SWFAction->__construct.

Return Values

No value is returned.

See Also

  • SWFButton->addAction
  • SWFAction

SWFButton->__construct
SWFButton->setDown
SWFButton


Alias for addShape(shape, SWFBUTTON_DOWN)

SWFButton->setAction
SWFButton->setHit
SWFButton
PHP Manual

SWFButton->setDown

(PHP 4 >= 4.0.5)

SWFButton->setDown — Alias for addShape(shape, SWFBUTTON_DOWN)

Description

SWFButton
void setDown ( SWFShape $shape )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfbutton->setdown() alias for addShape(shape, SWFBUTTON_DOWN).

Return Values

No value is returned.

See Also

  • SWFButton->addShape
  • SWFAction

SWFButton->setAction
SWFButton->setHit
SWFButton


Alias for addShape(shape, SWFBUTTON_HIT)

SWFButton->setDown
SWFButton->setMenu
SWFButton
PHP Manual

SWFButton->setHit

(PHP 4 >= 4.0.5)

SWFButton->setHit — Alias for addShape(shape, SWFBUTTON_HIT)

Description

SWFButton
void setHit ( SWFShape $shape )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfbutton->sethit() alias for addShape(shape, SWFBUTTON_HIT).

Return Values

No value is returned.

See Also

  • SWFButton->addShape
  • SWFAction

SWFButton->setDown
SWFButton->setMenu
SWFButton


enable track as menu button behaviour

SWFButton->setHit
SWFButton->setOver
SWFButton
PHP Manual

SWFButton->setMenu

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton->setMenu — enable track as menu button behaviour

Description

SWFButton
void setMenu ( int $flag )
Warning

This function is currently not documented; only its argument list is available.

Parameters

flag

This parameter can be used for a slight different behavior of buttons. You can set it to 0 (off) or 1 (on).

Return Values

No value is returned.

SWFButton->setHit
SWFButton->setOver
SWFButton


Alias for addShape(shape, SWFBUTTON_OVER)

SWFButton->setMenu
SWFButton->setUp
SWFButton
PHP Manual

SWFButton->setOver

(PHP 4 >= 4.0.5)

SWFButton->setOver — Alias for addShape(shape, SWFBUTTON_OVER)

Description

SWFButton
void setOver ( SWFShape $shape )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfbutton->setover() alias for addShape(shape, SWFBUTTON_OVER).

Return Values

No value is returned.

See Also

  • SWFButton->addShape
  • SWFAction

SWFButton->setMenu
SWFButton->setUp
SWFButton


Alias for addShape(shape, SWFBUTTON_UP)

SWFButton->setOver
SWFDisplayItem
SWFButton
PHP Manual

SWFButton->setUp

(PHP 4 >= 4.0.5)

SWFButton->setUp — Alias for addShape(shape, SWFBUTTON_UP)

Description

SWFButton
void setUp ( SWFShape $shape )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfbutton->setup() alias for addShape(shape, SWFBUTTON_UP).

Return Values

No value is returned.

See Also

  • SWFButton->addShape
  • SWFAction

SWFButton->setOver
SWFDisplayItem
SWFButton


Adds this SWFAction to the given SWFSprite instance

SWFDisplayItem
SWFDisplayItem->addColor
SWFDisplayItem
PHP Manual

SWFDisplayItem->addAction

(PHP 4 >= 4.2.0)

SWFDisplayItem->addAction — Adds this SWFAction to the given SWFSprite instance

Description

SWFDisplayItem
void addAction ( SWFAction $action , int $flags )
Warning

This function is currently not documented; only its argument list is available.

Parameters

action

An SWFAction, returned by SWFAction->__construct.

flags

Return Values

No value is returned.

See Also

  • SWFAction

SWFDisplayItem
SWFDisplayItem->addColor
SWFDisplayItem


Adds the given color to this item's color transform

SWFDisplayItem->addAction
SWFDisplayItem->endMask
SWFDisplayItem
PHP Manual

SWFDisplayItem->addColor

(PHP 4 >= 4.0.5)

SWFDisplayItem->addColor — Adds the given color to this item's color transform

Description

SWFDisplayItem
void addColor ( int $red , int $green , int $blue [, int $a ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->addcolor() adds the color to this item's color transform. The color is given in its RGB form.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

Return Values

No value is returned.

SWFDisplayItem->addAction
SWFDisplayItem->endMask
SWFDisplayItem


Another way of defining a MASK layer

SWFDisplayItem->addColor
SWFDisplayItem->getRot
SWFDisplayItem
PHP Manual

SWFDisplayItem->endMask

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem->endMask — Another way of defining a MASK layer

Description

SWFDisplayItem
void endMask ( void )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFDisplayItem->addColor
SWFDisplayItem->getRot
SWFDisplayItem


SWFDisplayItem->endMask
SWFDisplayItem->getX
SWFDisplayItem
PHP Manual

SWFDisplayItem->getRot

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem->getRot —

Description

SWFDisplayItem
float getRot ( void )
Warning

This function is currently not documented; only its argument list is available.

SWFDisplayItem->endMask
SWFDisplayItem->getX
SWFDisplayItem


SWFDisplayItem->getRot
SWFDisplayItem->getXScale
SWFDisplayItem
PHP Manual

SWFDisplayItem->getX

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem->getX —

Description

SWFDisplayItem
float getX ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem->getY

SWFDisplayItem->getRot
SWFDisplayItem->getXScale
SWFDisplayItem


SWFDisplayItem->getX
SWFDisplayItem->getXSkew
SWFDisplayItem
PHP Manual

SWFDisplayItem->getXScale

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem->getXScale —

Description

SWFDisplayItem
float getXScale ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem->getYScale

SWFDisplayItem->getX
SWFDisplayItem->getXSkew
SWFDisplayItem


SWFDisplayItem->getXScale
SWFDisplayItem->getY
SWFDisplayItem
PHP Manual

SWFDisplayItem->getXSkew

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem->getXSkew —

Description

SWFDisplayItem
float getXSkew ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem->getYSkew

SWFDisplayItem->getXScale
SWFDisplayItem->getY
SWFDisplayItem


SWFDisplayItem->getXSkew
SWFDisplayItem->getYScale
SWFDisplayItem
PHP Manual

SWFDisplayItem->getY

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem->getY —

Description

SWFDisplayItem
float getY ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem->getX

SWFDisplayItem->getXSkew
SWFDisplayItem->getYScale
SWFDisplayItem


SWFDisplayItem->getY
SWFDisplayItem->getYSkew
SWFDisplayItem
PHP Manual

SWFDisplayItem->getYScale

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem->getYScale —

Description

SWFDisplayItem
float getYScale ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem->getXScale

SWFDisplayItem->getY
SWFDisplayItem->getYSkew
SWFDisplayItem


SWFDisplayItem->getYScale
SWFDisplayItem->move
SWFDisplayItem
PHP Manual

SWFDisplayItem->getYSkew

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem->getYSkew —

Description

SWFDisplayItem
float getYSkew ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem->getXSkew

SWFDisplayItem->getYScale
SWFDisplayItem->move
SWFDisplayItem


Moves object in relative coordinates

SWFDisplayItem->getYSkew
SWFDisplayItem->moveTo
SWFDisplayItem
PHP Manual

SWFDisplayItem->move

(PHP 4 >= 4.0.5)

SWFDisplayItem->move — Moves object in relative coordinates

Description

SWFDisplayItem
void move ( float $dx , float $dy )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->move() moves the current object by (dx ,dy ) from its current position.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem->moveTo

SWFDisplayItem->getYSkew
SWFDisplayItem->moveTo
SWFDisplayItem


Moves object in global coordinates

SWFDisplayItem->move
SWFDisplayItem->multColor
SWFDisplayItem
PHP Manual

SWFDisplayItem->moveTo

(PHP 4 >= 4.0.5)

SWFDisplayItem->moveTo — Moves object in global coordinates

Description

SWFDisplayItem
void moveTo ( float $x , float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->moveto() moves the current object to (x ,y ) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem->move

SWFDisplayItem->move
SWFDisplayItem->multColor
SWFDisplayItem


Multiplies the item's color transform

SWFDisplayItem->moveTo
SWFDisplayItem->remove
SWFDisplayItem
PHP Manual

SWFDisplayItem->multColor

(PHP 4 >= 4.0.5)

SWFDisplayItem->multColor — Multiplies the item's color transform

Description

SWFDisplayItem
void multColor ( float $red , float $green , float $blue [, float $a ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->multcolor() multiplies the item's color transform by the given values.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Parameters

These parameters are floats between 0.0 and 1.0:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Return Values

No value is returned.

Examples

This simple example will modify your picture's atmosphere to Halloween (use a landscape or bright picture).

Example #1 swfdisplayitem->multcolor() example

<?php

$b = new SWFBitmap(file_get_contents("backyard.jpg"));
// note use your own picture :-)
$s = new SWFShape();
$s->setRightFill($s->addFill($b));
$s->drawLine($b->getWidth(), 0);
$s->drawLine(0, $b->getHeight());
$s->drawLine(-$b->getWidth(), 0);
$s->drawLine(0, -$b->getHeight());

$m = new SWFMovie();
$m->setDimension($b->getWidth(), $b->getHeight());

$i = $m->add($s);

for ($n=0; $n<=20; ++$n) {
  $i->multColor(1.0-$n/10, 1.0, 1.0);
  $i->addColor(0xff*$n/20, 0, 0);
  $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFDisplayItem->moveTo
SWFDisplayItem->remove
SWFDisplayItem


Removes the object from the movie

SWFDisplayItem->multColor
SWFDisplayItem->rotate
SWFDisplayItem
PHP Manual

SWFDisplayItem->remove

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem->remove — Removes the object from the movie

Description

SWFDisplayItem
void remove ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->remove() removes this object from the movie's display list.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

  • SWFMovie->add

SWFDisplayItem->multColor
SWFDisplayItem->rotate
SWFDisplayItem


Rotates in relative coordinates

SWFDisplayItem->remove
SWFDisplayItem->rotateTo
SWFDisplayItem
PHP Manual

SWFDisplayItem->rotate

(PHP 4 >= 4.0.5)

SWFDisplayItem->rotate — Rotates in relative coordinates

Description

SWFDisplayItem
void rotate ( float $angle )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->rotate() rotates the current object by angle degrees from its current rotation.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem->rotateTo

SWFDisplayItem->remove
SWFDisplayItem->rotateTo
SWFDisplayItem


Rotates the object in global coordinates

SWFDisplayItem->rotate
SWFDisplayItem->scale
SWFDisplayItem
PHP Manual

SWFDisplayItem->rotateTo

(PHP 4 >= 4.0.5)

SWFDisplayItem->rotateTo — Rotates the object in global coordinates

Description

SWFDisplayItem
void rotateTo ( float $angle )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->rotateto() set the current object rotation to angle degrees in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

Examples

This example bring three rotating string from the background to the foreground. Pretty nice.

Example #1 swfdisplayitem->rotateto() example

<?php
$thetext =  "ming!";

$f = new SWFFont("Bauhaus 93.fdb");

$m = new SWFMovie();
$m->setRate(24.0);
$m->setDimension(2400, 1600);
$m->setBackground(0xff, 0xff, 0xff);

// functions with huge numbers of arbitrary
// arguments are always a good idea!  Really!

function text($r, $g, $b, $a, $rot, $x, $y, $scale, $string)
{
  global $f, $m;

  $t = new SWFText();
  $t->setFont($f);
  $t->setColor($r, $g, $b, $a);
  $t->setHeight(960);
  $t->moveTo(-($f->getWidth($string))/2, $f->getAscent()/2);
  $t->addString($string);

  // we can add properties just like a normal PHP var,
  // as long as the names aren't already used.
  // e.g., we can't set $i->scale, because that's a function

  $i = $m->add($t);
  $i->x = $x;
  $i->y = $y;
  $i->rot = $rot;
  $i->s = $scale;
  $i->rotateTo($rot);
  $i->scale($scale, $scale);

  // but the changes are local to the function, so we have to
  // return the changed object.  kinda weird..

  return $i;
}

function step($i)
{
  $oldrot = $i->rot;
  $i->rot = 19*$i->rot/20;
  $i->x = (19*$i->x + 1200)/20;
  $i->y = (19*$i->y + 800)/20;
  $i->s = (19*$i->s + 1.0)/20;

  $i->rotateTo($i->rot);
  $i->scaleTo($i->s, $i->s);
  $i->moveTo($i->x, $i->y);

  return $i;
}

// see?  it sure paid off in legibility:

$i1 = text(0xff, 0x33, 0x33, 0xff, 900, 1200, 800, 0.03, $thetext);
$i2 = text(0x00, 0x33, 0xff, 0x7f, -560, 1200, 800, 0.04, $thetext);
$i3 = text(0xff, 0xff, 0xff, 0x9f, 180, 1200, 800, 0.001, $thetext);

for ($i=1; $i<=100; ++$i) {
  $i1 = step($i1);
  $i2 = step($i2);
  $i3 = step($i3);

  $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

See Also

  • SWFDisplayItem->rotate

SWFDisplayItem->rotate
SWFDisplayItem->scale
SWFDisplayItem


Scales the object in relative coordinates

SWFDisplayItem->rotateTo
SWFDisplayItem->scaleTo
SWFDisplayItem
PHP Manual

SWFDisplayItem->scale

(PHP 4 >= 4.0.5)

SWFDisplayItem->scale — Scales the object in relative coordinates

Description

SWFDisplayItem
void scale ( float $dx , float $dy )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->scale() scales the current object by (dx ,dy ) from its current size.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem->scaleTo

SWFDisplayItem->rotateTo
SWFDisplayItem->scaleTo
SWFDisplayItem


Scales the object in global coordinates

SWFDisplayItem->scale
SWFDisplayItem->setDepth
SWFDisplayItem
PHP Manual

SWFDisplayItem->scaleTo

(PHP 4 >= 4.0.5)

SWFDisplayItem->scaleTo — Scales the object in global coordinates

Description

SWFDisplayItem
void scaleTo ( float $x [, float $y ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->scaleto() scales the current object to (x ,y ) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem->scale

SWFDisplayItem->scale
SWFDisplayItem->setDepth
SWFDisplayItem


Sets z-order

SWFDisplayItem->scaleTo
SWFDisplayItem->setMaskLevel
SWFDisplayItem
PHP Manual

SWFDisplayItem->setDepth

(PHP 4 >= 4.0.5)

SWFDisplayItem->setDepth — Sets z-order

Description

SWFDisplayItem
void setDepth ( int $depth )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->setdepth() sets the object's z-order to depth . Depth defaults to the order in which instances are created (by adding a shape/text to a movie)- newer ones are on top of older ones. If two objects are given the same depth, only the later-defined one can be moved.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

SWFDisplayItem->scaleTo
SWFDisplayItem->setMaskLevel
SWFDisplayItem


Defines a MASK layer at level

SWFDisplayItem->setDepth
SWFDisplayItem->setMatrix
SWFDisplayItem
PHP Manual

SWFDisplayItem->setMaskLevel

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem->setMaskLevel — Defines a MASK layer at level

Description

SWFDisplayItem
void setMaskLevel ( int $level )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFDisplayItem->setDepth
SWFDisplayItem->setMatrix
SWFDisplayItem


Sets the item's transform matrix

SWFDisplayItem->setMaskLevel
SWFDisplayItem->setName
SWFDisplayItem
PHP Manual

SWFDisplayItem->setMatrix

(PHP 4 >= 4.0.5)

SWFDisplayItem->setMatrix — Sets the item's transform matrix

Description

SWFDisplayItem
void setMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFDisplayItem->setMaskLevel
SWFDisplayItem->setName
SWFDisplayItem


Sets the object's name

SWFDisplayItem->setMatrix
SWFDisplayItem->setRatio
SWFDisplayItem
PHP Manual

SWFDisplayItem->setName

(PHP 4 >= 4.0.5)

SWFDisplayItem->setName — Sets the object's name

Description

SWFDisplayItem
void setName ( string $name )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->setname() sets the object's name to name , for targetting with action script. Only useful on sprites.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

SWFDisplayItem->setMatrix
SWFDisplayItem->setRatio
SWFDisplayItem


Sets the object's ratio

SWFDisplayItem->setName
SWFDisplayItem->skewX
SWFDisplayItem
PHP Manual

SWFDisplayItem->setRatio

(PHP 4 >= 4.0.5)

SWFDisplayItem->setRatio — Sets the object's ratio

Description

SWFDisplayItem
void setRatio ( float $ratio )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->setratio() sets the object's ratio to ratio . Obviously only useful for morphs.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

Examples

This simple example will morph nicely three concentric circles.

Example #1 swfdisplayitem->setname() example

<?php

$p = new SWFMorph();

$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(0.16, 0xff, 0xff, 0xff);
$g->addEntry(0.32, 0, 0, 0);
$g->addEntry(0.48, 0xff, 0xff, 0xff);
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0xff, 0xff, 0xff);
$g->addEntry(1.00, 0, 0, 0);

$s = $p->getShape1();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.05);
$s->setLeftFill($f);
$s->movePenTo(-160, -120);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);

$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(0.16, 0xff, 0, 0);
$g->addEntry(0.32, 0, 0, 0);
$g->addEntry(0.48, 0, 0xff, 0);
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0, 0, 0xff);
$g->addEntry(1.00, 0, 0, 0);

$s = $p->getShape2();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.05);
$f->skewXTo(1.0);
$s->setLeftFill($f);
$s->movePenTo(-160, -120);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);

$m = new SWFMovie();
$m->setDimension(320, 240);
$i = $m->add($p);
$i->moveTo(160, 120);

for ($n=0; $n<=1.001; $n+=0.01) {
    $i->setRatio($n);
    $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFDisplayItem->setName
SWFDisplayItem->skewX
SWFDisplayItem


Sets the X-skew

SWFDisplayItem->setRatio
SWFDisplayItem->skewXTo
SWFDisplayItem
PHP Manual

SWFDisplayItem->skewX

(PHP 4 >= 4.0.5)

SWFDisplayItem->skewX — Sets the X-skew

Description

SWFDisplayItem
void skewX ( float $ddegrees )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->skewx() adds ddegrees to current x-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem->skewXTo
  • SWFDisplayItem->skewY
  • SWFDisplayItem->skewYTo

SWFDisplayItem->setRatio
SWFDisplayItem->skewXTo
SWFDisplayItem


Sets the X-skew

SWFDisplayItem->skewX
SWFDisplayItem->skewY
SWFDisplayItem
PHP Manual

SWFDisplayItem->skewXTo

(PHP 4 >= 4.0.5)

SWFDisplayItem->skewXTo — Sets the X-skew

Description

SWFDisplayItem
void skewXTo ( float $degrees )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->skewxto() sets the x-skew to degrees . For degrees is 1.0, it means a 45-degree forward slant. More is more forward, less is more backward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem->skewX
  • SWFDisplayItem->skewY
  • SWFDisplayItem->skewYTo

SWFDisplayItem->skewX
SWFDisplayItem->skewY
SWFDisplayItem


Sets the Y-skew

SWFDisplayItem->skewXTo
SWFDisplayItem->skewYTo
SWFDisplayItem
PHP Manual

SWFDisplayItem->skewY

(PHP 4 >= 4.0.5)

SWFDisplayItem->skewY — Sets the Y-skew

Description

SWFDisplayItem
void skewY ( float $ddegrees )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->skewy() adds ddegrees to current y-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem->skewYTo
  • SWFDisplayItem->skewX
  • SWFDisplayItem->skewXTo

SWFDisplayItem->skewXTo
SWFDisplayItem->skewYTo
SWFDisplayItem


Sets the Y-skew

SWFDisplayItem->skewY
SWFFill
SWFDisplayItem
PHP Manual

SWFDisplayItem->skewYTo

(PHP 4 >= 4.0.5)

SWFDisplayItem->skewYTo — Sets the Y-skew

Description

SWFDisplayItem
void skewYTo ( float $degrees )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfdisplayitem->skewyto() sets the y-skew to degrees . For degrees is 1.0, it means a 45-degree forward slant. More is more upward, less is more downward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem->skewY
  • SWFDisplayItem->skewX
  • SWFDisplayItem->skewXTo

SWFDisplayItem->skewY
SWFFill
SWFDisplayItem


Moves fill origin

SWFFill
SWFFill->rotateTo
SWFFill
PHP Manual

SWFFill->moveTo

(PHP 4 >= 4.0.5)

SWFFill->moveTo — Moves fill origin

Description

SWFFill
void moveTo ( float $x , float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Moves the fill origin to the given global coordinates.

Parameters

x

X-coordinate

y

Y-coordinate

Return Values

No value is returned.

SWFFill
SWFFill->rotateTo
SWFFill


Sets fill's rotation

SWFFill->moveTo
SWFFill->scaleTo
SWFFill
PHP Manual

SWFFill->rotateTo

(PHP 4 >= 4.0.5)

SWFFill->rotateTo — Sets fill's rotation

Description

SWFFill
void rotateTo ( float $angle )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets the fill rotation to the given angle .

Parameters

angle

The rotation angle, in degrees.

Return Values

No value is returned.

SWFFill->moveTo
SWFFill->scaleTo
SWFFill


Sets fill's scale

SWFFill->rotateTo
SWFFill->skewXTo
SWFFill
PHP Manual

SWFFill->scaleTo

(PHP 4 >= 4.0.5)

SWFFill->scaleTo — Sets fill's scale

Description

SWFFill
void scaleTo ( float $x [, float $y ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets the fill scale to the given coordinates.

Parameters

x

X-coordinate

y

Y-coordinate

Return Values

No value is returned.

SWFFill->rotateTo
SWFFill->skewXTo
SWFFill


Sets fill x-skew

SWFFill->scaleTo
SWFFill->skewYTo
SWFFill
PHP Manual

SWFFill->skewXTo

(PHP 4 >= 4.0.5)

SWFFill->skewXTo — Sets fill x-skew

Description

SWFFill
void skewXTo ( float $x )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets the fill x-skew to x .

Parameters

x

When x is 1.0, it is a 45-degree forward slant. More is more forward, less is more backward.

Return Values

No value is returned.

See Also

  • SWFFill->skewYTo

SWFFill->scaleTo
SWFFill->skewYTo
SWFFill


Sets fill y-skew

SWFFill->skewXTo
SWFFont
SWFFill
PHP Manual

SWFFill->skewYTo

(PHP 4 >= 4.0.5)

SWFFill->skewYTo — Sets fill y-skew

Description

SWFFill
void skewYTo ( float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets the fill y-skew to y .

Parameters

y

When y is 1.0, it is a 45-degree upward slant. More is more upward, less is more downward.

Return Values

No value is returned.

See Also

  • SWFFill->skewXTo

SWFFill->skewXTo
SWFFont
SWFFill


Loads a font definition

SWFFont
SWFFont->getAscent
SWFFont
PHP Manual

SWFFont->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont->__construct — Loads a font definition

Description

SWFFont
SWFFont __construct ( string $filename )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

If filename is the name of an FDB file (i.e., it ends in ".fdb"), load the font definition found in said file. Otherwise, create a browser-defined font reference.

FDB ("font definition block") is a very simple wrapper for the SWF DefineFont2 block which contains a full description of a font. One may create FDB files from SWT Generator template files with the included makefdb utility- look in the util directory off the main ming distribution directory.

Browser-defined fonts don't contain any information about the font other than its name. It is assumed that the font definition will be provided by the movie player. The fonts _serif, _sans, and _typewriter should always be available. For example:

<?php
$f = newSWFFont("_sans");
?>

will give you the standard sans-serif font, probably the same as what you'd get with <font name="sans-serif"> in HTML.

SWFFont
SWFFont->getAscent
SWFFont


Returns the ascent of the font, or 0 if not available

SWFFont->__construct
SWFFont->getDescent
SWFFont
PHP Manual

SWFFont->getAscent

(PHP 4 >= 4.0.5)

SWFFont->getAscent — Returns the ascent of the font, or 0 if not available

Description

SWFFont
float getAscent ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFFont->getDescent

SWFFont->__construct
SWFFont->getDescent
SWFFont


Returns the descent of the font, or 0 if not available

SWFFont->getAscent
SWFFont->getLeading
SWFFont
PHP Manual

SWFFont->getDescent

(PHP 4 >= 4.0.5)

SWFFont->getDescent — Returns the descent of the font, or 0 if not available

Description

SWFFont
float getDescent ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFFont->getAscent

SWFFont->getAscent
SWFFont->getLeading
SWFFont


Returns the leading of the font, or 0 if not available

SWFFont->getDescent
SWFFont->getShape
SWFFont
PHP Manual

SWFFont->getLeading

(PHP 4 >= 4.0.5)

SWFFont->getLeading — Returns the leading of the font, or 0 if not available

Description

SWFFont
float getLeading ( void )
Warning

This function is currently not documented; only its argument list is available.

SWFFont->getDescent
SWFFont->getShape
SWFFont


Returns the glyph shape of a char as a text string

SWFFont->getLeading
SWFFont->getUTF8Width
SWFFont
PHP Manual

SWFFont->getShape

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont->getShape — Returns the glyph shape of a char as a text string

Description

SWFFont
string getShape ( int $code )
Warning

This function is currently not documented; only its argument list is available.

SWFFont->getLeading
SWFFont->getUTF8Width
SWFFont


Calculates the width of the given string in this font at full height

SWFFont->getShape
SWFFont->getWidth
SWFFont
PHP Manual

SWFFont->getUTF8Width

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont->getUTF8Width — Calculates the width of the given string in this font at full height

Description

SWFFont
float getUTF8Width ( string $string )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFFont->getWidth

SWFFont->getShape
SWFFont->getWidth
SWFFont


Returns the string's width

SWFFont->getUTF8Width
SWFFontChar
SWFFont
PHP Manual

SWFFont->getWidth

(PHP 4 >= 4.0.5)

SWFFont->getWidth — Returns the string's width

Description

SWFFont
float getWidth ( string $string )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swffont->getwidth() returns the string string 's width, using font's default scaling. You'll probably want to use the swftext() version of this method which uses the text object's scale.

See Also

  • SWFFont->getUTF8Width

SWFFont->getUTF8Width
SWFFontChar
SWFFont


Adds characters to a font for exporting font

SWFFontChar
SWFFontChar->addUTF8Chars
SWFFontChar
PHP Manual

SWFFontChar->addChars

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFontChar->addChars — Adds characters to a font for exporting font

Description

SWFFontChar
void addChars ( string $char )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFFontChar->addUTF8Chars

SWFFontChar
SWFFontChar->addUTF8Chars
SWFFontChar


Adds characters to a font for exporting font

SWFFontChar->addChars
SWFGradient
SWFFontChar
PHP Manual

SWFFontChar->addUTF8Chars

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFontChar->addUTF8Chars — Adds characters to a font for exporting font

Description

SWFFontChar
void addUTF8Chars ( string $char )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFFontChar->addChars

SWFFontChar->addChars
SWFGradient
SWFFontChar


Adds an entry to the gradient list

SWFGradient
SWFGradient->__construct
SWFGradient
PHP Manual

SWFGradient->addEntry

(PHP 4 >= 4.3.0)

SWFGradient->addEntry — Adds an entry to the gradient list

Description

SWFGradient
void addEntry ( float $ratio , int $red , int $green , int $blue [, int $alpha = 255 ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfgradient->addentry() adds an entry to the gradient list. ratio is a number between 0 and 1 indicating where in the gradient this color appears. Thou shalt add entries in order of increasing ratio.

red , green , blue is a color (RGB mode).

Return Values

No value is returned.

SWFGradient
SWFGradient->__construct
SWFGradient


Creates a gradient object

SWFGradient->addEntry
SWFMorph
SWFGradient
PHP Manual

SWFGradient->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFGradient->__construct — Creates a gradient object

Description

SWFGradient
SWFGradient __construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfgradient() creates a new SWFGradient object.

After you've added the entries to your gradient, you can use the gradient in a shape fill with the swfshape->addfill() method.

SWFGradient has the following methods : swfgradient->addentry().

This simple example will draw a big black-to-white gradient as background, and a reddish disc in its center.

Example #1 swfgradient() example

<?php

  $m = new SWFMovie();
  $m->setDimension(320, 240);

  $s = new SWFShape();

  // first gradient- black to white
  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(1.0, 0xff, 0xff, 0xff);

  $f = $s->addFill($g, SWFFILL_LINEAR_GRADIENT);
  $f->scaleTo(0.01);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  $s = new SWFShape();

  // second gradient- radial gradient from red to transparent
  $g = new SWFGradient();
  $g->addEntry(0.0, 0xff, 0, 0, 0xff);
  $g->addEntry(1.0, 0xff, 0, 0, 0);

  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.005);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFGradient->addEntry
SWFMorph
SWFGradient


Creates a new SWFMorph object

SWFMorph
SWFMorph->getShape1
SWFMorph
PHP Manual

SWFMorph->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMorph->__construct — Creates a new SWFMorph object

Description

SWFMorph
SWFMorph __construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Creates a new SWFMorph object.

Also called a "shape tween". This thing lets you make those tacky twisting things that make your computer choke. Oh, joy!

Examples

This simple example will morph a big red square into a smaller blue black-bordered square.

Example #1 swfmorph() example

<?php
  $p = new SWFMorph();

  $s = $p->getShape1();
  $s->setLine(0, 0, 0, 0);

  /* Note that this is backwards from normal shapes (left instead of right).
     I have no idea why, but this seems to work.. */

  $s->setLeftFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-1000,-1000);
  $s->drawLine(2000,0);
  $s->drawLine(0,2000);
  $s->drawLine(-2000,0);
  $s->drawLine(0,-2000);

  $s = $p->getShape2();
  $s->setLine(60,0,0,0);
  $s->setLeftFill($s->addFill(0, 0, 0xff));
  $s->movePenTo(0,-1000);
  $s->drawLine(1000,1000);
  $s->drawLine(-1000,1000);
  $s->drawLine(-1000,-1000);
  $s->drawLine(1000,-1000);

  $m = new SWFMovie();
  $m->setDimension(3000,2000);
  $m->setBackground(0xff, 0xff, 0xff);

  $i = $m->add($p);
  $i->moveTo(1500,1000);

  for ($r=0.0; $r<=1.0; $r+=0.1) {
    $i->setRatio($r);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFMorph
SWFMorph->getShape1
SWFMorph


Gets a handle to the starting shape

SWFMorph->__construct
SWFMorph->getShape2
SWFMorph
PHP Manual

SWFMorph->getShape1

(PHP 4 >= 4.0.5)

SWFMorph->getShape1 — Gets a handle to the starting shape

Description

SWFMorph
SWFShape getShape1 ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Gets the morph's starting shape.

Return Values

Returns a SWFShape object.

See Also

  • SWFMorph->getShape2

SWFMorph->__construct
SWFMorph->getShape2
SWFMorph


Gets a handle to the ending shape

SWFMorph->getShape1
SWFMovie
SWFMorph
PHP Manual

SWFMorph->getShape2

(PHP 4 >= 4.0.5)

SWFMorph->getShape2 — Gets a handle to the ending shape

Description

SWFMorph
SWFShape getShape2 ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Gets the morph's ending shape.

Return Values

Returns a SWFShape object.

See Also

  • SWFMorph->getShape1

SWFMorph->getShape1
SWFMovie
SWFMorph


Adds any type of data to a movie

SWFMovie
SWFMovie->addExport
SWFMovie
PHP Manual

SWFMovie->add

(PHP 4 >= 4.3.3)

SWFMovie->add — Adds any type of data to a movie

Description

SWFMovie
mixed add ( object $instance )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Adds an SWF object instance to the current movie.

Parameters

instance

Any type of object instance, like SWFShape, SWFText, SWFFont.

Return Values

For displayable types (shape, text, button, sprite), this returns an SWFDisplayItem, a handle to the object in a display list. Thus, you can add the same shape to a movie multiple times and get separate handles back for each separate instance.

See Also

  • SWFMovie->remove

SWFMovie
SWFMovie->addExport
SWFMovie


SWFMovie->add
SWFMovie->addFont
SWFMovie
PHP Manual

SWFMovie->addExport

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie->addExport —

Description

SWFMovie
void addExport ( SWFCharacter $char , string $name )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFMovie->add
SWFMovie->addFont
SWFMovie


SWFMovie->addExport
SWFMovie->__construct
SWFMovie
PHP Manual

SWFMovie->addFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie->addFont —

Description

SWFMovie
mixed addFont ( SWFFont $font )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFMovie->addExport
SWFMovie->__construct
SWFMovie


Creates a new movie object, representing an SWF version 4 movie

SWFMovie->addFont
SWFMovie->importChar
SWFMovie
PHP Manual

SWFMovie->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie->__construct — Creates a new movie object, representing an SWF version 4 movie

Description

SWFMovie
SWFMovie __construct ([ int $version ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Creates a new movie object, representing an SWF movie.

Parameters

version

The desired SWF version. Default is 4.

SWFMovie->addFont
SWFMovie->importChar
SWFMovie


SWFMovie->__construct
SWFMovie->importFont
SWFMovie
PHP Manual

SWFMovie->importChar

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie->importChar —

Description

SWFMovie
SWFSprite importChar ( string $libswf , string $name )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFMovie->importFont

SWFMovie->__construct
SWFMovie->importFont
SWFMovie


SWFMovie->importChar
SWFMovie->labelFrame
SWFMovie
PHP Manual

SWFMovie->importFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie->importFont —

Description

SWFMovie
SWFFontChar importFont ( string $libswf , string $name )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFMovie->importChar

SWFMovie->importChar
SWFMovie->labelFrame
SWFMovie


Labels a frame

SWFMovie->importFont
SWFMovie->nextFrame
SWFMovie
PHP Manual

SWFMovie->labelFrame

(PHP 4 >= 4.3.3)

SWFMovie->labelFrame — Labels a frame

Description

SWFMovie
void labelFrame ( string $label )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFMovie->importFont
SWFMovie->nextFrame
SWFMovie


Moves to the next frame of the animation

SWFMovie->labelFrame
SWFMovie->output
SWFMovie
PHP Manual

SWFMovie->nextFrame

(PHP 4 >= 4.3.3)

SWFMovie->nextFrame — Moves to the next frame of the animation

Description

SWFMovie
void nextFrame ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Moves to the next frame of the animation.

Return Values

No value is returned.

SWFMovie->labelFrame
SWFMovie->output
SWFMovie


Dumps your lovingly prepared movie out

SWFMovie->nextFrame
SWFMovie->remove
SWFMovie
PHP Manual

SWFMovie->output

(PHP 4 >= 4.3.3)

SWFMovie->output — Dumps your lovingly prepared movie out

Description

SWFMovie
int output ([ int $compression ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Dumps the SWFMovie.

Don't forget to send the Content-Type HTTP header file before using this function, in order to display the movie in a browser.

Parameters

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Return Values

Return the number of bytes written or FALSE on error.

Examples

Example #1 Displaying your $movie in a browser

<?php
header('Content-type: application/x-shockwave-flash');
$movie->output();
?>

See Also

  • SWFMovie->save
  • SWFMovie->saveToFile

SWFMovie->nextFrame
SWFMovie->remove
SWFMovie


Removes the object instance from the display list

SWFMovie->output
SWFMovie->save
SWFMovie
PHP Manual

SWFMovie->remove

(PHP 5.2.1-5.3.0, PECL ming SVN)

SWFMovie->remove — Removes the object instance from the display list

Description

SWFMovie
void remove ( object $instance )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Removes the given object instance from the display list.

Return Values

No value is returned.

See Also

  • SWFMovie->add

SWFMovie->output
SWFMovie->save
SWFMovie


Saves the SWF movie in a file

SWFMovie->remove
SWFMovie->saveToFile
SWFMovie
PHP Manual

SWFMovie->save

(PHP 4 >= 4.3.3)

SWFMovie->save — Saves the SWF movie in a file

Description

SWFMovie
int save ( string $filename [, int $compression ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Saves the SWF movie to the specified filename .

Parameters

filename

The path to the saved SWF document.

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Return Values

Return the number of bytes written or FALSE on error.

See Also

  • SWFMovie->output
  • SWFMovie->saveToFile

SWFMovie->remove
SWFMovie->saveToFile
SWFMovie


SWFMovie->save
SWFMovie->setbackground
SWFMovie
PHP Manual

SWFMovie->saveToFile

(PHP 4 >= 4.3.3)

SWFMovie->saveToFile —

Description

SWFMovie
int saveToFile ( resource $x [, int $compression ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

X

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Return Values

Return the number of bytes written or FALSE on error.

See Also

  • SWFMovie->output
  • SWFMovie->save

SWFMovie->save
SWFMovie->setbackground
SWFMovie


Sets the background color

SWFMovie->saveToFile
SWFMovie->setDimension
SWFMovie
PHP Manual

SWFMovie->setbackground

(PHP 4 >= 4.3.3)

SWFMovie->setbackground — Sets the background color

Description

SWFMovie
void setbackground ( int $red , int $green , int $blue )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets the background color.

Why is there no rgba version? Think about it, you might want to let the HTML background show through. There's a way to do that, but it only works on IE4. Search the » http://www.macromedia.com/ site for details.

Parameters

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

Return Values

No value is returned.

SWFMovie->saveToFile
SWFMovie->setDimension
SWFMovie


Sets the movie's width and height

SWFMovie->setbackground
SWFMovie->setFrames
SWFMovie
PHP Manual

SWFMovie->setDimension

(PHP 4 >= 4.3.3)

SWFMovie->setDimension — Sets the movie's width and height

Description

SWFMovie
void setDimension ( float $width , float $height )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets the movie's dimension to the specified width and height .

Parameters

width

The movie width.

height

The movie height.

Return Values

No value is returned.

SWFMovie->setbackground
SWFMovie->setFrames
SWFMovie


Sets the total number of frames in the animation

SWFMovie->setDimension
SWFMovie->setRate
SWFMovie
PHP Manual

SWFMovie->setFrames

(PHP 4 >= 4.3.3)

SWFMovie->setFrames — Sets the total number of frames in the animation

Description

SWFMovie
void setFrames ( int $number )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets the total number of frames in the animation to the given number .

Parameters

number

The number of frames.

Return Values

No value is returned.

SWFMovie->setDimension
SWFMovie->setRate
SWFMovie


Sets the animation's frame rate

SWFMovie->setFrames
SWFMovie->startSound
SWFMovie
PHP Manual

SWFMovie->setRate

(PHP 4 >= 4.3.3)

SWFMovie->setRate — Sets the animation's frame rate

Description

SWFMovie
void setRate ( float $rate )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Sets the frame rate to the specified rate .

Animation will slow down if the player can't render frames fast enough- unless there's a streaming sound, in which case display frames are sacrificed to keep sound from skipping.

Parameters

rate

The frame rate, in frame per seconds.

Return Values

No value is returned.

SWFMovie->setFrames
SWFMovie->startSound
SWFMovie


SWFMovie->setRate
SWFMovie->stopSound
SWFMovie
PHP Manual

SWFMovie->startSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie->startSound —

Description

SWFMovie
SWFSoundInstance startSound ( SWFSound $sound )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFMovie->stopSound

SWFMovie->setRate
SWFMovie->stopSound
SWFMovie


SWFMovie->startSound
SWFMovie->streamMP3
SWFMovie
PHP Manual

SWFMovie->stopSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie->stopSound —

Description

SWFMovie
void stopSound ( SWFSound $sound )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFMovie->startSound

SWFMovie->startSound
SWFMovie->streamMP3
SWFMovie


Streams a MP3 file

SWFMovie->stopSound
SWFMovie->writeExports
SWFMovie
PHP Manual

SWFMovie->streamMP3

(PHP 4 >= 4.3.3)

SWFMovie->streamMP3 — Streams a MP3 file

Description

SWFMovie
int streamMP3 ( mixed $mp3file [, float $skip = 0 ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Streams the given MP3 file mp3file .

This method is not very robust in dealing with oddities (can skip over an initial ID3 tag, but that's about it).

Note that the movie isn't smart enough to put enough frames in to contain the entire mp3 stream- you'll have to add (length of song * frames per second) frames to get the entire stream in.

Parameters

mp3file

Can be a file pointer returned by fopen() or the MP3 data, as a binary string.

skip

Number of seconds to skip.

Return Values

Return number of frames.

Changelog

Version | Description
5.2.0 | skip added

Examples

Example #1 Streaming example

<?php
$m = new SWFMovie();
$m->setRate(12.0);
$m->streamMp3(file_get_contents("distortobass.mp3"));
// use your own MP3

// The file is 11.85 seconds at 12.0 fps = 142 frames
$m->setFrames(142);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFMovie->stopSound
SWFMovie->writeExports
SWFMovie


SWFMovie->streamMP3
SWFPrebuiltClip
SWFMovie
PHP Manual

SWFMovie->writeExports

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie->writeExports —

Description

SWFMovie
void writeExports ( void )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFMovie->streamMP3
SWFPrebuiltClip
SWFMovie


Returns a SWFPrebuiltClip object

SWFPrebuiltClip
SWFShape
SWFPrebuiltClip
PHP Manual

SWFPrebuiltClip->__construct

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFPrebuiltClip->__construct — Returns a SWFPrebuiltClip object

Description

SWFPrebuiltClip
SWFPrebuiltClip __construct ( mixed $file )
Warning

This function is currently not documented; only its argument list is available.

SWFPrebuiltClip
SWFShape
SWFPrebuiltClip


Adds a solid fill to the shape

SWFShape
SWFShape->__construct
SWFShape
PHP Manual

SWFShape->addFill

(PHP 4 >= 4.0.5)

SWFShape->addFill — Adds a solid fill to the shape

Description

SWFShape
SWFFill addFill ( int $red , int $green , int $blue [, int $alpha = 255 ] )
SWFFill addFill ( SWFBitmap $bitmap [, int $flags ] )
SWFFill addFill ( SWFGradient $gradient [, int $flags ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

SWFShape->addFill() adds a solid fill to the shape's list of fill styles. SWFShape->addFill() accepts three different types of arguments.

red , green , blue is a color (RGB mode).

The bitmap argument is an SWFBitmap() object. The flags argument can be one of the following values: SWFFILL_CLIPPED_BITMAP, SWFFILL_TILED_BITMAP, SWFFILL_LINEAR_GRADIENT or SWFFILL_RADIAL_GRADIENT. Default is SWFFILL_TILED_BITMAP for SWFBitmap and SWFFILL_LINEAR_GRADIENT for SWFGradient.

The gradient argument is an SWFGradient() object. The flags argument can be one of the following values : SWFFILL_RADIAL_GRADIENT or SWFFILL_LINEAR_GRADIENT. Default is SWFFILL_LINEAR_GRADIENT. I'm sure about this one. Really.

SWFShape->addFill() returns an SWFFill()
object for use with the SWFShape->setLeftFill()
and SWFShape->setRightFill() functions
described below.

Examples

This simple example will draw a frame on a bitmap. Ah, here's another buglet in the flash player- it doesn't seem to care about the second shape's bitmap's transformation in a morph. According to spec, the bitmap should stretch along with the shape in this example..

Example #1 SWFShape->addFill() example

<?php

$p = new SWFMorph();

$b = new SWFBitmap(file_get_contents("alphafill.jpg"));
// use your own bitmap
$width = $b->getWidth();
$height = $b->getHeight();

$s = $p->getShape1();
$f = $s->addFill($b, SWFFILL_TILED_BITMAP);
$f->moveTo(-$width/2, -$height/4);
$f->scaleTo(1.0, 0.5);
$s->setLeftFill($f);
$s->movePenTo(-$width/2, -$height/4);
$s->drawLine($width, 0);
$s->drawLine(0, $height/2);
$s->drawLine(-$width, 0);
$s->drawLine(0, -$height/2);

$s = $p->getShape2();
$f = $s->addFill($b, SWFFILL_TILED_BITMAP);

// these two have no effect!
$f->moveTo(-$width/4, -$height/2);
$f->scaleTo(0.5, 1.0);

$s->setLeftFill($f);
$s->movePenTo(-$width/4, -$height/2);
$s->drawLine($width/2, 0);
$s->drawLine(0, $height);
$s->drawLine(-$width/2, 0);
$s->drawLine(0, -$height);

$m = new SWFMovie();
$m->setDimension($width, $height);
$i = $m->add($p);
$i->moveTo($width/2, $height/2);

for ($n=0; $n<1.001; $n+=0.03) {
    $i->setRatio($n);
    $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

See Also

  • SWFShape->setLeftFill
  • SWFShape->setRightFill

SWFShape
SWFShape->__construct
SWFShape


Creates a new shape object

SWFShape->addFill
SWFShape->drawArc
SWFShape
PHP Manual

SWFShape->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape->__construct — Creates a new shape object

Description

SWFShape
SWFShape __construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Created a new SWFShape object.

Examples

This simple example will draw a big red elliptic quadrant.

Example #1 swfshape() example

<?php
$s = new SWFShape();
$s->setLine(40, 0x7f, 0, 0);
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(200, 200);
$s->drawLineTo(6200, 200);
$s->drawLineTo(6200, 4600);
$s->drawCurveTo(200, 4600, 200, 200);

$m = new SWFMovie();
$m->setDimension(6400, 4800);
$m->setRate(12.0);
$m->add($s);
$m->nextFrame();

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFShape->addFill
SWFShape->drawArc
SWFShape


Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock

SWFShape->__construct
SWFShape->drawCircle
SWFShape
PHP Manual

SWFShape->drawArc

(PHP 4 >= 4.0.5)

SWFShape->drawArc — Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock

Description

SWFShape
void drawArc ( float $r , float $startAngle , float $endAngle )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFShape->drawCircle

SWFShape->__construct
SWFShape->drawCircle
SWFShape


Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

SWFShape->drawArc
SWFShape->drawCubic
SWFShape
PHP Manual

SWFShape->drawCircle

(PHP 4 >= 4.0.5)

SWFShape->drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

Description

SWFShape
void drawCircle ( float $r )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFShape->drawArc
SWFShape->drawCubic
SWFShape


Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape->drawCircle
SWFShape->drawCubicTo
SWFShape
PHP Manual

SWFShape->drawCubic

(PHP 4 >= 4.0.5)

SWFShape->drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points

Description

SWFShape
int drawCubic ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFShape->drawCubicTo

SWFShape->drawCircle
SWFShape->drawCubicTo
SWFShape


Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape->drawCubic
SWFShape->drawCurve
SWFShape
PHP Manual

SWFShape->drawCubicTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape->drawCubicTo — Draws a cubic bezier curve using the current position and the three given points as control points

Description

SWFShape
int drawCubicTo ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFShape->drawCubic

SWFShape->drawCubic
SWFShape->drawCurve
SWFShape


Draws a curve (relative)

SWFShape->drawCubicTo
SWFShape->drawCurveTo
SWFShape
PHP Manual

SWFShape->drawCurve

(PHP 4 >= 4.0.5)

SWFShape->drawCurve — Draws a curve (relative)

Description

SWFShape
int drawCurve ( float $controldx , float $controldy , float $anchordx , float $anchordy [, float $targetdx ], float $targetdy )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfshape->drawcurve() draws a quadratic curve (using the current line style,set by swfshape->setline()) from the current pen position to the relative position (anchorx ,anchory ) using relative control point (controlx ,controly ). That is, head towards the control point, then smoothly turn to the anchor point.

With 6 parameters, it draws a cubic bezier to point (x+targetdx , x+targetdy ) with control points (x+controldx , y+controldy ) and (x+anchordx , y+anchordy ).

See Also

  • SWFShape->drawCurve

SWFShape->drawCubicTo
SWFShape->drawCurveTo
SWFShape


Draws a curve

SWFShape->drawCurve
SWFShape->drawGlyph
SWFShape
PHP Manual

SWFShape->drawCurveTo

(PHP 4 >= 4.0.5)

SWFShape->drawCurveTo — Draws a curve

Description

SWFShape
int drawCurveTo ( float $controlx , float $controly , float $anchorx , float $anchory [, float $targetx ], float $targety )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfshape->drawcurveto() draws a quadratic curve (using the current line style, set by swfshape->setline()) from the current pen position to (anchorx ,anchory ) using (controlx ,controly ) as a control point. That is, head towards the control point, then smoothly turn to the anchor point.

With 6 parameters, it draws a cubic bezier to point (targetx , targety ) with control points (controlx , controly ) and (anchorx , anchory ).

See Also

  • SWFShape->drawCurveTo

SWFShape->drawCurve
SWFShape->drawGlyph
SWFShape


Draws the first character in the given string into the shape using the glyph definition from the given font

SWFShape->drawCurveTo
SWFShape->drawLine
SWFShape
PHP Manual

SWFShape->drawGlyph

(PHP 4 >= 4.0.5)

SWFShape->drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font

Description

SWFShape
void drawGlyph ( SWFFont $font , string $character [, int $size ] )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFShape->drawCurveTo
SWFShape->drawLine
SWFShape


Draws a line (relative)

SWFShape->drawGlyph
SWFShape->drawLineTo
SWFShape
PHP Manual

SWFShape->drawLine

(PHP 4 >= 4.0.5)

SWFShape->drawLine — Draws a line (relative)

Description

SWFShape
void drawLine ( float $dx , float $dy )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfshape->drawline() draws a line (using the current line style set by swfshape->setline()) from the current pen position to displacement (dx ,dy ).

Return Values

No value is returned.

See Also

  • SWFShape->drawLineTo

SWFShape->drawGlyph
SWFShape->drawLineTo
SWFShape


Draws a line

SWFShape->drawLine
SWFShape->movePen
SWFShape
PHP Manual

SWFShape->drawLineTo

(PHP 4 >= 4.0.5)

SWFShape->drawLineTo — Draws a line

Description

SWFShape
void drawLineTo ( float $x , float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfshape->setrightfill() draws a line (using the current line style, set by swfshape->setline()) from the current pen position to point (x ,y ) in the shape's coordinate space.

Return Values

No value is returned.

See Also

  • SWFShape->drawLine

SWFShape->drawLine
SWFShape->movePen
SWFShape


Moves the shape's pen (relative)

SWFShape->drawLineTo
SWFShape->movePenTo
SWFShape
PHP Manual

SWFShape->movePen

(PHP 4 >= 4.0.5)

SWFShape->movePen — Moves the shape's pen (relative)

Description

SWFShape
void movePen ( float $dx , float $dy )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfshape->setrightfill() move the shape's pen from coordinates (current x,current y) to (current x + dx , current y + dy ) in the shape's coordinate space.

Return Values

No value is returned.

See Also

  • SWFShape->movePenTo

SWFShape->drawLineTo
SWFShape->movePenTo
SWFShape


Moves the shape's pen

SWFShape->movePen
SWFShape->setLeftFill
SWFShape
PHP Manual

SWFShape->movePenTo

(PHP 4 >= 4.0.5)

SWFShape->movePenTo — Moves the shape's pen

Description

SWFShape
void movePenTo ( float $x , float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfshape->setrightfill() move the shape's pen to (x ,y ) in the shape's coordinate space.

Return Values

No value is returned.

See Also

  • SWFShape->movePen

SWFShape->movePen
SWFShape->setLeftFill
SWFShape


Sets left rasterizing color

SWFShape->movePenTo
SWFShape->setLine
SWFShape
PHP Manual

SWFShape->setLeftFill

(PHP 4 >= 4.0.5)

SWFShape->setLeftFill — Sets left rasterizing color

Description

SWFShape
void setLeftFill ( SWFGradient $fill )
void setLeftFill ( int $red , int $green , int $blue [, int $a ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy to know what those fills are ahead of time, so the swf format requires these to be specified.

swfshape->setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.

This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill on the other side.

Shortcut for swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.

Return Values

No value is returned.

See Also

  • SWFShape->setRightFill

SWFShape->movePenTo
SWFShape->setLine
SWFShape


Sets the shape's line style

SWFShape->setLeftFill
SWFShape->setRightFill
SWFShape
PHP Manual

SWFShape->setLine

(PHP 4 >= 4.0.5)

SWFShape->setLine — Sets the shape's line style

Description

SWFShape
void setLine ( SWFShape $shape )
void setLine ( int $width , int $red , int $green , int $blue [, int $a ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfshape->setline() sets the shape's line style. width is the line's width. If width is 0, the line's style is removed (then, all other arguments are ignored). If width > 0, then line's color is set to red , green , blue . Last parameter a is optional.

You must declare all line styles before you use them (see example).

Return Values

No value is returned.

Examples

This simple example will draw a big "!#%*@", in funny colors and gracious style.

Example #1 swfshape->setline() example

<?php
$s = new SWFShape();
$f1 = $s->addFill(0xff, 0, 0);
$f2 = $s->addFill(0xff, 0x7f, 0);
$f3 = $s->addFill(0xff, 0xff, 0);
$f4 = $s->addFill(0, 0xff, 0);
$f5 = $s->addFill(0, 0, 0xff);

// bug: have to declare all line styles before you use them
$s->setLine(40, 0x7f, 0, 0);
$s->setLine(40, 0x7f, 0x3f, 0);
$s->setLine(40, 0x7f, 0x7f, 0);
$s->setLine(40, 0, 0x7f, 0);
$s->setLine(40, 0, 0, 0x7f);

$f = new SWFFont('Techno.fdb');

$s->setRightFill($f1);
$s->setLine(40, 0x7f, 0, 0);
$s->drawGlyph($f, '!');
$s->movePen($f->getWidth('!'), 0);

$s->setRightFill($f2);
$s->setLine(40, 0x7f, 0x3f, 0);
$s->drawGlyph($f, '#');
$s->movePen($f->getWidth('#'), 0);

$s->setRightFill($f3);
$s->setLine(40, 0x7f, 0x7f, 0);
$s->drawGlyph($f, '%');
$s->movePen($f->getWidth('%'), 0);

$s->setRightFill($f4);
$s->setLine(40, 0, 0x7f, 0);
$s->drawGlyph($f, '*');
$s->movePen($f->getWidth('*'), 0);

$s->setRightFill($f5);
$s->setLine(40, 0, 0, 0x7f);
$s->drawGlyph($f, '@');

$m = new SWFMovie();
$m->setDimension(3000,2000);
$m->setRate(12.0);
$i = $m->add($s);
$i->moveTo(1500-$f->getWidth("!#%*@")/2, 1000+$f->getAscent()/2);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

Return Values

No value is returned.

SWFShape->setLeftFill
SWFShape->setRightFill
SWFShape


Sets right rasterizing color

SWFShape->setLine
SWFSound
SWFShape
PHP Manual

SWFShape->setRightFill

(PHP 4 >= 4.0.5)

SWFShape->setRightFill — Sets right rasterizing color

Description

SWFShape
void setRightFill ( SWFGradient $fill )
void setRightFill ( int $red , int $green , int $blue [, int $a ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.

Return Values

No value is returned.

See Also

  • SWFShape->setLeftFill

SWFShape->setLine
SWFSound
SWFShape


Returns a new SWFSound object from given file

SWFSound
SWFSoundInstance
SWFSound
PHP Manual

SWFSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSound — Returns a new SWFSound object from given file

Description

SWFSound
SWFSound __construct ( string $filename [, int $flags = 0 ] )
Warning

This function is currently not documented; only its argument list is available.

SWFSound
SWFSoundInstance
SWFSound
PHP Manual


SWFSoundInstance
SWFSoundInstance->loopInPoint
SWFSoundInstance
PHP Manual

SWFSoundInstance->loopCount

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance->loopCount —

Description

SWFSoundInstance
void loopCount ( int $point )
Warning

This function is currently not documented; only its argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

  • SWFSoundInstance->loopOutPoint

SWFSoundInstance
SWFSoundInstance->loopInPoint
SWFSoundInstance


SWFSoundInstance->loopCount
SWFSoundInstance->loopOutPoint
SWFSoundInstance
PHP Manual

SWFSoundInstance->loopInPoint

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance->loopInPoint —

Description

SWFSoundInstance
void loopInPoint ( int $point )
Warning

This function is currently not documented; only its argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

  • SWFSoundInstance->loopOutPoint

SWFSoundInstance->loopCount
SWFSoundInstance->loopOutPoint
SWFSoundInstance


SWFSoundInstance->loopInPoint
SWFSoundInstance->noMultiple
SWFSoundInstance
PHP Manual

SWFSoundInstance->loopOutPoint

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance->loopOutPoint —

Description

SWFSoundInstance
void loopOutPoint ( int $point )
Warning

This function is currently not documented; only its argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

  • SWFSoundInstance->loopInPoint

SWFSoundInstance->loopInPoint
SWFSoundInstance->noMultiple
SWFSoundInstance


SWFSoundInstance->loopOutPoint
SWFSprite
SWFSoundInstance
PHP Manual

SWFSoundInstance->noMultiple

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance->noMultiple —

Description

SWFSoundInstance
void noMultiple ( void )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFSoundInstance->loopOutPoint
SWFSprite
SWFSoundInstance


Adds an object to a sprite

SWFSprite
SWFSprite->__construct
SWFSprite
PHP Manual

SWFSprite->add

(PHP 4 >= 4.0.5)

SWFSprite->add — Adds an object to a sprite

Description

SWFSprite
void add ( object $object )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfsprite->add() adds a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object.

For displayable types (swfshape(),
swfbutton(), swftext(),
swfaction() or swfsprite()),
this returns a handle  to the object in a display list.

Return Values

No value is returned.

SWFSprite
SWFSprite->__construct
SWFSprite


Creates a movie clip (a sprite)

SWFSprite->add
SWFSprite->labelFrame
SWFSprite
PHP Manual

SWFSprite->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite->__construct — Creates a movie clip (a sprite)

Description

SWFSprite
SWFSprite __construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Creates a new SWFSprite object.

SWFSprite->add
SWFSprite->labelFrame
SWFSprite


Labels frame

SWFSprite->__construct
SWFSprite->nextFrame
SWFSprite
PHP Manual

SWFSprite->labelFrame

(PHP 4 >= 4.3.3)

SWFSprite->labelFrame — Labels frame

Description

SWFSprite
void labelFrame ( string $label )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFSprite->__construct
SWFSprite->nextFrame
SWFSprite


Moves to the next frame of the animation

SWFSprite->labelFrame
SWFSprite->remove
SWFSprite
PHP Manual

SWFSprite->nextFrame

(PHP 4 >= 4.0.5)

SWFSprite->nextFrame — Moves to the next frame of the animation

Description

SWFSprite
void nextFrame ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfsprite->setframes() moves to the next frame of the animation.

Return Values

No value is returned.

SWFSprite->labelFrame
SWFSprite->remove
SWFSprite


Removes an object to a sprite

SWFSprite->nextFrame
SWFSprite->setFrames
SWFSprite
PHP Manual

SWFSprite->remove

(PHP 4 >= 4.0.5)

SWFSprite->remove — Removes an object to a sprite

Description

SWFSprite
void remove ( object $object )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfsprite->remove() remove a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object
from the sprite.

Return Values

No value is returned.

SWFSprite->nextFrame
SWFSprite->setFrames
SWFSprite


Sets the total number of frames in the animation

SWFSprite->remove
SWFSprite->startSound
SWFSprite
PHP Manual

SWFSprite->setFrames

(PHP 4 >= 4.0.5)

SWFSprite->setFrames — Sets the total number of frames in the animation

Description

SWFSprite
void setFrames ( int $number )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swfsprite->setframes() sets the total number of frames in the animation to numberofframes .

Return Values

No value is returned.

SWFSprite->remove
SWFSprite->startSound
SWFSprite


SWFSprite->setFrames
SWFSprite->stopSound
SWFSprite
PHP Manual

SWFSprite->startSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite->startSound —

Description

SWFSprite
SWFSoundInstance startSound ( SWFSound $sount )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFSprite->stopSound

SWFSprite->setFrames
SWFSprite->stopSound
SWFSprite


SWFSprite->startSound
SWFText
SWFSprite
PHP Manual

SWFSprite->stopSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite->stopSound —

Description

SWFSprite
void stopSound ( SWFSound $sount )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFSprite->startSound

SWFSprite->startSound
SWFText
SWFSprite


Draws a string

SWFText
SWFText->addUTF8String
SWFText
PHP Manual

SWFText->addString

(PHP 4 >= 4.0.5)

SWFText->addString — Draws a string

Description

SWFText
void addString ( string $string )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftext->addstring() draws the string string at the current pen (cursor) location. Pen is at the baseline of the text; i.e., ascending text is in the -y direction.

Return Values

No value is returned.

See Also

  • SWFText->addUTF8String

SWFText
SWFText->addUTF8String
SWFText


Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

SWFText->addString
SWFText->__construct
SWFText
PHP Manual

SWFText->addUTF8String

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText->addUTF8String — Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

Description

SWFText
void addUTF8String ( string $text )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFText->addString

SWFText->addString
SWFText->__construct
SWFText


Creates a new SWFText object

SWFText->addUTF8String
SWFText->getAscent
SWFText
PHP Manual

SWFText->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText->__construct — Creates a new SWFText object

Description

SWFText
void __construct ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Creates a new SWFText object, fresh for manipulating.

Examples

This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.

Example #1 swftext() example

<?php
$f = new SWFFont("Techno.fdb");
$t = new SWFText();
$t->setFont($f);
$t->moveTo(200, 2400);
$t->setColor(0xff, 0xff, 0);
$t->setHeight(1200);
$t->addString("PHP generates Flash with Ming!!");

$m = new SWFMovie();
$m->setDimension(5400, 3600);

$m->add($t);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFText->addUTF8String
SWFText->getAscent
SWFText


Returns the ascent of the current font at its current size, or 0 if not available

SWFText->__construct
SWFText->getDescent
SWFText
PHP Manual

SWFText->getAscent

(PHP 4 >= 4.0.5)

SWFText->getAscent — Returns the ascent of the current font at its current size, or 0 if not available

Description

SWFText
float getAscent ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFText->getDescent

SWFText->__construct
SWFText->getDescent
SWFText


Returns the descent of the current font at its current size, or 0 if not available

SWFText->getAscent
SWFText->getLeading
SWFText
PHP Manual

SWFText->getDescent

(PHP 4 >= 4.0.5)

SWFText->getDescent — Returns the descent of the current font at its current size, or 0 if not available

Description

SWFText
float getDescent ( void )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFText->getAscent

SWFText->getAscent
SWFText->getLeading
SWFText


Returns the leading of the current font at its current size, or 0 if not available

SWFText->getDescent
SWFText->getUTF8Width
SWFText
PHP Manual

SWFText->getLeading

(PHP 4 >= 4.0.5)

SWFText->getLeading — Returns the leading of the current font at its current size, or 0 if not available

Description

SWFText
float getLeading ( void )
Warning

This function is currently not documented; only its argument list is available.

SWFText->getDescent
SWFText->getUTF8Width
SWFText


calculates the width of the given string in this text objects current font and size

SWFText->getLeading
SWFText->getWidth
SWFText
PHP Manual

SWFText->getUTF8Width

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText->getUTF8Width — calculates the width of the given string in this text objects current font and size

Description

SWFText
float getUTF8Width ( string $string )
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFText->getWidth

SWFText->getLeading
SWFText->getWidth
SWFText


Computes string's width

SWFText->getUTF8Width
SWFText->moveTo
SWFText
PHP Manual

SWFText->getWidth

(PHP 4 >= 4.0.5)

SWFText->getWidth — Computes string's width

Description

SWFText
float getWidth ( string $string )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Returns the rendered width of the string at the text object's current font, scale, and spacing settings.

See Also

  • SWFText->getUTF8Width

SWFText->getUTF8Width
SWFText->moveTo
SWFText


Moves the pen

SWFText->getWidth
SWFText->setColor
SWFText
PHP Manual

SWFText->moveTo

(PHP 4 >= 4.0.5)

SWFText->moveTo — Moves the pen

Description

SWFText
void moveTo ( float $x , float $y )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftext->moveto() moves the pen (or cursor, if that makes more sense) to (x ,y ) in text object's coordinate space. If either is zero, though, value in that dimension stays the same. Annoying, should be fixed.

Return Values

No value is returned.

SWFText->getWidth
SWFText->setColor
SWFText


Sets the current text color

SWFText->moveTo
SWFText->setFont
SWFText
PHP Manual

SWFText->setColor

(PHP 4 >= 4.0.5)

SWFText->setColor — Sets the current text color

Description

SWFText
void setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Changes the current text color.

Parameters

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Return Values

No value is returned.

SWFText->moveTo
SWFText->setFont
SWFText


Sets the current font

SWFText->setColor
SWFText->setHeight
SWFText
PHP Manual

SWFText->setFont

(PHP 4 >= 4.0.5)

SWFText->setFont — Sets the current font

Description

SWFText
void setFont ( SWFFont $font )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftext->setfont() sets the current font to font .

Return Values

No value is returned.

SWFText->setColor
SWFText->setHeight
SWFText


Sets the current font height

SWFText->setFont
SWFText->setSpacing
SWFText
PHP Manual

SWFText->setHeight

(PHP 4 >= 4.0.5)

SWFText->setHeight — Sets the current font height

Description

SWFText
void setHeight ( float $height )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftext->setheight() sets the current font height to height . Default is 240.

Return Values

No value is returned.

SWFText->setFont
SWFText->setSpacing
SWFText


Sets the current font spacing

SWFText->setHeight
SWFTextField
SWFText
PHP Manual

SWFText->setSpacing

(PHP 4 >= 4.0.5)

SWFText->setSpacing — Sets the current font spacing

Description

SWFText
void setSpacing ( float $spacing )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftext->setspacing() sets the current font spacing to spacing . Default is 1.0. 0 is all of the letters written at the same point. This doesn't really work that well because it inflates the advance across the letter, doesn't add the same amount of spacing between the letters. I should try and explain that better, prolly. Or just fix the damn thing to do constant spacing. This was really just a way to figure out how letter advances work, anyway.. So nyah.

Return Values

No value is returned.

SWFText->setHeight
SWFTextField
SWFText


adds characters to a font that will be available within a textfield

SWFTextField
SWFTextField->addString
SWFTextField
PHP Manual

SWFTextField->addChars

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField->addChars — adds characters to a font that will be available within a textfield

Description

SWFTextField
void addChars ( string $chars )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFTextField->addString

SWFTextField
SWFTextField->addString
SWFTextField


Concatenates the given string to the text field

SWFTextField->addChars
SWFTextField->align
SWFTextField
PHP Manual

SWFTextField->addString

(PHP 4 >= 4.0.5)

SWFTextField->addString — Concatenates the given string to the text field

Description

SWFTextField
void addString ( string $string )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setname() concatenates the string string to the text field.

Return Values

No value is returned.

SWFTextField->addChars
SWFTextField->align
SWFTextField


Sets the text field alignment

SWFTextField->addString
SWFTextField->__construct
SWFTextField
PHP Manual

SWFTextField->align

(PHP 4 >= 4.0.5)

SWFTextField->align — Sets the text field alignment

Description

SWFTextField
void align ( int $alignement )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->align() sets the text field alignment to alignement . Valid values for alignement are : SWFTEXTFIELD_ALIGN_LEFT, SWFTEXTFIELD_ALIGN_RIGHT, SWFTEXTFIELD_ALIGN_CENTER and SWFTEXTFIELD_ALIGN_JUSTIFY.

Return Values

No value is returned.

SWFTextField->addString
SWFTextField->__construct
SWFTextField


Creates a text field object

SWFTextField->align
SWFTextField->setBounds
SWFTextField
PHP Manual

SWFTextField->__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField->__construct — Creates a text field object

Description

SWFTextField
SWFTextField __construct ([ int $flags ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield() creates a new text field object. Text Fields are less flexible than swftext() objects- they can't be rotated, scaled non-proportionally, or skewed, but they can be used as form entries, and they can use browser-defined fonts.

The optional flags change the text field's behavior. It has the following possibles values :

  • SWFTEXTFIELD_DRAWBOX draws the outline of the textfield
  • SWFTEXTFIELD_HASLENGTH
  • SWFTEXTFIELD_HTML allows text markup using HTML-tags
  • SWFTEXTFIELD_MULTILINE allows multiple lines
  • SWFTEXTFIELD_NOEDIT indicates that the field shouldn't be user-editable
  • SWFTEXTFIELD_NOSELECT makes the field non-selectable
  • SWFTEXTFIELD_PASSWORD obscures the data entry
  • SWFTEXTFIELD_WORDWRAP allows text to wrap

Flags are combined with the bitwise OR operation. For example,

<?php
$t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT);
?>

creates a totally useless non-editable password field.

SWFTextField has the following methods : swftextfield->setfont(),
swftextfield->setbounds(), swftextfield->align(),
swftextfield->setheight(), swftextfield->setleftmargin(),
swftextfield->setrightmargin(), swftextfield->setmargins(),
swftextfield->setindentation(), swftextfield->setlinespacing(),
swftextfield->setcolor(), swftextfield->setname() and
swftextfield->addstring().

SWFTextField->align
SWFTextField->setBounds
SWFTextField


Sets the text field width and height

SWFTextField->__construct
SWFTextField->setColor
SWFTextField
PHP Manual

SWFTextField->setBounds

(PHP 4 >= 4.0.5)

SWFTextField->setBounds — Sets the text field width and height

Description

SWFTextField
void setBounds ( float $width , float $height )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setbounds() sets the text field width to width and height to height . If you don't set the bounds yourself, Ming makes a poor guess at what the bounds are.

Return Values

No value is returned.

SWFTextField->__construct
SWFTextField->setColor
SWFTextField


Sets the color of the text field

SWFTextField->setBounds
SWFTextField->setFont
SWFTextField
PHP Manual

SWFTextField->setColor

(PHP 4 >= 4.0.5)

SWFTextField->setColor — Sets the color of the text field

Description

SWFTextField
void setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.

Parameters

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Return Values

No value is returned.

SWFTextField->setBounds
SWFTextField->setFont
SWFTextField


Sets the text field font

SWFTextField->setColor
SWFTextField->setHeight
SWFTextField
PHP Manual

SWFTextField->setFont

(PHP 4 >= 4.2.0)

SWFTextField->setFont — Sets the text field font

Description

SWFTextField
void setFont ( SWFFont $font )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setfont() sets the text field font to the [browser-defined?] font font.

Return Values

No value is returned.

SWFTextField->setColor
SWFTextField->setHeight
SWFTextField


Sets the font height of this text field font

SWFTextField->setFont
SWFTextField->setIndentation
SWFTextField
PHP Manual

SWFTextField->setHeight

(PHP 4 >= 4.0.5)

SWFTextField->setHeight — Sets the font height of this text field font

Description

SWFTextField
void setHeight ( float $height )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setheight() sets the font height of this text field font to the given height height . Default is 240.

Return Values

No value is returned.

SWFTextField->setFont
SWFTextField->setIndentation
SWFTextField


Sets the indentation of the first line

SWFTextField->setHeight
SWFTextField->setLeftMargin
SWFTextField
PHP Manual

SWFTextField->setIndentation

(PHP 4 >= 4.0.5)

SWFTextField->setIndentation — Sets the indentation of the first line

Description

SWFTextField
void setIndentation ( float $width )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setindentation() sets the indentation of the first line in the text field, to width .

Return Values

No value is returned.

SWFTextField->setHeight
SWFTextField->setLeftMargin
SWFTextField


Sets the left margin width of the text field

SWFTextField->setIndentation
SWFTextField->setLineSpacing
SWFTextField
PHP Manual

SWFTextField->setLeftMargin

(PHP 4 >= 4.0.5)

SWFTextField->setLeftMargin — Sets the left margin width of the text field

Description

SWFTextField
void setLeftMargin ( float $width )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setleftmargin() sets the left margin width of the text field to width . Default is 0.

Return Values

No value is returned.

SWFTextField->setIndentation
SWFTextField->setLineSpacing
SWFTextField


Sets the line spacing of the text field

SWFTextField->setLeftMargin
SWFTextField->setMargins
SWFTextField
PHP Manual

SWFTextField->setLineSpacing

(PHP 4 >= 4.0.5)

SWFTextField->setLineSpacing — Sets the line spacing of the text field

Description

SWFTextField
void setLineSpacing ( float $height )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setlinespacing() sets the line spacing of the text field to the height of height . Default is 40.

Return Values

No value is returned.

SWFTextField->setLeftMargin
SWFTextField->setMargins
SWFTextField


Sets the margins width of the text field

SWFTextField->setLineSpacing
SWFTextField->setName
SWFTextField
PHP Manual

SWFTextField->setMargins

(PHP 4 >= 4.0.5)

SWFTextField->setMargins — Sets the margins width of the text field

Description

SWFTextField
void setMargins ( float $left , float $right )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setmargins() set both margins at once, for the man on the go.

Return Values

No value is returned.

SWFTextField->setLineSpacing
SWFTextField->setName
SWFTextField


Sets the variable name

SWFTextField->setMargins
SWFTextField->setPadding
SWFTextField
PHP Manual

SWFTextField->setName

(PHP 4 >= 4.0.5)

SWFTextField->setName — Sets the variable name

Description

SWFTextField
void setName ( string $name )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setname() sets the variable name of this text field to name , for form posting and action scripting purposes.

Return Values

No value is returned.

SWFTextField->setMargins
SWFTextField->setPadding
SWFTextField


Sets the padding of this textfield

SWFTextField->setName
SWFTextField->setRightMargin
SWFTextField
PHP Manual

SWFTextField->setPadding

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField->setPadding — Sets the padding of this textfield

Description

SWFTextField
void setPadding ( float $padding )
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

SWFTextField->setName
SWFTextField->setRightMargin
SWFTextField


Sets the right margin width of the text field

SWFTextField->setPadding
SWFVideoStream
SWFTextField
PHP Manual

SWFTextField->setRightMargin

(PHP 4 >= 4.0.5)

SWFTextField->setRightMargin — Sets the right margin width of the text field

Description

SWFTextField
void setRightMargin ( float $width )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

swftextfield->setrightmargin() sets the right margin width of the text field to width . Default is 0.

Return Values

No value is returned.

SWFTextField->setPadding
SWFVideoStream
SWFTextField


Returns a SWFVideoStream object

SWFVideoStream
SWFVideoStream->getNumFrames
SWFVideoStream
PHP Manual

SWFVideoStream->__construct

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFVideoStream->__construct — Returns a SWFVideoStream object

Description

SWFVideoStream
SWFVideoStream __construct ([ string $file ] )
Warning

This function is currently not documented; only its argument list is available.

SWFVideoStream
SWFVideoStream->getNumFrames
SWFVideoStream


Returns the number of frames in the video

SWFVideoStream->__construct
SWFVideoStream->setDimension
SWFVideoStream
PHP Manual

SWFVideoStream->getNumFrames

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFVideoStream->getNumFrames — Returns the number of frames in the video

Description

SWFVideoStream
int getNumFrames ( void )

This function returns the number of video-frames of a SWFVideoStream.

Return Values

Returns the number of frames, as an integer

SWFVideoStream->__construct
SWFVideoStream->setDimension
SWFVideoStream


Sets video dimension

SWFVideoStream->getNumFrames
PDF
SWFVideoStream
PHP Manual

SWFVideoStream->setDimension

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFVideoStream->setDimension — Sets video dimension

Description

SWFVideoStream
void setDimension ( int $x , int $y )

Sets the width and height for streamed videos.

Parameters

x

Width in pixels.

y

Height in pixels.

Return Values

No value is returned.

SWFVideoStream->getNumFrames
PDF
SWFVideoStream


Gets number of affected rows in last query

Sybase Functions
sybase_close
Sybase Functions
PHP Manual

sybase_affected_rows

(PHP 4, PHP 5)

sybase_affected_rows — Gets number of affected rows in last query

Description

int sybase_affected_rows ([ resource $link_identifier ] )

sybase_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier.

This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().

Parameters

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns the number of affected rows, as an integer.

Examples

Example #1 Delete-Query

<?php
/* connect to database */
sybase_connect('SYBASE', '', '') or
die("Could not connect");
sybase_select_db("db");

sybase_query("DELETE FROM sometable WHERE id < 10");
printf("Records deleted: %d\n", sybase_affected_rows());
?>

The above example will output:

Records deleted: 10

See Also

  • sybase_num_rows() - Get number of rows in a result set

Sybase Functions
sybase_close
Sybase Functions


Closes a Sybase connection

sybase_affected_rows
sybase_connect
Sybase Functions
PHP Manual

sybase_close

(PHP 4, PHP 5)

sybase_close — Closes a Sybase connection

Description

bool sybase_close ([ resource $link_identifier ] )

sybase_close() closes the link to a Sybase database that's associated with the specified link link_identifier .

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

sybase_close() will not close persistent links generated by sybase_pconnect().

Parameters

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_connect() - Opens a Sybase server connection
  • sybase_pconnect() - Open persistent Sybase connection

sybase_affected_rows
sybase_connect
Sybase Functions


Opens a Sybase server connection

sybase_close
sybase_data_seek
Sybase Functions
PHP Manual

sybase_connect

(PHP 4, PHP 5)

sybase_connect — Opens a Sybase server connection

Description

resource sybase_connect ([ string $servername [, string $username [, string $password [, string $charset [, string $appname [, bool $new = false ]]]]]] )

sybase_connect() establishes a connection to a Sybase server.

In case a second call is made to sybase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling sybase_close().

Parameters

servername

The servername argument has to be a valid servername that is defined in the 'interfaces' file.

username

Sybase user name

password

Password associated with username .

charset

Specifies the charset for the connection

appname

Specifies an appname for the Sybase connection. This allow you to make separate connections in the same script to the same database. This may come handy when you have started a transaction in your current connection, and you need to be able to do a separate query which cannot be performed inside this transaction.

new

Whether to open a new connection or use the existing one.

Return Values

Returns a positive Sybase link identifier on success, or FALSE on failure.

Changelog

Version | Description
5.3.0 | The new parameter was added.
4.2.0 | The appname parameter was added.
4.0.2 | The charset parameter was added.

Examples

Example #1 sybase_connect() example

<?php
$link = sybase_connect('SYBASE', '', '')
        or die("Could not connect !");
echo "Connected successfully";
sybase_close($link);
?>

See Also

  • sybase_pconnect() - Open persistent Sybase connection
  • sybase_close() - Closes a Sybase connection

sybase_close
sybase_data_seek
Sybase Functions


Moves internal row pointer

sybase_connect
sybase_deadlock_retry_count
Sybase Functions
PHP Manual

sybase_data_seek

(PHP 4, PHP 5)

sybase_data_seek — Moves internal row pointer

Description

bool sybase_data_seek ( resource $result_identifier , int $row_number )

sybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specified row number. The next call to sybase_fetch_row() would return that row.

Parameters

result_identifier

row_number

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_fetch_row() - Get a result row as an enumerated array

sybase_connect
sybase_deadlock_retry_count
Sybase Functions


Sets the deadlock retry count

sybase_data_seek
sybase_fetch_array
Sybase Functions
PHP Manual

sybase_deadlock_retry_count

(PHP 4 >= 4.3.0, PHP 5)

sybase_deadlock_retry_count — Sets the deadlock retry count

Description

void sybase_deadlock_retry_count ( int $retry_count )

Using sybase_deadlock_retry_count(), the number of retries can be defined in cases of deadlocks. By default, every deadlock is retried an infinite number of times or until the process is killed by Sybase, the executing script is killed (for instance, by set_time_limit()) or the query succeeds.

Parameters

retry_count

Values for retry_count
-1 | Retry forever (default)
0 | Do not retry
n | Retry n times

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

sybase_data_seek
sybase_fetch_array
Sybase Functions


Fetch row as array

sybase_deadlock_retry_count
sybase_fetch_assoc
Sybase Functions
PHP Manual

sybase_fetch_array

(PHP 4, PHP 5)

sybase_fetch_array — Fetch row as array

Description

array sybase_fetch_array ( resource $result )

sybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Note: When selecting fields with identical names (for instance, in a join), the associative indices will have a sequential number prepended. See the example for details.

Examples

Example #1 Identical fieldnames

<?php

$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_query('SELECT * FROM p, a WHERE p.person_id= a.person_id');
var_dump(sybase_fetch_array($q));
sybase_close($dbh);
?>

The above example would produce the following output (assuming the two tables only have each one column called "person_id"):

array(4) {
  [0]=>
  int(1)
  ["person_id"]=>
  int(1)
  [1]=>
  int(1)
  ["person_id1"]=>
  int(1)
}

See Also

  • sybase_fetch_row() - Get a result row as an enumerated array
  • sybase_fetch_assoc() - Fetch a result row as an associative array
  • sybase_fetch_object() - Fetch a row as an object

sybase_deadlock_retry_count
sybase_fetch_assoc
Sybase Functions


Fetch a result row as an associative array

sybase_fetch_array
sybase_fetch_field
Sybase Functions
PHP Manual

sybase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

sybase_fetch_assoc — Fetch a result row as an associative array

Description

array sybase_fetch_assoc ( resource $result )

sybase_fetch_assoc() is a version of sybase_fetch_row() that uses column names instead of integers for indices in the result array. Columns from different tables with the same names are returned as name, name1, name2, ..., nameN.

An important thing to note is that using sybase_fetch_assoc() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_fetch_row() - Get a result row as an enumerated array
  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_object() - Fetch a row as an object

sybase_fetch_array
sybase_fetch_field
Sybase Functions


Get field information from a result

sybase_fetch_assoc
sybase_fetch_object
Sybase Functions
PHP Manual

sybase_fetch_field

(PHP 4, PHP 5)

sybase_fetch_field — Get field information from a result

Description

object sybase_fetch_field ( resource $result [, int $field_offset = -1 ] )

sybase_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parameters

result

field_offset

If the field offset isn't specified, the next field that wasn't yet retrieved by sybase_fetch_field() is retrieved.

Return Values

Returns an object containing field information.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
  • column_source - the table from which the column was taken
  • max_length - maximum length of the column
  • numeric - 1 if the column is numeric
  • type - datatype of the column

See Also

  • sybase_field_seek() - Sets field offset

sybase_fetch_assoc
sybase_fetch_object
Sybase Functions


Fetch a row as an object

sybase_fetch_field
sybase_fetch_row
Sybase Functions
PHP Manual

sybase_fetch_object

(PHP 4, PHP 5)

sybase_fetch_object — Fetch a row as an object

Description

object sybase_fetch_object ( resource $result [, mixed $object ] )

sybase_fetch_object() is similar to sybase_fetch_assoc(), with one difference - an object is returned, instead of an array.

Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).

Parameters

result

object

Use the second object to specify the type of object you want to return. If this parameter is omitted, the object will be of type stdClass.

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Changelog

Version Description
4.3.0

This function will no longer return numeric object members. Old behaviour:

object(stdclass)(3) {
  [0]=>
  string(3) "foo"
  ["foo"]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "bar"
}
New behaviour:
object(stdclass)(3) {
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
}

Examples

Example #1 sybase_fetch_object() return as Foo

<?php
    class Foo {
        var $foo, $bar, $baz;
    }

    // {...]
    $qrh= sybase_query('SELECT foo, bar, baz FROM example');
    $foo= sybase_fetch_object($qrh, 'Foo');
    $bar= sybase_fetch_object($qrh, new Foo());
    // {...]
?>

See Also

  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_row() - Get a result row as an enumerated array

sybase_fetch_field
sybase_fetch_row
Sybase Functions


Get a result row as an enumerated array

sybase_fetch_object
sybase_field_seek
Sybase Functions
PHP Manual

sybase_fetch_row

(PHP 4, PHP 5)

sybase_fetch_row — Get a result row as an enumerated array

Description

array sybase_fetch_row ( resource $result )

sybase_fetch_row() fetches one row of data from the result associated with the specified result identifier.

Subsequent call to sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 0.

Data types
PHP | Sybase
string | VARCHAR, TEXT, CHAR, IMAGE, BINARY, VARBINARY, DATETIME
int | NUMERIC (w/o precision), DECIMAL (w/o precision), INT, BIT, TINYINT, SMALLINT
float | NUMERIC (w/ precision), DECIMAL (w/ precision), REAL, FLOAT, MONEY
NULL | NULL

See Also

  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_assoc() - Fetch a result row as an associative array
  • sybase_fetch_object() - Fetch a row as an object
  • sybase_data_seek() - Moves internal row pointer
  • sybase_result() - Get result data

sybase_fetch_object
sybase_field_seek
Sybase Functions


Sets field offset

sybase_fetch_row
sybase_free_result
Sybase Functions
PHP Manual

sybase_field_seek

(PHP 4, PHP 5)

sybase_field_seek — Sets field offset

Description

bool sybase_field_seek ( resource $result , int $field_offset )

Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.

Parameters

result

field_offset

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_fetch_field() - Get field information from a result

sybase_fetch_row
sybase_free_result
Sybase Functions


Frees result memory

sybase_field_seek
sybase_get_last_message
Sybase Functions
PHP Manual

sybase_free_result

(PHP 4, PHP 5)

sybase_free_result — Frees result memory

Description

bool sybase_free_result ( resource $result )

sybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.

Parameters

result

Return Values

Returns TRUE on success or FALSE on failure.

sybase_field_seek
sybase_get_last_message
Sybase Functions


Returns the last message from the server

sybase_free_result
sybase_min_client_severity
Sybase Functions
PHP Manual

sybase_get_last_message

(PHP 4, PHP 5)

sybase_get_last_message — Returns the last message from the server

Description

string sybase_get_last_message ( void )

sybase_get_last_message() returns the last message reported by the server.

Return Values

Returns the message as a string.

See Also

  • sybase_min_message_severity() - Sets minimum message severity

sybase_free_result
sybase_min_client_severity
Sybase Functions


Sets minimum client severity

sybase_get_last_message
sybase_min_error_severity
Sybase Functions
PHP Manual

sybase_min_client_severity

(PHP 4, PHP 5)

sybase_min_client_severity — Sets minimum client severity

Description

void sybase_min_client_severity ( int $severity )

sybase_min_client_severity() sets the minimum client severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_min_server_severity() - Sets minimum server severity

sybase_get_last_message
sybase_min_error_severity
Sybase Functions


Sets minimum error severity

sybase_min_client_severity
sybase_min_message_severity
Sybase Functions
PHP Manual

sybase_min_error_severity

(PHP 4, PHP 5)

sybase_min_error_severity — Sets minimum error severity

Description

void sybase_min_error_severity ( int $severity )

sybase_min_error_severity() sets the minimum error severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_min_message_severity() - Sets minimum message severity

sybase_min_client_severity
sybase_min_message_severity
Sybase Functions


Sets minimum message severity

sybase_min_error_severity
sybase_min_server_severity
Sybase Functions
PHP Manual

sybase_min_message_severity

(PHP 4, PHP 5)

sybase_min_message_severity — Sets minimum message severity

Description

void sybase_min_message_severity ( int $severity )

sybase_min_message_severity() sets the minimum message severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the DB library interface to Sybase, and not with the CT library.

See Also

  • sybase_min_error_severity() - Sets minimum error severity

sybase_min_error_severity
sybase_min_server_severity
Sybase Functions


Sets minimum server severity

sybase_min_message_severity
sybase_num_fields
Sybase Functions
PHP Manual

sybase_min_server_severity

(PHP 4, PHP 5)

sybase_min_server_severity — Sets minimum server severity

Description

void sybase_min_server_severity ( int $severity )

sybase_min_server_severity() sets the minimum server severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_min_client_severity() - Sets minimum client severity

sybase_min_message_severity
sybase_num_fields
Sybase Functions


Gets the number of fields in a result set

sybase_min_server_severity
sybase_num_rows
Sybase Functions
PHP Manual

sybase_num_fields

(PHP 4, PHP 5)

sybase_num_fields — Gets the number of fields in a result set

Description

int sybase_num_fields ( resource $result )

sybase_num_fields() returns the number of fields in a result set.

Parameters

result

Return Values

Returns the number of fields as an integer.

See Also

  • sybase_query() - Sends a Sybase query
  • sybase_fetch_field() - Get field information from a result
  • sybase_num_rows() - Get number of rows in a result set

sybase_min_server_severity
sybase_num_rows
Sybase Functions


Get number of rows in a result set

sybase_num_fields
sybase_pconnect
Sybase Functions
PHP Manual

sybase_num_rows

(PHP 4, PHP 5)

sybase_num_rows — Get number of rows in a result set

Description

int sybase_num_rows ( resource $result )

sybase_num_rows() returns the number of rows in a result set.

Parameters

result

Return Values

Returns the number of rows as an integer.

See Also

  • sybase_num_fields() - Gets the number of fields in a result set
  • sybase_query() - Sends a Sybase query
  • sybase_fetch_row() - Get a result row as an enumerated array

sybase_num_fields
sybase_pconnect
Sybase Functions


Open persistent Sybase connection

sybase_num_rows
sybase_query
Sybase Functions
PHP Manual

sybase_pconnect

(PHP 4, PHP 5)

sybase_pconnect — Open persistent Sybase connection

Description

resource sybase_pconnect ([ string $servername [, string $username [, string $password [, string $charset [, string $appname ]]]]] )

sybase_pconnect() acts very much like sybase_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()).

This type of links is therefore called 'persistent'.

Parameters

servername

The servername argument has to be a valid servername that is defined in the 'interfaces' file.

username

Sybase user name

password

Password associated with username .

charset

Specifies the charset for the connection

appname

Specifies an appname for the Sybase connection. This allow you to make separate connections in the same script to the same database. This may come handy when you have started a transaction in your current connection, and you need to be able to do a separate query which cannot be performed inside this transaction.

Return Values

Returns a positive Sybase persistent link identifier on success, or FALSE on error.

Changelog

Version | Description
4.2.0 | The appname parameter was added.
4.0.2 | The charset parameter was added.

See Also

  • sybase_connect() - Opens a Sybase server connection

sybase_num_rows
sybase_query
Sybase Functions


Sends a Sybase query

sybase_pconnect
sybase_result
Sybase Functions
PHP Manual

sybase_query

(PHP 4, PHP 5)

sybase_query — Sends a Sybase query

Description

mixed sybase_query ( string $query [, resource $link_identifier ] )

sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

link_identifier

If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

Return Values

Returns a positive Sybase result identifier on success, FALSE on error, or TRUE if the query was successful but didn't return any columns.

See Also

  • sybase_select_db() - Selects a Sybase database
  • sybase_connect() - Opens a Sybase server connection

sybase_pconnect
sybase_result
Sybase Functions


Get result data

sybase_query
sybase_select_db
Sybase Functions
PHP Manual

sybase_result

(PHP 4, PHP 5)

sybase_result — Get result data

Description

string sybase_result ( resource $result , int $row , mixed $field )

Returns the contents of the cell at the row and offset in the specified Sybase result set.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than sybase_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives:
sybase_fetch_row(),
sybase_fetch_array() and
sybase_fetch_object().

Parameters

result

row

field

The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

Return Values

sybase_result() returns the contents of one cell from a Sybase result set.

sybase_query
sybase_select_db
Sybase Functions


Selects a Sybase database

sybase_result
sybase_set_message_handler
Sybase Functions
PHP Manual

sybase_select_db

(PHP 4, PHP 5)

sybase_select_db — Selects a Sybase database

Description

bool sybase_select_db ( string $database_name [, resource $link_identifier ] )

sybase_select_db() sets the current active database on the server that's associated with the specified link identifier.

Every subsequent call to sybase_query() will be made on the active database.

Parameters

database_name

link_identifier

If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if sybase_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_connect() - Opens a Sybase server connection
  • sybase_pconnect() - Open persistent Sybase connection
  • sybase_query() - Sends a Sybase query

sybase_result
sybase_set_message_handler
Sybase Functions


Sets the handler called when a server message is raised

sybase_select_db
sybase_unbuffered_query
Sybase Functions
PHP Manual

sybase_set_message_handler

(PHP 4 >= 4.3.0, PHP 5)

sybase_set_message_handler — Sets the handler called when a server message is raised

Description

bool sybase_set_message_handler ( callback $handler [, resource $connection ] )

sybase_set_message_handler() sets a user function to handle messages generated by the server. You may specify the name of a global function, or use an array to specify an object reference and a method name.

Parameters

handler

The handler expects five arguments in the following order: message number, severity, state, line number and description. The first four are integers. The last is a string. If the function returns FALSE, PHP generates an ordinary error message.

connection

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
4.3.5 | The connection parameter was added.

Examples

Example #1 sybase_set_message_handler() callback function

<?php
    function msg_handler($msgnumber, $severity, $state, $line, $text)
    {
        var_dump($msgnumber, $severity, $state, $line, $text);
    }

    sybase_set_message_handler('msg_handler');
?>

Example #2 sybase_set_message_handler() callback to a class

<?php
    class Sybase {
        function handler($msgnumber, $severity, $state, $line, $text)
        {
            var_dump($msgnumber, $severity, $state, $line, $text);
        }
    }

    $sybase= new Sybase();
    sybase_set_message_handler(array($sybase, 'handler'));
?>

Example #3 sybase_set_message_handler() unhandled messages

<?php
    // Return FALSE from this function to indicate you can't handle
    // this. The error is printed out as a warning, the way you're used
    // to it if there is no handler installed.
    function msg_handler($msgnumber, $severity, $state, $line, $text)
    {
        if (257 == $msgnumber) {
            return false;
        }
        var_dump($msgnumber, $severity, $state, $line, $text);
    }

    sybase_set_message_handler('msg_handler');
?>

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

sybase_select_db
sybase_unbuffered_query
Sybase Functions


Send a Sybase query and do not block

sybase_set_message_handler
tokyo_tyrant
Sybase Functions
PHP Manual

sybase_unbuffered_query

(PHP 4 >= 4.3.0, PHP 5)

sybase_unbuffered_query — Send a Sybase query and do not block

Description

resource sybase_unbuffered_query ( string $query , resource $link_identifier [, bool $store_result ] )

sybase_unbuffered_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

Unlike sybase_query(), sybase_unbuffered_query() reads only the first row of the result set. sybase_fetch_array() and similar function read more rows as needed. sybase_data_seek() reads up to the target row. The behavior may produce better performance for large result sets.

sybase_num_rows() will only return the correct number of rows if all result sets have been read. To Sybase, the number of rows is not known and is therefore computed by the client implementation.

Note: If you don't read all of the resultsets prior to executing the next query, PHP will raise a warning and cancel all of the pending results. To get rid of this, use sybase_free_result() which will cancel pending results of an unbuffered query.

Parameters

query

link_identifier

store_result

The optional store_result can be FALSE to indicate the resultsets shouldn't be fetched into memory, thus minimizing memory usage which is particularly interesting with very large resultsets.

Return Values

Returns a positive Sybase result identifier on success, or FALSE on error.

Examples

Example #1 sybase_unbuffered_query() example

<?php

$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_unbuffered_query('select firstname, lastname from huge_table', $dbh, false);
sybase_data_seek($q, 10000);
$i = 0;

while ($row = sybase_fetch_row($q)) {
    echo $row[0], ' ', $row[1], '<br />';
    if ($i++ > 40000) {
        break;
    }
}

sybase_free_result($q);
sybase_close($dbh);

?>

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_query() - Sends a Sybase query

sybase_set_message_handler
tokyo_tyrant
Sybase Functions


Creates a symbolic link

stat
tempnam
Filesystem Functions
PHP Manual

symlink

(PHP 4, PHP 5)

symlink — Creates a symbolic link

Description

bool symlink ( string $target , string $link )

symlink() creates a symbolic link to the existing target with the specified name link .

Parameters

target

Target of the link.

link

The link name.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Examples

Example #1 Create a symbolic link

<?php
$target = 'uploads.php';
$link = 'uploads';
symlink($target, $link);

echo readlink($link);
?>

Notes

Note: For Windows only: This function will only function if the system you run PHP from is Windows Vista/Windows Server 2008 or greater. Windows versions prior to that does not support symbolic links.

See Also

  • link() - Create a hard link
  • readlink() - Returns the target of a symbolic link
  • linkinfo() - Gets information about a link

stat
tempnam
Filesystem Functions


Returns directory path used for temporary files

set_time_limit
version_compare
PHP Options/Info Functions
PHP Manual

sys_get_temp_dir

(PHP 5 >= 5.2.1)

sys_get_temp_dir — Returns directory path used for temporary files

Description

string sys_get_temp_dir ( void )

Returns the path of the directory PHP stores temporary files in by default.

Return Values

Returns the path of the temporary directory.

Examples

Example #1 sys_get_temp_dir() example

<?php
// Create a temporary file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'Tux');

echo $temp_file;
?>

The above example will output something similar to:

C:\Windows\Temp\TuxA318.tmp

See Also

  • tmpfile() - Creates a temporary file
  • tempnam() - Create file with unique file name

set_time_limit
version_compare
PHP Options/Info Functions


Gets system load average

sleep
time_nanosleep
Misc. Functions
PHP Manual

sys_getloadavg

(PHP 5 >= 5.1.3)

sys_getloadavg — Gets system load average

Description

array sys_getloadavg ( void )

Returns three samples representing the average system load (the number of processes in the system run queue) over the last 1, 5 and 15 minutes, respectively.

Return Values

Returns an array with three samples (last 1, 5 and 15 minutes).

Examples

Example #1 A sys_getloadavg() example

<?php
$load = sys_getloadavg();
if ($load[0] > 80) {
    header('HTTP/1.1 503 Too busy, try again later');
    die('Server too busy. Please try again later.');
}
?>

Notes

Note: This function is not implemented on Windows platforms.

sleep
time_nanosleep
Misc. Functions


Execute an external program and display the output

shell_exec
Expect
Program execution Functions
PHP Manual

system

(PHP 4, PHP 5)

system — Execute an external program and display the output

Description

string system ( string $command [, int &$return_var ] )

system() is just like the C version of the function in that it executes the given command and outputs the result.

The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

Parameters

command

The command that will be executed.

return_var

If the return_var argument is present, then the return status of the executed command will be written to this variable.

Return Values

Returns the last line of the command output on success, and FALSE on failure.

Examples

Example #1 system() example

<?php
echo '<pre>';

// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
$last_line = system('ls', $retval);

// Printing additional info
echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>

Notes

Warning

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note: If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.

Warning

With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x.

See Also

  • exec() - Execute an external program
  • passthru() - Execute an external program and display raw output
  • popen() - Opens process file pointer
  • escapeshellcmd() - Escape shell metacharacters
  • pcntl_exec() - Executes specified program in current process space
  • backtick operator

shell_exec
Expect
Program execution Functions


Tangent

srand
tanh
Math Functions
PHP Manual

tan

(PHP 4, PHP 5)

tan — Tangent

Description

float tan ( float $arg )

tan() returns the tangent of the arg parameter. The arg parameter is in radians.

Parameters

arg

The argument to process in radians

Return Values

The tangent of arg

Examples

Example #1 tan() example

<?php

echo tan(M_PI_4); // 1

?>

See Also

  • atan() - Arc tangent
  • atan2() - Arc tangent of two variables
  • sin() - Sine
  • cos() - Cosine
  • tanh() - Hyperbolic tangent
  • deg2rad() - Converts the number in degrees to the radian equivalent

srand
tanh
Math Functions


Hyperbolic tangent

tan
Statistics
Math Functions
PHP Manual

tanh

(PHP 4 >= 4.1.0, PHP 5)

tanh — Hyperbolic tangent

Description

float tanh ( float $arg )

Returns the hyperbolic tangent of arg , defined as sinh(arg)/cosh(arg).

Parameters

arg

The argument to process

Return Values

The hyperbolic tangent of arg

See Also

  • tan() - Tangent
  • atanh() - Inverse hyperbolic tangent
  • sinh() - Hyperbolic sine
  • cosh() - Hyperbolic cosine

tan
Statistics
Math Functions


Create file with unique file name

symlink
tmpfile
Filesystem Functions
PHP Manual

tempnam

(PHP 4, PHP 5)

tempnam — Create file with unique file name

Description

string tempnam ( string $dir , string $prefix )

Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the name of that.

Parameters

dir

The directory where the temporary filename will be created.

prefix

The prefix of the generated temporary filename.

Note: Windows uses only the first three characters of prefix.

Return Values

Returns the new temporary filename, or FALSE on failure.

Changelog

Version | Description
4.0.6 | Prior to PHP 4.0.6, the behaviour of the tempnam() function was system dependent. On Windows the TMP environment variable will override the dir parameter, on Linux the TMPDIR environment variable has precedence, while SVR4 will always use your dir parameter if the directory it points to exists. Consult your system documentation on the tempnam(3) function if in doubt.
4.0.3 | This function's behavior changed in 4.0.3. The temporary file is also created to avoid a race condition where the file might appear in the filesystem between the time the string was generated and before the script gets around to creating the file. Note, that you need to remove the file in case you need it no more, it is not done automatically.

Examples

Example #1 tempnam() example

<?php
$tmpfname = tempnam("/tmp", "FOO");

$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something

unlink($tmpfname);
?>

Notes

Note: If PHP cannot create a file in the specified dir parameter, it falls back on the system default. On NTFS this also happens if the specified dir contains more than 65534 files.

See Also

  • tmpfile() - Creates a temporary file
  • sys_get_temp_dir() - Returns directory path used for temporary files
  • unlink() - Deletes a file

symlink
tmpfile
Filesystem Functions


Sets the default domain

ngettext
i18n
Gettext Functions
PHP Manual

textdomain

(PHP 4, PHP 5)

textdomain — Sets the default domain

Description

string textdomain ( string $text_domain )

This function sets the domain to search within when calls are made to gettext(), usually the named after an application.

Parameters

text_domain

The new message domain, or NULL to get the current setting without changing it

Return Values

If successful, this function returns the current message domain, after possibly changing it.

ngettext
i18n
Gettext Functions


Return current Unix timestamp

strtotime
timezone_abbreviations_list
Date/Time Functions
PHP Manual

time

(PHP 4, PHP 5)

time — Return current Unix timestamp

Description

int time ( void )

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Examples

Example #1 time() example

<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
                   // 7 days; 24 hours; 60 mins; 60secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>

The above example will output something similar to:

Now:       2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06

Notes

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.

See Also

  • date() - Format a local time/date
  • microtime() - Return current Unix timestamp with microseconds

strtotime
timezone_abbreviations_list
Date/Time Functions


Delay for a number of seconds and nanoseconds

sys_getloadavg
time_sleep_until
Misc. Functions
PHP Manual

time_nanosleep

(PHP 5)

time_nanosleep — Delay for a number of seconds and nanoseconds

Description

mixed time_nanosleep ( int $seconds , int $nanoseconds )

Delays program execution for the given number of seconds and nanoseconds .

Parameters

seconds

Must be a positive integer.

nanoseconds

Must be a positive integer less than 1 billion.

Return Values

Returns TRUE on success or FALSE on failure.

If the delay was interrupted by a signal, an associative array will be returned with the components:

  • seconds - number of seconds remaining in the delay
  • nanoseconds - number of nanoseconds remaining in the delay

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Examples

Example #1 time_nanosleep() example

<?php
// Careful! This won't work as expected if an array is returned
if (time_nanosleep(0, 500000000)) {
    echo "Slept for half a second.\n";
}

// This is better:
if (time_nanosleep(0, 500000000) === true) {
    echo "Slept for half a second.\n";
}

// And this is the best:
$nano = time_nanosleep(2, 100000);

if ($nano === true) {
    echo "Slept for 2 seconds, 100 microseconds.\n";
} elseif ($nano === false) {
    echo "Sleeping failed.\n";
} elseif (is_array($nano)) {
    $seconds = $nano['seconds'];
    $nanoseconds = $nano['nanoseconds'];
    echo "Interrupted by a signal.\n";
    echo "Time remaining: $seconds seconds, $nanoseconds nanoseconds.";
}
?>

See Also

  • sleep() - Delay execution
  • usleep() - Delay execution in microseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time

sys_getloadavg
time_sleep_until
Misc. Functions


Make the script sleep until the specified time

time_nanosleep
uniqid
Misc. Functions
PHP Manual

time_sleep_until

(PHP 5 >= 5.1.0)

time_sleep_until — Make the script sleep until the specified time

Description

bool time_sleep_until ( float $timestamp )

Makes the script sleep until the specified timestamp .

Parameters

timestamp

The timestamp when the script should wake.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Errors/Exceptions

If the specified timestamp is in the past, this function will generate a E_WARNING.

Examples

Example #1 A time_sleep_until() example

<?php

//returns false and generates a warning
var_dump(time_sleep_until(time()-1));

// may only work on faster computers, will sleep up to 0.2 seconds
var_dump(time_sleep_until(microtime(true)+0.2));

?>

Notes

Note: All signals will be delivered after the script wakes up.

See Also

  • sleep() - Delay execution
  • usleep() - Delay execution in microseconds
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • set_time_limit() - Limits the maximum execution time

time_nanosleep
uniqid
Misc. Functions


Alias of DateTimeZone::listAbbreviations

time
timezone_identifiers_list
Date/Time Functions
PHP Manual

timezone_abbreviations_list

(PHP 5 >= 5.1.0)

timezone_abbreviations_list — Alias of DateTimeZone::listAbbreviations

Description

This function is an alias of: DateTimeZone::listAbbreviations

time
timezone_identifiers_list
Date/Time Functions


Alias of DateTimeZone::listIdentifiers

timezone_abbreviations_list
timezone_location_get
Date/Time Functions
PHP Manual

timezone_identifiers_list

(PHP 5 >= 5.1.0)

timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers

Description

This function is an alias of: DateTimeZone::listIdentifiers

timezone_abbreviations_list
timezone_location_get
Date/Time Functions


Alias of DateTimeZone::getLocation

timezone_identifiers_list
timezone_name_from_abbr
Date/Time Functions
PHP Manual

timezone_location_get

(PHP 5 >= 5.3.0)

timezone_location_get — Alias of DateTimeZone::getLocation

Description

This function is an alias of: DateTimeZone::getLocation

timezone_identifiers_list
timezone_name_from_abbr
Date/Time Functions


Returns the timezone name from abbreviation

timezone_location_get
timezone_name_get
Date/Time Functions
PHP Manual

timezone_name_from_abbr

(PHP 5 >= 5.1.3)

timezone_name_from_abbr — Returns the timezone name from abbreviation

Description

string timezone_name_from_abbr ( string $abbr [, int $gmtOffset = -1 [, int $isdst = -1 ]] )

Parameters

abbr

Time zone abbreviation.

gmtOffset

Offset from GMT in seconds. Defaults to -1 which means that first found time zone corresponding to abbr is returned. Otherwise exact offset is searched and only if not found then the first time zone with any offset is returned.

isdst

Daylight saving time indicator. If abbr doesn't exist then the time zone is searched solely by offset and isdst .

Return Values

Returns time zone name on success or FALSE on failure.

Examples

Example #1 A timezone_name_from_abbr() example

<?php
echo timezone_name_from_abbr("CET") . "\n";
echo timezone_name_from_abbr("", 3600, 0) . "\n";
?>

The above example will output something similar to:

Europe/Berlin
Europe/Paris

See Also

  • timezone_abbreviations_list() - Alias of DateTimeZone::listAbbreviations

timezone_location_get
timezone_name_get
Date/Time Functions


Alias of DateTimeZone::getName

timezone_name_from_abbr
timezone_offset_get
Date/Time Functions
PHP Manual

timezone_name_get

(PHP 5 >= 5.1.0)

timezone_name_get — Alias of DateTimeZone::getName

Description

This function is an alias of: DateTimeZone::getName

timezone_name_from_abbr
timezone_offset_get
Date/Time Functions


Alias of DateTimeZone::getOffset

timezone_name_get
timezone_open
Date/Time Functions
PHP Manual

timezone_offset_get

(PHP 5 >= 5.1.0)

timezone_offset_get — Alias of DateTimeZone::getOffset

Description

This function is an alias of: DateTimeZone::getOffset

timezone_name_get
timezone_open
Date/Time Functions


Returns new DateTimeZone object

timezone_offset_get
timezone_transitions_get
Date/Time Functions
PHP Manual

timezone_open

(PHP 5 >= 5.1.0)

timezone_open — Returns new DateTimeZone object

Description

DateTimeZone timezone_open ( string $timezone )
DateTimeZone DateTimeZone::__construct ( string $timezone )

Parameters

timezone

Time zone identifier as full name (e.g. Europe/Prague) or abbreviation (e.g. CET).

Return Values

Returns DateTimeZone object on success or FALSE on failure.

timezone_offset_get
timezone_transitions_get
Date/Time Functions


Alias of DateTimeZone::getTransitions

timezone_open
timezone_version_get
Date/Time Functions
PHP Manual

timezone_transitions_get

(PHP 5 >= 5.2.0)

timezone_transitions_get — Alias of DateTimeZone::getTransitions

Description

This function is an alias of: DateTimeZone::getTransitions

timezone_open
timezone_version_get
Date/Time Functions


Gets the version of the timezonedb

timezone_transitions_get
Command Line Specific Extensions
Date/Time Functions
PHP Manual

timezone_version_get

(PHP 5 >= 5.3.0)

timezone_version_get — Gets the version of the timezonedb

Description

string timezone_version_get ( void )

Returns the current version of the timezonedb.

Return Values

Returns a string.

Examples

Example #1 Getting the timezonedb version

<?php
echo timezone_version_get();
?>

The above example will output something similar to:

2009.7

See Also

  • List of Supported Timezones

timezone_transitions_get
Command Line Specific Extensions
Date/Time Functions


Creates a temporary file

tempnam
touch
Filesystem Functions
PHP Manual

tmpfile

(PHP 4, PHP 5)

tmpfile — Creates a temporary file

Description

resource tmpfile ( void )

Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle .

The file is automatically removed when closed (using fclose()), or when the script ends.

For details, consult your system documentation on the tmpfile(3) function, as well as the stdio.h header file.

Return Values

Returns a file handle, similar to the one returned by fopen(), for the new file or FALSE on failure.

Examples

Example #1 tmpfile() example

<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>

The above example will output:

writing to tempfile

See Also

  • tempnam() - Create file with unique file name
  • sys_get_temp_dir() - Returns directory path used for temporary files

tempnam
touch
Filesystem Functions


Sets access and modification time of file

tmpfile
umask
Filesystem Functions
PHP Manual

touch

(PHP 4, PHP 5)

touch — Sets access and modification time of file

Description

bool touch ( string $filename [, int $time = time() [, int $atime ]] )

Attempts to set the access and modification times of the file named in the filename parameter to the value given in time . Note that the access time is always modified, regardless of the number of parameters.

If the file does not exist, it will be created.

Parameters

filename

The name of the file being touched.

time

The touch time. If time is not supplied, the current system time is used.

atime

If present, the access time of the given filename is set to the value of atime . Otherwise, it is set to time .

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | It became possible to change the modification time of a directory under Windows.

Examples

Example #1 touch() example

<?php
if (touch($filename)) {
    echo $filename . ' modification time has been changed to present time';
} else {
    echo 'Sorry, could not change modification time of ' . $filename;
}
?>

Example #2 touch() using the time parameter

<?php
// This is the touch time, we'll set it to one hour in the past.
$time = time() - 3600;

// Touch the file
if (!touch('some_file.txt', $time)) {
    echo 'Whoops, something went wrong...';
} else {
    echo 'Touched file with success';
}
?>

Notes

Note: Note that time resolution may differ from one file system to another.

Warning

Prior to PHP 5.3.0 it was not possible to change the modification time of a directory with this function under Windows.

tmpfile
umask
Filesystem Functions


Generates a user-level error/warning/notice message

set_exception_handler
user_error
Error Handling Functions
PHP Manual

trigger_error

(PHP 4 >= 4.0.1, PHP 5)

trigger_error — Generates a user-level error/warning/notice message

Description

bool trigger_error ( string $error_msg [, int $error_type = E_USER_NOTICE ] )

Used to trigger a user error condition, it can be used by in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()).

This function is useful when you need to generate a particular response to an exception at runtime.

Parameters

error_msg

The designated error message for this error. It's limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.

error_type

The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

Return Values

This function returns FALSE if wrong error_type is specified, TRUE otherwise.

Examples

Example #1 trigger_error() example

See set_error_handler() for a more extensive example.

<?php
if ($divisor == 0) {
    trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?>

Notes

Warning

HTML entities in error_msg are not escaped. Use htmlentities() on the message if the error is to be displayed in a browser.

See Also

  • error_reporting() - Sets which PHP errors are reported
  • set_error_handler() - Sets a user-defined error handler function
  • restore_error_handler() - Restores the previous error handler function
  • The error level constants

set_exception_handler
user_error
Error Handling Functions


Changes the current umask

touch
unlink
Filesystem Functions
PHP Manual

umask

(PHP 4, PHP 5)

umask — Changes the current umask

Description

int umask ([ int $mask ] )

umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished.

Parameters

mask

The new umask.

Return Values

umask() without arguments simply returns the current umask otherwise the old umask is returned.

Examples

Example #1 umask() example

<?php
$old = umask(0);
chmod("/path/some_dir/some_file.txt", 0755);
umask($old);

// Checking
if ($old != umask()) {
    die('An error occured while changing back the umask');
}
?>

Notes

Note: Avoid using this function in multithreaded webservers. It is better to change the file permissions with chmod() after creating the file. Using umask() can lead to unexpected behavior of concurrently running scripts and the webserver itself because they all use the same umask.

touch
unlink
Filesystem Functions


Convert a binary string into a Unicode string

Unicode Functions
unicode_encode
Unicode Functions
PHP Manual

unicode_decode

(PHP 6 >= 6.0.0)

unicode_decode — Convert a binary string into a Unicode string

Description

unicode unicode_decode ( string $input , string $encoding [, int $errmode ] )

Convert a binary string encoded in encoding to a unicode string.

Parameters

input

Try string that is converted.

encoding

The encoding of input .

errmode

Conversion error mode. This parameter determines the action to take when the converter cannot convert a character. For a list of available modes, refer to unicode_set_error_mode(). If the parameter is not set, the global error mode is used.

Return Values

A unicode string or FALSE on failure.

Errors/Exceptions

Emits a E_WARNING level error if a converter cannot be created for the desired encoding .

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • unicode_set_error_mode() - Set the error mode for strings conversions
  • unicode_encode() - Convert a unicode string in any encoding

Unicode Functions
unicode_encode
Unicode Functions


Convert a unicode string in any encoding

unicode_decode
unicode_get_error_mode
Unicode Functions
PHP Manual

unicode_encode

(PHP 6 >= 6.0.0)

unicode_encode — Convert a unicode string in any encoding

Description

string unicode_encode ( unicode $input , string $encoding [, int $errmode ] )

Takes a unicode string and converts it to a string in the specified encoding .

Parameters

input

The unicode string that is converted.

encoding

The new encoding for input .

errmode

Conversion error mode. This parameter determines the action to take when the converter cannot convert a character. For a list of available modes, refer to unicode_set_error_mode(). If the parameter is not set, the global error mode is used.

Return Values

A string on success or FALSE on failure.

Errors/Exceptions

Emits a E_WARNING level error if a converter cannot be created for the desired encoding .

Examples

Example #1 A unicode_encode() example

Note: The characters will be seen instead of entities in the output.

<?php
header ('Content-Type: text/plain; charset=ISO-8859-2');

$encoded = unicode_encode ('\u0150\u0179', 'ISO-8859-2');

echo 'The string itself:', $encoded, PHP_EOL;
echo 'The length of the string: ', strlen ($encoded);
?>

The above example will output something similar to:

The string itself: &#336;&#377;
The length of the string: 2

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • unicode_set_error_mode() - Set the error mode for strings conversions
  • unicode_decode() - Convert a binary string into a Unicode string

unicode_decode
unicode_get_error_mode
Unicode Functions


Get the error mode for strings conversions

unicode_encode
unicode_get_subst_char
Unicode Functions
PHP Manual

unicode_get_error_mode

(PHP 6 >= 6.0.0)

unicode_get_error_mode — Get the error mode for strings conversions

Description

int unicode_get_error_mode ( int $direction )

Return the current error mode for string conversions in direction .

Parameters

direction

Get the error mode for conversion direction . This can either be FROM_UNICODE or TO_UNICODE. See unicode_set_error_mode() for more details.

Return Values

This function returns one of the error mode constants or FALSE on failure.

Errors/Exceptions

Emits a E_WARNING level error if direction is invalid.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • unicode_set_error_mode() - Set the error mode for strings conversions
  • unicode_encode() - Convert a unicode string in any encoding
  • unicode_decode() - Convert a binary string into a Unicode string

unicode_encode
unicode_get_subst_char
Unicode Functions


Get the substitution character for string conversion errors

unicode_get_error_mode
unicode_set_error_mode
Unicode Functions
PHP Manual

unicode_get_subst_char

(PHP 6 >= 6.0.0)

unicode_get_subst_char — Get the substitution character for string conversion errors

Description

unicode unicode_get_subst_char ( void )

Return the substitution character for string conversion errors set by unicode_set_subst_char().

Return Values

The unicode substitution character is returned.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • unicode_set_error_mode() - Set the error mode for strings conversions
  • unicode_set_subst_char() - Set the substitution character for string conversion errors

unicode_get_error_mode
unicode_set_error_mode
Unicode Functions


Set the error mode for strings conversions

unicode_get_subst_char
unicode_set_subst_char
Unicode Functions
PHP Manual

unicode_set_error_mode

(PHP 6 >= 6.0.0)

unicode_set_error_mode — Set the error mode for strings conversions

Description

bool unicode_set_error_mode ( int $direction , int $mode )

This function sets the error mode for string conversions between different encodings. An error can occur during conversion when an illegal character is encountered or if a character cannot be represented into the new encoding. By default, when an error is encountered, the conversion stops.

Parameters

direction

The direction sets the conversion direction to which the error mode will apply. This can either be FROM_UNICODE, which will set the error mode for conversions from a unicode string to a binary string or TO_UNICODE, which will set the error mode for conversions from a binary string to a unicode string.

mode

mode determines how the conversion errors are handled. It should be one of the following constants:

Available modes
Mode | Description
U_CONV_ERROR_STOP | Stop the conversion. This is the default mode.
U_CONV_ERROR_SKIP | Skip the character.
U_CONV_ERROR_SUBST | Substitute the character. The substituting character can be set with unicode_set_subst_char().
U_CONV_ERROR_ESCAPE_UNICODE | Escape the faulty bytes and represent them in the Unicode character format.
U_CONV_ERROR_ESCAPE_ICU | Escape the faulty bytes and represent them in the ICU character format.
U_CONV_ERROR_ESCAPE_JAVA | Escape the faulty bytes and print them in the Java character format.
U_CONV_ERROR_ESCAPE_XML_DEC | Escape the faulty bytes and represent them in decimal format.
U_CONV_ERROR_ESCAPE_XML_HEX | Escape the faulty bytes and represent them in hexadecimal format.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits a E_WARNING level error if the direction or the mode are invalid.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • unicode_encode() - Convert a unicode string in any encoding
  • unicode_decode() - Convert a binary string into a Unicode string

unicode_get_subst_char
unicode_set_subst_char
Unicode Functions


Set the substitution character for string conversion errors

unicode_set_error_mode
Image Processing and Generation
Unicode Functions
PHP Manual

unicode_set_subst_char

(PHP 6 >= 6.0.0)

unicode_set_subst_char — Set the substitution character for string conversion errors

Description

bool unicode_set_subst_char ( unicode $character )

When converting a string from or to unicode, an invalid or unconvertible character may be encountered. When the conversion error mode is set to U_CONV_ERROR_SUBST, the character that caused the error is substituted by a character set by this function. The default substitution character is ?.

Parameters

character

The substitution character to use.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits a E_WARNING level error if character is invalid.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

See Also

  • unicode_set_error_mode() - Set the error mode for strings conversions
  • unicode_get_error_mode() - Get the error mode for strings conversions
  • unicode_encode() - Convert a unicode string in any encoding
  • unicode_decode() - Convert a binary string into a Unicode string

unicode_set_error_mode
Image Processing and Generation
Unicode Functions


Generate a unique ID

time_sleep_until
unpack
Misc. Functions
PHP Manual

uniqid

(PHP 4, PHP 5)

uniqid — Generate a unique ID

Description

string uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] )

Gets a prefixed unique identifier based on the current time in microseconds.

Parameters

prefix

Can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond.

With an empty prefix , the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.

more_entropy

If set to TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which should make the results more unique.

Return Values

Returns the unique identifier, as a string.

Examples

Example #1 uniqid() Example

<?php
/* A uniqid, like: 4b3403665fea6 */
printf("uniqid(): %s\r\n", uniqid());

/* We can also prefix the uniqid, this the same as
 * doing:
 *
 * $uniqid = $prefix . uniqid();
 * $uniqid = uniqid($prefix);
 */
printf("uniqid('php_'): %s\r\n", uniqid('php_'));

/* We can also activate the more_entropy parameter, which is
 * required on some systems, like Cygwin. This makes uniqid()
 * produce a value like: 4b340550242239.64159797
 */
printf("uniqid('', true): %s\r\n", uniqid('', true));
?>

Changelog

Version | Description
5.0.0 | The prefix parameter was made optional.
4.3.1 | The limit of 114 characters long for prefix was raised.

Notes

Note: Under Cygwin, the more_entropy must be set to TRUE for this function to work.

time_sleep_until
unpack
Misc. Functions


Convert Unix timestamp to Julian Day

JulianToJD
Date/Time
Calendar Functions
PHP Manual

unixtojd

(PHP 4, PHP 5)

unixtojd — Convert Unix timestamp to Julian Day

Description

int unixtojd ([ int $timestamp = time() ] )

Return the Julian Day for a Unix timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.

Parameters

timestamp

A unix timestamp to convert.

Return Values

A julian day number as integer.

See Also

  • jdtounix() - Convert Julian Day to Unix timestamp

JulianToJD
Date/Time
Calendar Functions


Deletes a file

umask
Inotify
Filesystem Functions
PHP Manual

unlink

(PHP 4, PHP 5)

unlink — Deletes a file

Description

bool unlink ( string $filename [, resource $context ] )

Deletes filename . Similar to the Unix C unlink() function.

Parameters

filename

Path to the file.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Stream Functions.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | As of PHP 5.0.0 unlink() can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support unlink().

Examples

Example #1 Basic unlink() usage

<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);

mkdir('testdir', 0777);

unlink('test.html');
unlink('testdir');
?>

See Also

  • rmdir() - Removes directory

umask
Inotify
Filesystem Functions


Unpack data from binary string

uniqid
usleep
Misc. Functions
PHP Manual

unpack

(PHP 4, PHP 5)

unpack — Unpack data from binary string

Description

array unpack ( string $format , string $data )

Unpacks from a binary string into an array according to the given format .

unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /.

Parameters

format

See pack() for an explanation of the format codes.

data

The packed data.

Return Values

Returns an associative array containing unpacked elements of binary string.

Examples

Example #1 unpack() example

<?php
$array = unpack("c2chars/nint", $binarydata);
?>

The resulting array will contain the entries "chars1", "chars2" and "int".

Notes

Caution

Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified.

See Also

  • pack() - Pack data into binary string

uniqid
usleep
Misc. Functions


Alias of trigger_error

trigger_error
htscanner
Error Handling Functions
PHP Manual

user_error

(PHP 4, PHP 5)

user_error — Alias of trigger_error()

Description

This function is an alias of: trigger_error().

trigger_error
htscanner
Error Handling Functions


Delay execution in microseconds

unpack
Parsekit
Misc. Functions
PHP Manual

usleep

(PHP 4, PHP 5)

usleep — Delay execution in microseconds

Description

void usleep ( int $micro_seconds )

Delays program execution for the given number of micro seconds.

Parameters

micro_seconds

Halt time in micro seconds. A micro second is one millionth of a second.

Return Values

No value is returned.

Changelog

Version | Description
5.0.0 | This function now works on Windows systems.

Examples

Example #1 usleep() example

<?php

// Current time
echo date('h:i:s') . "\n";

// wait for 2 seconds
usleep(2000000);

// back!
echo date('h:i:s') . "\n";

?>

The above example will output:

11:13:28
11:13:30

See Also

  • sleep() - Delay execution
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time

unpack
Parsekit
Misc. Functions


Compares two "PHP-standardized" version number strings

sys_get_temp_dir
zend_logo_guid
PHP Options/Info Functions
PHP Manual

version_compare

(PHP 4 >= 4.1.0, PHP 5)

version_compare — Compares two "PHP-standardized" version number strings

Description

mixed version_compare ( string $version1 , string $version2 [, string $operator ] )

version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.

The function first replaces _, - and + with a dot . in the version strings and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it splits the results like if you were using explode('.', $ver). Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: any string not found in this list < dev < alpha = a < beta = b < RC = rc < # < pl = p. This way not only versions with different levels like '4.1' and '4.1.2' can be compared but also any PHP specific version containing development state.

Parameters

version1

First version number.

version2

Second version number.

operator

If you specify the third optional operator argument, you can test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.

This parameter is case-sensitive, so values should be lowercase.

Return Values

By default, version_compare() returns -1 if the first version is lower than the second, 0 if they are equal, and 1 if the second is lower.

When using the optional operator argument, the function will return TRUE if the relationship is the one specified by the operator, FALSE otherwise.

Examples

The examples below use the PHP_VERSION constant, because it contains the value of the PHP version that is executing the code.

Example #1 version_compare() examples

<?php
if (version_compare(PHP_VERSION, '6.0.0') >= 0) {
    echo 'I am at least PHP version 6.0.0, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
    echo 'I am at least PHP version 5.3.0, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.0.0', '>=')) {
    echo 'I am using PHP 5, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.0.0', '<')) {
    echo 'I am using PHP 4, my version: ' . PHP_VERSION . "\n";
}
?>

Notes

Note: The PHP_VERSION constant holds current PHP version.

Note: Note that pre-release versions, such as 5.3.0-dev, are considered lower than their final release counterparts (like 5.3.0).

See Also

  • phpversion() - Gets the current PHP version
  • php_uname() - Returns information about the operating system PHP is running on
  • function_exists() - Return TRUE if the given function has been defined

sys_get_temp_dir
zend_logo_guid
PHP Options/Info Functions


Add an alias for a virtual domain

vpopmail_add_alias_domain_ex
vpopmail_add_domain_ex
vpopmail Functions
PHP Manual

vpopmail_add_alias_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_alias_domain — Add an alias for a virtual domain

Description

bool vpopmail_add_alias_domain ( string $domain , string $aliasdomain )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_add_alias_domain_ex
vpopmail_add_domain_ex
vpopmail Functions


Add alias to an existing virtual domain

vpopmail Functions
vpopmail_add_alias_domain
vpopmail Functions
PHP Manual

vpopmail_add_alias_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_alias_domain_ex — Add alias to an existing virtual domain

Description

bool vpopmail_add_alias_domain_ex ( string $olddomain , string $newdomain )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail Functions
vpopmail_add_alias_domain
vpopmail Functions


Add a new virtual domain

vpopmail_add_domain_ex
vpopmail_add_user
vpopmail Functions
PHP Manual

vpopmail_add_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_domain — Add a new virtual domain

Description

bool vpopmail_add_domain ( string $domain , string $dir , int $uid , int $gid )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_add_domain_ex
vpopmail_add_user
vpopmail Functions


Add a new virtual domain

vpopmail_add_alias_domain
vpopmail_add_domain
vpopmail Functions
PHP Manual

vpopmail_add_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_domain_ex — Add a new virtual domain

Description

bool vpopmail_add_domain_ex ( string $domain , string $passwd [, string $quota [, string $bounce [, bool $apop ]]] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_add_alias_domain
vpopmail_add_domain
vpopmail Functions


Add a new user to the specified virtual domain

vpopmail_add_domain
vpopmail_alias_add
vpopmail Functions
PHP Manual

vpopmail_add_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_user — Add a new user to the specified virtual domain

Description

bool vpopmail_add_user ( string $user , string $domain , string $password [, string $gecos [, bool $apop ]] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_add_domain
vpopmail_alias_add
vpopmail Functions


Insert a virtual alias

vpopmail_add_user
vpopmail_alias_del_domain
vpopmail Functions
PHP Manual

vpopmail_alias_add

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_add — Insert a virtual alias

Description

bool vpopmail_alias_add ( string $user , string $domain , string $alias )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_add_user
vpopmail_alias_del_domain
vpopmail Functions


Deletes all virtual aliases of a user

vpopmail_alias_del_domain
vpopmail_alias_get_all
vpopmail Functions
PHP Manual

vpopmail_alias_del

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_del — Deletes all virtual aliases of a user

Description

bool vpopmail_alias_del ( string $user , string $domain )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_alias_del_domain
vpopmail_alias_get_all
vpopmail Functions


Deletes all virtual aliases of a domain

vpopmail_alias_add
vpopmail_alias_del
vpopmail Functions
PHP Manual

vpopmail_alias_del_domain

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_del_domain — Deletes all virtual aliases of a domain

Description

bool vpopmail_alias_del_domain ( string $domain )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_alias_add
vpopmail_alias_del
vpopmail Functions


Get all lines of an alias for a domain

vpopmail_alias_get_all
vpopmail_auth_user
vpopmail Functions
PHP Manual

vpopmail_alias_get

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_get — Get all lines of an alias for a domain

Description

array vpopmail_alias_get ( string $alias , string $domain )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_alias_get_all
vpopmail_auth_user
vpopmail Functions


Get all lines of an alias for a domain

vpopmail_alias_del
vpopmail_alias_get
vpopmail Functions
PHP Manual

vpopmail_alias_get_all

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_get_all — Get all lines of an alias for a domain

Description

array vpopmail_alias_get_all ( string $domain )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_alias_del
vpopmail_alias_get
vpopmail Functions


Attempt to validate a username/domain/password

vpopmail_alias_get
vpopmail_del_domain_ex
vpopmail Functions
PHP Manual

vpopmail_auth_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_auth_user — Attempt to validate a username/domain/password

Description

bool vpopmail_auth_user ( string $user , string $domain , string $password [, string $apop ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_alias_get
vpopmail_del_domain_ex
vpopmail Functions


Delete a virtual domain

vpopmail_del_domain_ex
vpopmail_del_user
vpopmail Functions
PHP Manual

vpopmail_del_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_domain — Delete a virtual domain

Description

bool vpopmail_del_domain ( string $domain )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_del_domain_ex
vpopmail_del_user
vpopmail Functions


Delete a virtual domain

vpopmail_auth_user
vpopmail_del_domain
vpopmail Functions
PHP Manual

vpopmail_del_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_domain_ex — Delete a virtual domain

Description

bool vpopmail_del_domain_ex ( string $domain )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_auth_user
vpopmail_del_domain
vpopmail Functions


Delete a user from a virtual domain

vpopmail_del_domain
vpopmail_error
vpopmail Functions
PHP Manual

vpopmail_del_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_user — Delete a user from a virtual domain

Description

bool vpopmail_del_user ( string $user , string $domain )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_del_domain
vpopmail_error
vpopmail Functions


Get text message for last vpopmail error

vpopmail_del_user
vpopmail_passwd
vpopmail Functions
PHP Manual

vpopmail_error

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_error — Get text message for last vpopmail error

Description

string vpopmail_error ( void )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_del_user
vpopmail_passwd
vpopmail Functions


Change a virtual user's password

vpopmail_error
vpopmail_set_user_quota
vpopmail Functions
PHP Manual

vpopmail_passwd

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_passwd — Change a virtual user's password

Description

bool vpopmail_passwd ( string $user , string $domain , string $password [, bool $apop ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_error
vpopmail_set_user_quota
vpopmail Functions


Sets a virtual user's quota

vpopmail_passwd
Mathematical Extensions
vpopmail Functions
PHP Manual

vpopmail_set_user_quota

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_set_user_quota — Sets a virtual user's quota

Description

bool vpopmail_set_user_quota ( string $user , string $domain , string $quota )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Warning

This function is currently not documented; only its argument list is available.

vpopmail_passwd
Mathematical Extensions
vpopmail Functions


Retrieves information about files cached in the file cache

WinCache Functions
wincache_fcache_meminfo
WinCache Functions
PHP Manual

wincache_fcache_fileinfo

(PECL wincache >= 1.0.0)

wincache_fcache_fileinfo — Retrieves information about files cached in the file cache

Description

array wincache_fcache_fileinfo ( void )

Retrieves information about file cache content and its usage.

Return Values

Array of meta data about file cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the file cache has been active
  • total_file_count - total number of files that are currently in the file cache
  • total_hit_count - number of times the files have been served from the file cache
  • total_miss_count - number of times the files have not been found in the file cache

  • file_entries - an array that contains the information about all the cached files:

    • file_name - absolute file name of the cached file
    • add_time - time in seconds since the file has been added to the file cache
    • use_time - time in seconds since the file has been accessed in the file cache
    • last_check - time in seconds since the file has been checked for modifications
    • hit_count - number of times the file has been served from the cache
    • file_size - size of the cached file in bytes

Examples

Example #1 A wincache_fcache_fileinfo() example

<pre>
<?php
print_r(wincache_fcache_fileinfo());
?>
</pre>

The above example will output:

Array
(   [total_cache_uptime] => 3234
    [total_file_count] => 5
    [total_hit_count] => 0
    [total_miss_count] => 1
    [file_entries] => Array
        (
            [1] => Array
                (
                    [file_name] => c:\inetpub\wwwroot\checkcache.php
                    [add_time] => 1
                    [use_time] => 0
                    [last_check] => 1
                    [hit_count] => 1
                    [file_size] => 2435
                )
            [2] => Array (...iterates for each cached file)
        )
)

See Also

  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files

WinCache Functions
wincache_fcache_meminfo
WinCache Functions


Retrieves information about file cache memory usage

wincache_fcache_fileinfo
wincache_ocache_fileinfo
WinCache Functions
PHP Manual

wincache_fcache_meminfo

(PECL wincache >= 1.0.0)

wincache_fcache_meminfo — Retrieves information about file cache memory usage

Description

array wincache_fcache_meminfo ( void )

Retrieves information about memory usage by file cache.

Return Values

Array of meta data about file cache memory usage or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the file cache
  • memory_free - amount of free memory in bytes available for the file cache
  • num_used_blks - number of memory blocks used by the file cache
  • num_free_blks - number of free memory blocks available for the file cache
  • memory_overhead - amount of memory in bytes used for the file cache internal structures

Examples

Example #1 A wincache_fcache_meminfo() example

<pre>
<?php
print_r(wincache_fcache_meminfo());
?>
</pre>

The above example will output:

Array
(
    [memory_total] => 134217728
    [memory_free] => 131339120
    [num_used_blks] => 361
    [num_free_blks] => 3
    [memory_overhead] => 5856
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files

wincache_fcache_fileinfo
wincache_ocache_fileinfo
WinCache Functions


Retrieves information about files cached in the opcode cache

wincache_fcache_meminfo
wincache_ocache_meminfo
WinCache Functions
PHP Manual

wincache_ocache_fileinfo

(PECL wincache >= 1.0.0)

wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache

Description

array wincache_ocache_fileinfo ( void )

Retrieves information about opcode cache content and its usage.

Return Values

Array of meta data about opcode cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the opcode cache has been active
  • total_file_count - total number of files that are currently in the opcode cache
  • total_hit_count - number of times the compiled opcode have been served from the cache
  • total_miss_count - number of times the compiled opcode have not been found in the cache
  • is_local_cache - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache

  • file_entries - an array that contains the information about all the cached files:

    • file_name - absolute file name of the cached file
    • add_time - time in seconds since the file has been added to the opcode cache
    • use_time - time in seconds since the file has been accessed in the opcode cache
    • last_check - time in seconds since the file has been checked for modifications
    • hit_count - number of times the file has been served from the cache
    • function_count - number of functions in the cached file
    • class_count - number of classes in the cached file

Examples

Example #1 A wincache_ocache_fileinfo() example

<pre>
<?php
print_r(wincache_ocache_fileinfo());
?>
</pre>

The above example will output:

Array
(
    [total_cache_uptime] => 17357
    [total_file_count] => 121
    [total_hit_count] => 36562
    [total_miss_count] => 201
    [file_entries] => Array
        (
            [1] => Array
                (
                    [file_name] => c:\inetpub\wwwroot\checkcache.php
                    [add_time] => 17356
                    [use_time] => 7
                    [last_check] => 10
                    [hit_count] => 454
                    [function_count] => 0
                    [class_count] => 1
                )
            [2] => Array (...iterates for each cached file)
        )
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files

wincache_fcache_meminfo
wincache_ocache_meminfo
WinCache Functions


Retrieves information about opcode cache memory usage

wincache_ocache_fileinfo
wincache_refresh_if_changed
WinCache Functions
PHP Manual

wincache_ocache_meminfo

(PECL wincache >= 1.0.0)

wincache_ocache_meminfo — Retrieves information about opcode cache memory usage

Description

array wincache_ocache_meminfo ( void )

Retrieves information about memory usage by opcode cache.

Return Values

Array of meta data about opcode cache memory usage or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the opcode cache
  • memory_free - amount of free memory in bytes available for the opcode cache
  • num_used_blks - number of memory blocks used by the opcode cache
  • num_free_blks - number of free memory blocks available for the opcode cache
  • memory_overhead - amount of memory in bytes used for the opcode cache internal structures

Examples

Example #1 A wincache_ocache_meminfo() example

<pre>
<?php
print_r(wincache_ocache_meminfo());
?>
</pre>

The above example will output:

Array
(
    [memory_total] => 134217728
    [memory_free] => 112106972
    [num_used_blks] => 15469
    [num_free_blks] => 4
    [memory_overhead] => 247600
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files

wincache_ocache_fileinfo
wincache_refresh_if_changed
WinCache Functions


Refreshes the cache entries for the cached files

wincache_ocache_meminfo
wincache_rplist_fileinfo
WinCache Functions
PHP Manual

wincache_refresh_if_changed

(PECL wincache >= 1.0.0)

wincache_refresh_if_changed — Refreshes the cache entries for the cached files

Description

bool wincache_refresh_if_changed ([ array $files ] )

Refreshes the cache entries for the files, whose names were passed in the input argument. If no argument is specified then refreshes all the entries in the cache.

Parameters

files

An array of file names for files that need to be refreshed. An absolute or relative file paths can be used.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

WinCache performs regular checks on the cached files to ensure that if any file has changed then the corresponding entry in the cache is updated. By default this check is performed every 30 seconds. If, for example, a PHP script updates another PHP script where the application's configuration settings are stored, then it may happen that after the configuration settings have been saved to a file, the application is still using old settings for some time until the cache is refreshed. In those cases it may be preferrable to refresh the cache right after the file has been changed. The following example shows how this can be done.

Example #1 A wincache_refresh_if_changed() example

<?php
$filename = 'C:\inetpub\wwwroot\config.php';
$handle = fopen($filename, 'w+');
if ($handle === FALSE) die('Failed to open file '.$filename.' for writing');
fwrite($handle, '<?php $setting=something; ?>');
fclose($handle);
wincache_refresh_if_changed(array($filename));
?>

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache

wincache_ocache_meminfo
wincache_rplist_fileinfo
WinCache Functions


Retrieves information about resolve file path cache

wincache_refresh_if_changed
wincache_rplist_meminfo
WinCache Functions
PHP Manual

wincache_rplist_fileinfo

(PECL wincache >= 1.0.0)

wincache_rplist_fileinfo — Retrieves information about resolve file path cache

Description

array wincache_rplist_fileinfo ( void )

Retrieves information about cached mappings between relative file paths and corresponding absolute file paths.

Return Values

Array of meta data about the resolve file path cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_file_count - total number of file path mappings stored in the cache

  • rplist_entries - an array that contains the information about all the cached file paths:

    • resolve_path - path to a file
    • subkey_data - corresponding absolute path to a file

Examples

Example #1 A wincache_rplist_fileinfo() example

<pre>
<?php
print_r(wincache_rplist_fileinfo());
?>
</pre>

The above example will output:

Array
(
    [total_file_count] => 5
    [rplist_entries] => Array
        (
            [1] => Array
                (
                    [resolve_path] => checkcache.php
                    [subkey_data] => c:\inetpub\wwwroot|c:\inetpub\wwwroot\checkcache.php
                )

            [2] => Array (...iterates for each cached file)
        )
)

See Also

  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files

wincache_refresh_if_changed
wincache_rplist_meminfo
WinCache Functions


Retrieves information about memory usage by the resolve file path cache

wincache_rplist_fileinfo
Building for Windows
WinCache Functions
PHP Manual

wincache_rplist_meminfo

(PECL wincache >= 1.0.0)

wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache

Description

array wincache_rplist_meminfo ( void )

Retrieves information about memory usage by resolve file path cache.

Return Values

Array of meta data that describes memory usage by resolve file path cache. or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the resolve file path cache
  • memory_free - amount of free memory in bytes available for the resolve file path cache
  • num_used_blks - number of memory blocks used by the resolve file path cache
  • num_free_blks - number of free memory blocks available for the resolve file path cache
  • memory_overhead - amount of memory in bytes used for the internal structures of resolve file path cache

Examples

Example #1 A wincache_rplist_meminfo() example

<pre>
<?php
print_r(wincache_rplist_meminfo());
?>
</pre>

The above example will output:

Array
(
    [memory_total] => 9437184
    [memory_free] => 9416744
    [num_used_blks] => 23
    [num_free_blks] => 1
    [memory_overhead] => 416
)

See Also

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files

wincache_rplist_fileinfo
Building for Windows
WinCache Functions


Get an extended attribute

xattr Functions
xattr_list
xattr Functions
PHP Manual

xattr_get

(PECL xattr >= 0.9.0)

xattr_get — Get an extended attribute

Description

string xattr_get ( string $filename , string $name [, int $flags = 0 ] )

This function gets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The file from which we get the attribute.

name

The name of the attribute.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

Returns a string containing the value or FALSE if the attribute doesn't exist.

Examples

Example #1 Checks if system administrator has signed the file

<?php
$file = '/usr/local/sbin/some_binary';
$signature = xattr_get($file, 'Root signature', XATTR_ROOT);

/* ... check if $signature is valid ... */

?>

See Also

  • xattr_list() - Get a list of extended attributes
  • xattr_set() - Set an extended attribute
  • xattr_remove() - Remove an extended attribute

xattr Functions
xattr_list
xattr Functions


Get a list of extended attributes

xattr_get
xattr_remove
xattr Functions
PHP Manual

xattr_list

(PECL xattr >= 0.9.0)

xattr_list — Get a list of extended attributes

Description

array xattr_list ( string $filename [, int $flags = 0 ] )

This functions gets a list of names of extended attributes of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The path of the file.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

This function returns an array with names of extended attributes.

Examples

Example #1 Prints names of all extended attributes of file

<?php
$file = 'some_file';
$root_attributes = xattr_list($file, XATTR_ROOT);
$user_attributes = xattr_list($file);

echo "Root attributes: \n";
foreach ($root_attributes as $attr_name) {
    printf("%s\n", $attr_name);
}

echo "\n User attributes: \n";
foreach ($attributes as $attr_name) {
    printf("%s\n", $attr_name);
}

?>

See Also

  • xattr_get() - Get an extended attribute

xattr_get
xattr_remove
xattr Functions


Remove an extended attribute

xattr_list
xattr_set
xattr Functions
PHP Manual

xattr_remove

(PECL xattr >= 0.9.0)

xattr_remove — Remove an extended attribute

Description

bool xattr_remove ( string $filename , string $name [, int $flags = 0 ] )

This function removes an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The file from which we remove the attribute.

name

The name of the attribute to remove.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Removes all extended attributes of a file

<?php
$file = 'some_file';
$attributes = xattr_list($file);

foreach ($attributes as $attr_name) {
    xattr_remove($file, $attr_name);
}
?>

See Also

  • xattr_list() - Get a list of extended attributes
  • xattr_set() - Set an extended attribute
  • xattr_get() - Get an extended attribute

xattr_list
xattr_set
xattr Functions


Set an extended attribute

xattr_remove
xattr_supported
xattr Functions
PHP Manual

xattr_set

(PECL xattr >= 0.9.0)

xattr_set — Set an extended attribute

Description

bool xattr_set ( string $filename , string $name , string $value [, int $flags = 0 ] )

This function sets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The file in which we set the attribute.

name

The name of the extended attribute. This attribute will be created if it doesn't exist or replaced otherwise. You can change this behaviour by using the flags parameter.

value

The value of the attribute.

flags

Supported xattr flags
XATTR_CREATE | Function will fail if extended attribute already exists.
XATTR_REPLACE | Function will fail if extended attribute doesn't exist.
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Sets extended attributes on .wav file

<?php
$file = 'my_favourite_song.wav';
xattr_set($file, 'Artist', 'Someone');
xattr_set($file, 'My ranking', 'Good');
xattr_set($file, 'Listen count', '34');

/* ... other code ... */

printf("You've played this song %d times", xattr_get($file, 'Listen count'));
?>

See Also

  • xattr_get() - Get an extended attribute
  • xattr_remove() - Remove an extended attribute

xattr_remove
xattr_supported
xattr Functions


Check if filesystem supports extended attributes

xattr_set
xdiff
xattr Functions
PHP Manual

xattr_supported

(PECL xattr >= 1.0.0)

xattr_supported — Check if filesystem supports extended attributes

Description

bool xattr_supported ( string $filename [, int $flags = 0 ] )

This functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required.

Parameters

filename

The path of the tested file.

flags

Supported xattr flags
XATTR_DONTFOLLOW Do not follow the symbolic link but operate on symbolic link itself.

Return Values

This function returns TRUE if filesystem supports extended attributes, FALSE if it doesn't and NULL if it can't be determined (for example wrong path or lack of permissions to file).

Examples

Example #1 xattr_supported() example

The following code checks if we can use extended attributes.

<?php
$file = 'some_file';

if (xattr_supported($file)) {
    /* ... make use of some xattr_* functions ... */
}

?>

See Also

  • xattr_get() - Get an extended attribute
  • xattr_list() - Get a list of extended attributes

xattr_set
xdiff
xattr Functions


Make binary diff of two files

xdiff_file_bdiff_size
xdiff_file_bpatch
xdiff Functions
PHP Manual

xdiff_file_bdiff

(PECL xdiff >= 0.2.0)

xdiff_file_bdiff — Make binary diff of two files

Description

bool xdiff_file_bdiff ( string $old_file , string $new_file , string $dest )

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_bdiff() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_bdiff($old_version, $new_version, 'my_script.bdiff');
?>

Notes

Note: Both files will be loaded into memory so ensure that your memory_limit is set high enough.

See Also

  • xdiff_file_bpatch() - Patch a file with a binary diff

xdiff_file_bdiff_size
xdiff_file_bpatch
xdiff Functions


Read a size of file created by applying a binary diff

xdiff Functions
xdiff_file_bdiff
xdiff Functions
PHP Manual

xdiff_file_bdiff_size

(PECL xdiff >= 0.2.0)

xdiff_file_bdiff_size — Read a size of file created by applying a binary diff

Description

int xdiff_file_bdiff_size ( string $file )

Returns a size of a result file that would be created after applying binary patch from file file to the original file.

Parameters

file

The path to the binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Return Values

Returns the size of file that would be created.

Examples

Example #1 xdiff_file_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

<?php
$length = xdiff_string_bdiff_size('file.bdiff');
echo "Resulting file will be $length bytes long";
?>

See Also

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_rabdiff() - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
  • xdiff_file_bpatch() - Patch a file with a binary diff

xdiff Functions
xdiff_file_bdiff
xdiff Functions


Patch a file with a binary diff

xdiff_file_bdiff
xdiff_file_diff_binary
xdiff Functions
PHP Manual

xdiff_file_bpatch

(PECL xdiff >= 0.2.0)

xdiff_file_bpatch — Patch a file with a binary diff

Description

bool xdiff_file_bpatch ( string $file , string $patch , string $dest )

Patches a file with a binary patch and stores the result in a file dest . This function accepts patches created both via xdiff_file_bdiff() and xdiff_file_rabdiff() functions or their string counterparts.

Parameters

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_bpatch() example

The following code applies binary diff to a file.

<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';

$result = xdiff_file_bpatch($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
   echo "File patched";
} else {
   echo "File couldn't be patched";
}

?>

Notes

Note: Both files (file and patch ) will be loaded into memory so ensure that your memory_limit is set high enough.

See Also

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_rabdiff() - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

xdiff_file_bdiff
xdiff_file_diff_binary
xdiff Functions


Make unified diff of two files

xdiff_file_diff_binary
xdiff_file_merge3
xdiff Functions
PHP Manual

xdiff_file_diff

(PECL xdiff >= 0.2.0)

xdiff_file_diff — Make unified diff of two files

Description

bool xdiff_file_diff ( string $old_file , string $new_file , string $dest [, int $context = 3 [, bool $minimal = false ]] )

Makes an unified diff containing differences between old_file and new_file and stores it in dest file. The resulting file is human-readable. An optional context parameter specifies how many lines of context should be added around each change. Setting minimal parameter to true will result in outputting the shortest patch file possible (can take a long time).

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file.

context

Indicates how many lines of context you want to include in diff result.

minimal

Set this parameter to TRUE if you want to minimalize size of the result (can take a long time).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_diff() example

The following code makes unified diff of two php files with context length of 2.

<?php
$old_version = 'my_script.php';
$new_version = 'my_new_script.php';

xdiff_file_diff($old_version, $new_version, 'my_script.diff', 2);
?>

Notes

Note: This function doesn't work well with binary files. To make diff of binary files use xdiff_file_bdiff()/xdiff_file_rabdiff() function.

See Also

  • xdiff_file_patch() - Patch a file with an unified diff

xdiff_file_diff_binary
xdiff_file_merge3
xdiff Functions


Alias of xdiff_file_bdiff

xdiff_file_bpatch
xdiff_file_diff
xdiff Functions
PHP Manual

xdiff_file_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_file_diff_binary — Alias of xdiff_file_bdiff

Description

bool xdiff_file_diff_binary ( string $old_file , string $new_file , string $dest )

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_file_bdiff().

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_diff_binary() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_diff_binary($old_version, $new_version, 'my_script.bdiff');
?>

Notes

Note: Both files will be loaded into memory so ensure that your memory_limit is set high enough.

See Also

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_bpatch() - Patch a file with a binary diff

xdiff_file_bpatch
xdiff_file_diff
xdiff Functions


Merge 3 files into one

xdiff_file_diff
xdiff_file_patch_binary
xdiff Functions
PHP Manual

xdiff_file_merge3

(PECL xdiff >= 0.2.0)

xdiff_file_merge3 — Merge 3 files into one

Description

mixed xdiff_file_merge3 ( string $old_file , string $new_file1 , string $new_file2 , string $dest )

Merges three files into one and stores the result in a file dest . The old_file is an original version while new_file1 and new_file2 are modified versions of an original.

Parameters

old_file

Path to the first file. It acts as "old" file.

new_file1

Path to the second file. It acts as modified version of old_file .

new_file2

Path to the third file. It acts as modified version of old_file .

dest

Path of the resulting file, containing merged changed from both new_file1 and new_file2 .

Return Values

Returns TRUE if merge was successful, string with rejected chunks if it was not or FALSE if an internal error happened.

Examples

Example #1 xdiff_file_merge3() example

The following code merges three files into one.

<?php
$old_version = 'original_script.php';
$fix1 = 'script_with_fix1.php';
$fix2 = 'script_with_fix2.php';

$errors = xdiff_file_merge3($old_version, $fix1, $fix2, 'fixed_script.php');
if (is_string($errors)) {
    echo "Rejects:\n";
    echo $errors;
}
?>

See Also

  • xdiff_string_merge3() - Merge 3 strings into one

xdiff_file_diff
xdiff_file_patch_binary
xdiff Functions


Patch a file with an unified diff

xdiff_file_patch_binary
xdiff_file_rabdiff
xdiff Functions
PHP Manual

xdiff_file_patch

(PECL xdiff >= 0.2.0)

xdiff_file_patch — Patch a file with an unified diff

Description

mixed xdiff_file_patch ( string $file , string $patch , string $dest [, int $flags = DIFF_PATCH_NORMAL ] )

Patches a file with a patch and stores the result in a file. patch has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional flags parameter specifies mode of operation.

Parameters

file

The original file.

patch

The unified patch file. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

dest

Path of the resulting file.

flags

Can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Starting from version 1.5.0, you can also use binary OR to enable XDIFF_PATCH_IGNORESPACE flag.

Return Values

Returns FALSE if an internal error happened, string with rejected chunks if patch couldn't be applied or TRUE if patch has been successfully applied.

Examples

Example #1 xdiff_file_patch() example

The following code applies unified diff to a file.

<?php
$old_version = 'my_script-1.0.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($old_version, $patch, 'my_script-1.1.php');
if (is_string($errors)) {
   echo "Rejects:\n";
   echo $errors;
}

?>

Example #2 Patch reversing example

The following code reverses a patch.

<?php
$new_version = 'my_script-1.1.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($new_version, $patch, 'my_script-1.0.php', XDIFF_PATCH_REVERSE);
if (is_string($errors)) {
   echo "Rejects:\n";
   echo $errors;
}

?>

See Also

  • xdiff_file_diff() - Make unified diff of two files

xdiff_file_patch_binary
xdiff_file_rabdiff
xdiff Functions


Alias of xdiff_file_bpatch

xdiff_file_merge3
xdiff_file_patch
xdiff Functions
PHP Manual

xdiff_file_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_file_patch_binary — Alias of xdiff_file_bpatch

Description

bool xdiff_file_patch_binary ( string $file , string $patch , string $dest )

Patches a file with a binary patch and stores the result in a file dest . This function accepts patches created both via xdiff_file_bdiff() or xdiff_file_rabdiff() functions or their string counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_file_bpatch().

Parameters

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_patch_binary() example

The following code applies binary diff to a file.

<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';

$result = xdiff_file_patch_binary($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
   echo "File patched";
} else {
   echo "File couldn't be patched";
}

?>

Notes

Note: Both files (file and patch ) will be loaded into memory so ensure that your memory_limit is set high enough.

See Also

  • xdiff_string_patch_binary() - Alias of xdiff_string_bpatch

xdiff_file_merge3
xdiff_file_patch
xdiff Functions


Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

xdiff_file_patch
xdiff_string_bdiff_size
xdiff Functions
PHP Manual

xdiff_file_rabdiff

(PECL xdiff >= 0.2.0)

xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

Description

bool xdiff_file_rabdiff ( string $old_file , string $new_file , string $dest )

Makes a binary diff of two files and stores the result in a patch file. The difference between this function and xdiff_file_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_rabdiff() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_rabdiff($old_version, $new_version, 'my_script.bdiff');
?>

Notes

Note: Both files will be loaded into memory so ensure that your memory_limit is set high enough.

See Also

  • xdiff_file_bpatch() - Patch a file with a binary diff

xdiff_file_patch
xdiff_string_bdiff_size
xdiff Functions


Make binary diff of two strings

xdiff_string_bdiff_size
xdiff_string_bpatch
xdiff Functions
PHP Manual

xdiff_string_bdiff

(PECL xdiff >= 0.2.0)

xdiff_string_bdiff — Make binary diff of two strings

Description

string xdiff_string_bdiff ( string $old_data , string $new_data )

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

Parameters

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Return Values

Returns string with binary diff containing differences between "old" and "new" data or FALSE if an internal error occurred.

See Also

  • xdiff_string_bpatch() - Patch a string with a binary diff

xdiff_string_bdiff_size
xdiff_string_bpatch
xdiff Functions


Read a size of file created by applying a binary diff

xdiff_file_rabdiff
xdiff_string_bdiff
xdiff Functions
PHP Manual

xdiff_string_bdiff_size

(PECL xdiff >= 0.2.0)

xdiff_string_bdiff_size — Read a size of file created by applying a binary diff

Description

int xdiff_string_bdiff_size ( string $patch )

Returns a size of a result file that would be created after applying binary patch to the original file.

Parameters

patch

The binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Return Values

Returns the size of file that would be created.

Examples

Example #1 xdiff_string_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

<?php
$binary_patch = file_get_contents('file.bdiff');
$length = xdiff_string_bdiff_size($binary_patch);
echo "Resulting file will be $length bytes long";
?>

See Also

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
  • xdiff_string_bpatch() - Patch a string with a binary diff

xdiff_file_rabdiff
xdiff_string_bdiff
xdiff Functions


Patch a string with a binary diff

xdiff_string_bdiff
xdiff_string_diff_binary
xdiff Functions
PHP Manual

xdiff_string_bpatch

(PECL xdiff >= 0.2.0)

xdiff_string_bpatch — Patch a string with a binary diff

Description

string xdiff_string_bpatch ( string $str , string $patch )

Patches a string str with a binary patch . This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

Parameters

str

The original binary string.

patch

The binary patch string.

Return Values

Returns the patched string, or FALSE on error.

See Also

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_bdiff
xdiff_string_diff_binary
xdiff Functions


Make unified diff of two strings

xdiff_string_diff_binary
xdiff_string_merge3
xdiff Functions
PHP Manual

xdiff_string_diff

(PECL xdiff >= 0.2.0)

xdiff_string_diff — Make unified diff of two strings

Description

string xdiff_string_diff ( string $old_data , string $new_data [, int $context = 3 [, bool $minimal = false ]] )

Makes an unified diff containing differences between old_data string and new_data string and returns it. The resulting diff is human-readable. An optional context parameter specifies how many lines of context should be added around each change. Setting minimal parameter to true will result in outputting the shortest patch file possible (can take a long time).

Parameters

old_data

First string with data. It acts as "old" data.

new_data

Second string with data. It acts as "new" data.

context

Indicates how many lines of context you want to include in the diff result.

minimal

Set this parameter to TRUE if you want to minimalize the size of the result (can take a long time).

Return Values

Returns string with resulting diff or FALSE if an internal error happened.

Examples

Example #1 xdiff_string_diff() example

The following code makes unified diff of two articles.

<?php
$old_article = file_get_contents('./old_article.txt');
$new_article = $_REQUEST['article']; /* Let's say that someone pasted a new article to html form */

$diff = xdiff_string_diff($old_article, $new_article, 1);
if (is_string($diff)) {
    echo "Differences between two articles:\n";
    echo $diff;
}

?>

Notes

Note: This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_bdiff()/xdiff_string_rabdiff().

See Also

  • xdiff_string_patch() - Patch a string with an unified diff

xdiff_string_diff_binary
xdiff_string_merge3
xdiff Functions


Alias of xdiff_string_bdiff

xdiff_string_bpatch
xdiff_string_diff
xdiff Functions
PHP Manual

xdiff_string_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_string_diff_binary — Alias of xdiff_string_bdiff

Description

string xdiff_string_bdiff ( string $old_data , string $new_data )

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_string_bdiff().

Parameters

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Return Values

Returns string with result or FALSE if an internal error happened.

See Also

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_bpatch() - Patch a string with a binary diff

xdiff_string_bpatch
xdiff_string_diff
xdiff Functions


Merge 3 strings into one

xdiff_string_diff
xdiff_string_patch_binary
xdiff Functions
PHP Manual

xdiff_string_merge3

(PECL xdiff >= 0.2.0)

xdiff_string_merge3 — Merge 3 strings into one

Description

mixed xdiff_string_merge3 ( string $old_data , string $new_data1 , string $new_data2 [, string &$error ] )

Merges three strings into one and returns the result. The old_data is an original version of data while new_file1 and new_file2 are modified versions of an original. An optional error is used to pass any rejected parts during merging process.

Parameters

old_data

First string with data. It acts as "old" data.

new_data1

Second string with data. It acts as modified version of old_data .

new_data2

Third string with data. It acts as modified version of old_data .

error

If provided then rejected parts are stored inside this variable.

Return Values

Returns the merged string, FALSE if an internal error happened, or TRUE if merged string is empty.

See Also

  • xdiff_file_merge3() - Merge 3 files into one

xdiff_string_diff
xdiff_string_patch_binary
xdiff Functions


Patch a string with an unified diff

xdiff_string_patch_binary
xdiff_string_rabdiff
xdiff Functions
PHP Manual

xdiff_string_patch

(PECL xdiff >= 0.2.0)

xdiff_string_patch — Patch a string with an unified diff

Description

string xdiff_string_patch ( string $str , string $patch [, int $flags [, string &$error ]] )

Patches a str string with an unified patch in patch parameter and returns the result. patch has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional flags parameter specifies mode of operation. Any rejected parts of the patch will be stored inside error variable if it is provided.

Parameters

str

The original string.

patch

The unified patch string. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

flags

flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Starting from version 1.5.0, you can also use binary OR to enable XDIFF_PATCH_IGNORESPACE flag.

error

If provided then rejected parts are stored inside this variable.

Return Values

Returns the patched string, or FALSE on error.

Examples

Example #1 xdiff_string_patch() example

The following code applies changes to some article.

<?php
$old_article = file_get_contents('./old_article.txt');
$diff = $_SERVER['patch']; /* Let's say that someone pasted a patch to html form */

$errors = '';

$new_article = xdiff_string_patch($old_article, $diff, XDIFF_PATCH_NORMAL, $errors);
if (is_string($new_article)) {
    echo "New article:\n";
    echo $new_article;
}

if (strlen($errors)) {
    echo "Rejects: \n";
    echo $errors;
}

?>

See Also

  • xdiff_string_diff() - Make unified diff of two strings

xdiff_string_patch_binary
xdiff_string_rabdiff
xdiff Functions


Alias of xdiff_string_bpatch

xdiff_string_merge3
xdiff_string_patch
xdiff Functions
PHP Manual

xdiff_string_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_string_patch_binary — Alias of xdiff_string_bpatch

Description

string xdiff_string_patch_binary ( string $str , string $patch )

Patches a string str with a binary patch . This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_string_bpatch().

Parameters

str

The original binary string.

patch

The binary patch string.

Return Values

Returns the patched string, or FALSE on error.

See Also

  • xdiff_string_bpatch() - Patch a string with a binary diff
  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_merge3
xdiff_string_patch
xdiff Functions


Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_patch
Human Language and Character Encoding Support
xdiff Functions
PHP Manual

xdiff_string_rabdiff

(PECL xdiff >= 0.2.0)

xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

Description

string xdiff_string_bdiff ( string $old_data , string $new_data )

Makes a binary diff of two strings and returns the result. The difference between this function and xdiff_string_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

Parameters

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Return Values

Returns string with binary diff containing differences between "old" and "new" data or FALSE if an internal error occurred.

See Also

  • xdiff_string_bpatch() - Patch a string with a binary diff

xdiff_string_patch
Human Language and Character Encoding Support
xdiff Functions


Gets the Zend guid

version_compare
zend_thread_id
PHP Options/Info Functions
PHP Manual

zend_logo_guid

(PHP 4, PHP 5)

zend_logo_guid — Gets the Zend guid

Description

string zend_logo_guid ( void )

This function returns the ID which can be used to display the Zend logo using the built-in image.

Return Values

Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.

Examples

Example #1 zend_logo_guid() example

<?php

echo '<img src="' . $_SERVER['PHP_SELF'] .
     '?=' . zend_logo_guid() . '" alt="Zend Logo !" />';

?>

See Also

  • php_logo_guid() - Gets the logo guid

version_compare
zend_thread_id
PHP Options/Info Functions


Returns a unique identifier for the current thread

zend_logo_guid
zend_version
PHP Options/Info Functions
PHP Manual

zend_thread_id

(PHP 5)

zend_thread_id — Returns a unique identifier for the current thread

Description

int zend_thread_id ( void )

This function returns a unique identifier for the current thread.

Return Values

Returns the thread id as an integer.

Examples

Example #1 zend_thread_id() example

<?php
$thread_id = zend_thread_id();

echo 'Current thread id is: ' . $thread_id;
?>

The above example will output something similar to:

Current thread id is: 7864

Notes

Note: This function is only available if PHP has been built with ZTS (Zend Thread Safety) support and debug mode (--enable-debug).

zend_logo_guid
zend_version
PHP Options/Info Functions


Gets the version of the current Zend engine

zend_thread_id
Memtrack
PHP Options/Info Functions
PHP Manual

zend_version

(PHP 4, PHP 5)

zend_version — Gets the version of the current Zend engine

Description

string zend_version ( void )

Returns a string containing the version of the currently running Zend Engine.

Return Values

Returns the Zend Engine version number, as a string.

Examples

Example #1 zend_version() example

<?php
echo "Zend engine version: " . zend_version();
?>

The above example will output something similar to:

Zend engine version: 2.2.0

See Also

  • phpinfo() - Outputs lots of PHP information
  • phpcredits() - Prints out the credits for PHP
  • php_logo_guid() - Gets the logo guid
  • phpversion() - Gets the current PHP version

zend_thread_id
Memtrack
PHP Options/Info Functions


Close a ZIP file archive

Zip Functions
zip_entry_close
Zip Functions
PHP Manual

zip_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_close — Close a ZIP file archive

Description

void zip_close ( resource $zip )

Closes the given ZIP file archive.

Parameters

zip

A ZIP file previously opened with zip_open().

Return Values

No value is returned.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

Zip Functions
zip_entry_close
Zip Functions


Close a directory entry

zip_close
zip_entry_compressedsize
Zip Functions
PHP Manual

zip_entry_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_close — Close a directory entry

Description

bool zip_entry_close ( resource $zip_entry )

Closes the specified directory entry.

Parameters

zip_entry

A directory entry previously opened zip_entry_open().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • zip_entry_open() - Open a directory entry for reading
  • zip_entry_read() - Read from an open directory entry

zip_close
zip_entry_compressedsize
Zip Functions


Retrieve the compressed size of a directory entry

zip_entry_close
zip_entry_compressionmethod
Zip Functions
PHP Manual

zip_entry_compressedsize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_compressedsize — Retrieve the compressed size of a directory entry

Description

int zip_entry_compressedsize ( resource $zip_entry )

Returns the compressed size of the specified directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The compressed size.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_close
zip_entry_compressionmethod
Zip Functions


Retrieve the compression method of a directory entry

zip_entry_compressedsize
zip_entry_filesize
Zip Functions
PHP Manual

zip_entry_compressionmethod

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_compressionmethod — Retrieve the compression method of a directory entry

Description

string zip_entry_compressionmethod ( resource $zip_entry )

Returns the compression method of the directory entry specified by zip_entry .

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The compression method.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_compressedsize
zip_entry_filesize
Zip Functions


Retrieve the actual file size of a directory entry

zip_entry_compressionmethod
zip_entry_name
Zip Functions
PHP Manual

zip_entry_filesize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_filesize — Retrieve the actual file size of a directory entry

Description

int zip_entry_filesize ( resource $zip_entry )

Returns the actual size of the specified directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The size of the directory entry.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_compressionmethod
zip_entry_name
Zip Functions


Retrieve the name of a directory entry

zip_entry_filesize
zip_entry_open
Zip Functions
PHP Manual

zip_entry_name

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_name — Retrieve the name of a directory entry

Description

string zip_entry_name ( resource $zip_entry )

Returns the name of the specified directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The name of the directory entry.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_filesize
zip_entry_open
Zip Functions


Open a directory entry for reading

zip_entry_name
zip_entry_read
Zip Functions
PHP Manual

zip_entry_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_open — Open a directory entry for reading

Description

bool zip_entry_open ( resource $zip , resource $zip_entry [, string $mode ] )

Opens a directory entry in a zip file for reading.

Parameters

zip

A valid resource handle returned by zip_open().

zip_entry

A directory entry returned by zip_read().

mode

Any of the modes specified in the documentation of fopen().

Note: Currently, mode is ignored and is always "rb". This is due to the fact that zip support in PHP is read only access.

Return Values

Returns TRUE on success or FALSE on failure.

Note: Unlike fopen() and other similar functions, the return value of zip_entry_open() only indicates the result of the operation and is not needed for reading or closing the directory entry.

See Also

  • zip_entry_close() - Close a directory entry
  • zip_entry_read() - Read from an open directory entry

zip_entry_name
zip_entry_read
Zip Functions


Read from an open directory entry

zip_entry_open
zip_open
Zip Functions
PHP Manual

zip_entry_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_read — Read from an open directory entry

Description

string zip_entry_read ( resource $zip_entry [, int $length ] )

Reads from an open directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

length

The number of bytes to return. If not specified, this function will attempt to read 1024 bytes.

Note: This should be the uncompressed length you wish to read.

Return Values

Returns the data read, or FALSE if the end of the file is reached.

See Also

  • zip_entry_open() - Open a directory entry for reading
  • zip_entry_close() - Close a directory entry
  • zip_entry_filesize() - Retrieve the actual file size of a directory entry

zip_entry_open
zip_open
Zip Functions


Open a ZIP file archive

zip_entry_read
zip_read
Zip Functions
PHP Manual

zip_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_open — Open a ZIP file archive

Description

mixed zip_open ( string $filename )

Opens a new zip archive for reading.

Parameters

filename

The file name of the ZIP archive to open.

Return Values

Returns a resource handle for later use with zip_read() and zip_close() or returns the number of error if filename does not exist or in case of other error.

See Also

  • zip_read() - Read next entry in a ZIP file archive
  • zip_close() - Close a ZIP file archive

zip_entry_read
zip_read
Zip Functions


Read next entry in a ZIP file archive

zip_open
Zlib
Zip Functions
PHP Manual

zip_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_read — Read next entry in a ZIP file archive

Description

mixed zip_read ( resource $zip )

Reads the next entry in a zip file archive.

Parameters

zip

A ZIP file previously opened with zip_open().

Return Values

Returns a directory entry resource for later use with the zip_entry_... functions or FALSE if there's no more entries to read or number of error in case of other error.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_close() - Close a ZIP file archive
  • zip_entry_open() - Open a directory entry for reading
  • zip_entry_read() - Read from an open directory entry

zip_open
Zlib
Zip Functions


Add a new directory

ZipArchive
ZipArchive::addFile
ZipArchive
PHP Manual

ZipArchive::addEmptyDir

(PHP 5 >= 5.2.0, PECL zip >= 1.8.0)

ZipArchive::addEmptyDir — Add a new directory

Description

bool ZipArchive::addEmptyDir ( string $dirname )

Adds an empty directory in the archive.

Parameters

dirname

The directory to add.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create a new directory in an archive

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    if($zip->addEmptyDir('newDirectory')) {
        echo 'Created a new root directory';
    } else {
        echo 'Could not create the directory';
    }
    $zip->close();
} else {
    echo 'failed';
}
?>
ZipArchive
ZipArchive::addFile
ZipArchive


Adds a file to a ZIP archive from the given path

ZipArchive::addEmptyDir
ZipArchive::addFromString
ZipArchive
PHP Manual

ZipArchive::addFile

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::addFile — Adds a file to a ZIP archive from the given path

Description

bool ZipArchive::addFile ( string $filename [, string $localname ] )

Adds a file to a ZIP archive from a given path

Parameters

filename

The path to the file to add.

localname

local name inside ZIP archive.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

This example opens a ZIP file archive test.zip and add the file /path/to/index.txt. as newname.txt.

Example #1 Open and extract

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->addFile('/path/to/index.txt', 'newname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::addEmptyDir
ZipArchive::addFromString
ZipArchive


Add a file to a ZIP archive using its contents

ZipArchive::addFile
ZipArchive::close
ZipArchive
PHP Manual

ZipArchive::addFromString

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::addFromString — Add a file to a ZIP archive using its contents

Description

bool ZipArchive::addFromString ( string $localname , string $contents )

Add a file to a ZIP archive using its contents.

Parameters

localname

The name of the entry to create.

contents

The contents to use to create the entry. It is used in a binary safe mode.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Add an entry to a new archive

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

Example #2 Add file to a directory inside an archive

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->addFromString('dir/test.txt', 'file content goes here');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::addFile
ZipArchive::close
ZipArchive


Close the active archive (opened or newly created)

ZipArchive::addFromString
ZipArchive::deleteIndex
ZipArchive
PHP Manual

ZipArchive::close

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::close — Close the active archive (opened or newly created)

Description

bool ZipArchive::close ( void )

Close opened or created archive and save changes. This method is automatically called at the end of the script.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

ZipArchive::addFromString
ZipArchive::deleteIndex
ZipArchive


delete an entry in the archive using its index

ZipArchive::close
ZipArchive::deleteName
ZipArchive
PHP Manual

ZipArchive::deleteIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::deleteIndex — delete an entry in the archive using its index

Description

bool ZipArchive::deleteIndex ( int $index )

Delete an entry in the archive using its index.

Parameters

index

Index of the entry to delete.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Delete file from archive using its index

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->deleteIndex(2);
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::close
ZipArchive::deleteName
ZipArchive


delete an entry in the archive using its name

ZipArchive::deleteIndex
ZipArchive::extractTo
ZipArchive
PHP Manual

ZipArchive::deleteName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::deleteName — delete an entry in the archive using its name

Description

bool ZipArchive::deleteName ( string $name )

Delete an entry in the archive using its name.

Parameters

name

Name of the entry to delete.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Delete file from archive using its name

<?php
$zip = new ZipArchive;
if ($zip->open('test1.zip') === TRUE) {
    $zip->deleteName('testfromfile.php');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::deleteIndex
ZipArchive::extractTo
ZipArchive


Extract the archive contents

ZipArchive::deleteName
ZipArchive::getArchiveComment
ZipArchive
PHP Manual

ZipArchive::extractTo

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::extractTo — Extract the archive contents

Description

bool ZipArchive::extractTo ( string $destination [, mixed $entries ] )

Extract the complete archive or the given files to the specified destination.

Parameters

destination

Location where to extract the files.

entries

The entries to extract. It accepts either a single entry name or an array of names.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

This example opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.

Example #1 Extract all entries

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->extractTo('/my/destination/dir/');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

Example #2 Extract only two entries

<?php
$zip = new ZipArchive;
$res = $zip->open('test_im.zip');
if ($res === TRUE) {
    $zip->extractTo('/my/destination/dir/', array('pear_item.gif', 'testfromfile.php'));
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::deleteName
ZipArchive::getArchiveComment
ZipArchive


Returns the Zip archive comment

ZipArchive::extractTo
ZipArchive::getCommentIndex
ZipArchive
PHP Manual

ZipArchive::getArchiveComment

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::getArchiveComment — Returns the Zip archive comment

Description

string ZipArchive::getArchiveComment ( void )

Returns the Zip archive comment.

Parameters

This function has no parameters.

Return Values

Returns the Zip archive comment or FALSE on failure.

Examples

Example #1 Dump an archive comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test_with_comment.zip');
if ($res === TRUE) {
    var_dump($zip->getArchiveComment());
    /* Or using the archive property */
    var_dump($zip->comment);
} else {
    echo 'failed, code:' . $res;
}
?>
ZipArchive::extractTo
ZipArchive::getCommentIndex
ZipArchive


Returns the comment of an entry using the entry index

ZipArchive::getArchiveComment
ZipArchive::getCommentName
ZipArchive
PHP Manual

ZipArchive::getCommentIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index

Description

string ZipArchive::getCommentIndex ( int $index [, int $flags ] )

Returns the comment of an entry using the entry index.

Parameters

index

Index of the entry

flags

If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original unchanged comment is returned.

Return Values

Returns the comment on success or FALSE on failure.

Examples

Example #1 Dump an entry comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
    var_dump($zip->getCommentIndex(1));
} else {
    echo 'failed, code:' . $res;
}
?>
ZipArchive::getArchiveComment
ZipArchive::getCommentName
ZipArchive


Returns the comment of an entry using the entry name

ZipArchive::getCommentIndex
ZipArchive::getFromIndex
ZipArchive
PHP Manual

ZipArchive::getCommentName

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::getCommentName — Returns the comment of an entry using the entry name

Description

string ZipArchive::getCommentName ( string $name [, int $flags ] )

Returns the comment of an entry using the entry name.

Parameters

name

Name of the entry

flags

If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original unchanged comment is returned.

Return Values

Returns the comment on success or FALSE on failure.

Examples

Example #1 Dump an entry comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
    var_dump($zip->getCommentName('test/entry1.txt'));
} else {
    echo 'failed, code:' . $res;
}
?>
ZipArchive::getCommentIndex
ZipArchive::getFromIndex
ZipArchive


Returns the entry contents using its index.

ZipArchive::getCommentName
ZipArchive::getFromName
ZipArchive
PHP Manual

ZipArchive::getFromIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.3.0)

ZipArchive::getFromIndex — Returns the entry contents using its index.

Description

mixed ZipArchive::getFromIndex ( int $index [, int $flags ] )

Returns the entry contents using its index.

Parameters

index

Index of the entry

flags

The flags to use to open the archive. the following values may be ORed to it.

  • ZIPARCHIVE::FL_UNCHANGED

  • ZIPARCHIVE::FL_COMPRESSED

Return Values

Returns the contents of the entry on success or FALSE on failure.

Examples

Example #1 Get the file contents

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    echo $zip->getFromIndex(2);
    $zip->close();
} else {
    echo 'failed';
}
?>
ZipArchive::getCommentName
ZipArchive::getFromName
ZipArchive


Returns the entry contents using its name.

ZipArchive::getFromIndex
ZipArchive::getNameIndex
ZipArchive
PHP Manual

ZipArchive::getFromName

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::getFromName — Returns the entry contents using its name.

Description

mixed ZipArchive::getFromName ( string $name [, int $flags ] )

Returns the entry contents using its name.

Parameters

name

Name of the entry

flags

The flags to use to open the archive. the following values may be ORed to it.

  • ZIPARCHIVE::FL_UNCHANGED

  • ZIPARCHIVE::FL_COMPRESSED

Return Values

Returns the contents of the entry on success or FALSE on failure.

Examples

Example #1 Get the file contents

<?php
$zip = new ZipArchive;
if ($zip->open('test1.zip') === TRUE) {
    echo $zip->getFromName('testfromfile.php');
    $zip->close();
} else {
    echo 'failed';
}
?>

Example #2 Convert an image from a zip entry

<?php
$z = new ZipArchive();
if ($z->open(dirname(__FILE__) . '/test_im.zip')) {
    $im_string = $z->getFromName("pear_item.gif");
    $im = imagecreatefromstring($im_string);
    imagepng($im, 'b.png');
}
?>
ZipArchive::getFromIndex
ZipArchive::getNameIndex
ZipArchive


Returns the name of an entry using its index

ZipArchive::getFromName
ZipArchive::GetStatusString
ZipArchive
PHP Manual

ZipArchive::getNameIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::getNameIndex — Returns the name of an entry using its index

Description

string ZipArchive::getNameIndex ( int $index )

Returns the name of an entry using its index.

Parameters

index

Index of the entry.

Return Values

Returns the name on success or FALSE on failure.

ZipArchive::getFromName
ZipArchive::GetStatusString
ZipArchive


Returns the status error message, system and/or zip messages.

ZipArchive::getNameIndex
ZipArchive::getStream
ZipArchive
PHP Manual

ZipArchive::GetStatusString

(PHP 5 >= 5.2.7)

ZipArchive::GetStatusString — Returns the status error message, system and/or zip messages.

Description

string ZipArchive::getStatusString ( void )

Returns the status error message, system and/or zip messages.

Parameters

This function has no parameters.

Return Values

Returns a file pointer (resource) on success or FALSE on failure.

ZipArchive::getNameIndex
ZipArchive::getStream
ZipArchive


Get a file handler to the entry defined by its name (read only).

ZipArchive::GetStatusString
ZipArchive::locateName
ZipArchive
PHP Manual

ZipArchive::getStream

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::getStream — Get a file handler to the entry defined by its name (read only).

Description

resource ZipArchive::getStream ( string $name )

Get a file handler to the entry defined by its name. For now it only supports read operations.

Parameters

name

The name of the entry to use.

Return Values

Returns a file pointer (resource) on success or FALSE on failure.

Examples

Example #1 Get the entry contents with fread() and store it

<?php
$content = '';
$z = new ZipArchive();
if ($z->open('test.zip')) {
    $fp = $z->getStream('test');
    if(!$fp) exit("failed\n");

    while (!feof($fp)) {
        $contents .= fread($fp, 2);
    }

    fclose($fp);
    file_put_contents('t',$contents);
    echo "done.\n";
}
?>

Example #2 Same as the previous example but with fopen() and the zip stream wrapper

<?php
$fp = fopen('zip://' . dirname(__FILE__) . '/test.zip#test', 'r');
if (!$fp) {
    exit("cannot open\n");
}
while (!feof($fp)) {
    $contents .= fread($fp, 2);
    echo "$contents\n";
}
fclose($fp);
echo "done.\n";
?>

Example #3 Stream wrapper and image, can be used with the xml function as well

<?php
$im = imagecreatefromgif('zip://' . dirname(__FILE__) . '/test_im.zip#pear_item.gif');
imagepng($im, 'a.png');
?>
ZipArchive::GetStatusString
ZipArchive::locateName
ZipArchive


Returns the index of the entry in the archive

ZipArchive::getStream
ZipArchive::open
ZipArchive
PHP Manual

ZipArchive::locateName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::locateName — Returns the index of the entry in the archive

Description

mixed ZipArchive::locateName ( string $name [, int $flags ] )

Locates an entry using its name.

Parameters

name

The name of the entry to look up

flags

The flags are specified by ORing the following values, or 0 for none of them.

  • ZIPARCHIVE::FL_NOCASE

  • ZIPARCHIVE::FL_NODIR

Return Values

Returns the index of the entry on success or FALSE on failure.

Examples

Example #1 Create an archive and then use it with ZipArchive::locateName()

<?php
$file = 'testlocate.zip';

$zip = new ZipArchive;
if ($zip->open($file, ZIPARCHIVE::CREATE) !== TRUE) {
    exit('failed');
}

$zip->addFromString('entry1.txt', 'entry #1');
$zip->addFromString('entry2.txt', 'entry #2');
$zip->addFromString('dir/entry2d.txt', 'entry #2');

if (!$zip->status == ZIPARCHIVE::ER_OK) {
    echo "failed to write zip\n";
}
$zip->close();

if ($zip->open($file) !== TRUE) {
    exit('failed');
}

echo $zip->locateName('entry1.txt') . "\n";
echo $zip->locateName('eNtry2.txt') . "\n";
echo $zip->locateName('eNtry2.txt', ZIPARCHIVE::FL_NOCASE) . "\n";
echo $zip->locateName('enTRy2d.txt', ZIPARCHIVE::FL_NOCASE|ZIPARCHIVE::FL_NODIR) . "\n";
$zip->close();

?>

The above example will output:

0

1
2
ZipArchive::getStream
ZipArchive::open
ZipArchive


Open a ZIP file archive

ZipArchive::locateName
ZipArchive::renameIndex
ZipArchive
PHP Manual

ZipArchive::open

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::open — Open a ZIP file archive

Description

mixed ZipArchive::open ( string $filename [, int $flags ] )

Opens a new zip archive for reading, writing or modifying.

Parameters

filename

The file name of the ZIP archive to open.

flags

The mode to use to open the archive.

  • ZIPARCHIVE::OVERWRITE

  • ZIPARCHIVE::CREATE

  • ZIPARCHIVE::EXCL

  • ZIPARCHIVE::CHECKCONS

Return Values

Error codes

Returns TRUE on success or the error code.

  • ZIPARCHIVE::ER_EXISTS

  • ZIPARCHIVE::ER_INCONS

  • ZIPARCHIVE::ER_INVAL

  • ZIPARCHIVE::ER_MEMORY

  • ZIPARCHIVE::ER_NOENT

  • ZIPARCHIVE::ER_NOZIP

  • ZIPARCHIVE::ER_OPEN

  • ZIPARCHIVE::ER_READ

  • ZIPARCHIVE::ER_SEEK

Examples

This example opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.

Example #1 Open and extract

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    echo 'ok';
    $zip->extractTo('test');
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

Example #2 Create an archive

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->addFile('data.txt', 'entryname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::locateName
ZipArchive::renameIndex
ZipArchive


Renames an entry defined by its index

ZipArchive::open
ZipArchive::renameName
ZipArchive
PHP Manual

ZipArchive::renameIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::renameIndex — Renames an entry defined by its index

Description

bool ZipArchive::renameIndex ( int $index , string $newname )

Renames an entry defined by its index.

Parameters

index

Index of the entry to rename.

newname

New name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Rename one entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->renameIndex(2,'newname.txt');
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>
ZipArchive::open
ZipArchive::renameName
ZipArchive


Renames an entry defined by its name

ZipArchive::renameIndex
ZipArchive::setArchiveComment
ZipArchive
PHP Manual

ZipArchive::renameName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::renameName — Renames an entry defined by its name

Description

bool ZipArchive::renameName ( string $name , string $newname )

Renames an entry defined by its name.

Parameters

name

Name of the entry to rename.

newname

New name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Rename one entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->renameName('currentname.txt','newname.txt');
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>
ZipArchive::renameIndex
ZipArchive::setArchiveComment
ZipArchive


Set the comment of a ZIP archive

ZipArchive::renameName
ZipArchive::setCommentIndex
ZipArchive
PHP Manual

ZipArchive::setArchiveComment

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::setArchiveComment — Set the comment of a ZIP archive

Description

mixed ZipArchive::setArchiveComment ( string $comment )

Set the comment of a ZIP archive.

Parameters

comment

The contents of the comment.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create an archive and set a comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->setArchiveComment('new archive comment');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::renameName
ZipArchive::setCommentIndex
ZipArchive


Set the comment of an entry defined by its index

ZipArchive::setArchiveComment
ZipArchive::setCommentName
ZipArchive
PHP Manual

ZipArchive::setCommentIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::setCommentIndex — Set the comment of an entry defined by its index

Description

mixed ZipArchive::setCommentIndex ( int $index , string $comment )

Set the comment of an entry defined by its index.

Parameters

index

Index of the entry.

comment

The contents of the comment.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Open an archive and set a comment for an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->setCommentIndex(2, 'new entry comment');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::setArchiveComment
ZipArchive::setCommentName
ZipArchive


Set the comment of an entry defined by its name

ZipArchive::setCommentIndex
ZipArchive::statIndex
ZipArchive
PHP Manual

ZipArchive::setCommentName

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::setCommentName — Set the comment of an entry defined by its name

Description

mixed ZipArchive::setCommentName ( string $name , string $comment )

Set the comment of an entry defined by its name.

Parameters

name

Name of the entry.

comment

The contents of the comment.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Open an archive and set a comment for an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->setCommentName('entry1.txt', 'new entry comment');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::setCommentIndex
ZipArchive::statIndex
ZipArchive


Get the details of an entry defined by its index.

ZipArchive::setCommentName
ZipArchive::statName
ZipArchive
PHP Manual

ZipArchive::statIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::statIndex — Get the details of an entry defined by its index.

Description

mixed ZipArchive::statIndex ( int $index [, int $flags ] )

The function obtains information about the entry defined by its index.

Parameters

index

Index of the entry

flags

ZIPARCHIVE::FL_UNCHANGED may be ORed to it to request information about the original file in the archive, ignoring any changes made.

Return Values

Returns an array containing the entry details or FALSE on failure.

Examples

Example #1 Dump the stat info of an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    print_r($zip->statIndex(3));
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

The above example will output something similar to:

Array
(
    [name] => foobar/baz
    [index] => 3
    [crc] => 499465816
    [size] => 27
    [mtime] => 1123164748
    [comp_size] => 24
    [comp_method] => 8
)
ZipArchive::setCommentName
ZipArchive::statName
ZipArchive


Get the details of an entry defined by its name.

ZipArchive::statIndex
ZipArchive::unchangeAll
ZipArchive
PHP Manual

ZipArchive::statName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::statName — Get the details of an entry defined by its name.

Description

mixed ZipArchive::statName ( name $name [, int $flags ] )

The function obtains information about the entry defined by its name.

Parameters

name

Name of the entry

flags

The flags argument specifies how the name lookup should be done. Also, ZIPARCHIVE::FL_UNCHANGED may be ORed to it to request information about the original file in the archive, ignoring any changes made.

  • ZIPARCHIVE::FL_NOCASE

  • ZIPARCHIVE::FL_NODIR

  • ZIPARCHIVE::FL_UNCHANGED

Return Values

Returns an array containing the entry details or FALSE on failure.

Examples

Example #1 Dump the stat info of an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    print_r($zip->statName('foobar/baz'));
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

The above example will output something similar to:

Array
(
    [name] => foobar/baz
    [index] => 3
    [crc] => 499465816
    [size] => 27
    [mtime] => 1123164748
    [comp_size] => 24
    [comp_method] => 8
)
ZipArchive::statIndex
ZipArchive::unchangeAll
ZipArchive


Undo all changes done in the archive.

ZipArchive::statName
ZipArchive::unchangeArchive
ZipArchive
PHP Manual

ZipArchive::unchangeAll

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeAll — Undo all changes done in the archive.

Description

mixed ZipArchive::unchangeAll ( void )

Undo all changes done in the archive.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

ZipArchive::statName
ZipArchive::unchangeArchive
ZipArchive


Revert all global changes done in the archive.

ZipArchive::unchangeAll
ZipArchive::unchangeIndex
ZipArchive
PHP Manual

ZipArchive::unchangeArchive

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeArchive — Revert all global changes done in the archive.

Description

mixed ZipArchive::unchangeArchive ( void )

Revert all global changes to the archive archive. For now, this only reverts archive comment changes.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

ZipArchive::unchangeAll
ZipArchive::unchangeIndex
ZipArchive


Revert all changes done to an entry at the given index.

ZipArchive::unchangeArchive
ZipArchive::unchangeName
ZipArchive
PHP Manual

ZipArchive::unchangeIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index.

Description

mixed ZipArchive::unchangeIndex ( int $index )

Revert all changes done to an entry at the given index.

Parameters

index

Index of the entry.

Return Values

Returns TRUE on success or FALSE on failure.

ZipArchive::unchangeArchive
ZipArchive::unchangeName
ZipArchive


Revert all changes done to an entry with the given name.

ZipArchive::unchangeIndex
Zip Functions
ZipArchive
PHP Manual

ZipArchive::unchangeName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::unchangeName — Revert all changes done to an entry with the given name.

Description

mixed ZipArchive::unchangeName ( string $name )

Revert all changes done to an entry.

Parameters

name

Name of the entry.

Return Values

Returns TRUE on success or FALSE on failure.

ZipArchive::unchangeIndex
Zip Functions
ZipArchive


Returns the coding type used for output compression

readgzfile
Credit Card Processing
Zlib Functions
PHP Manual

zlib_get_coding_type

(PHP 4 >= 4.3.2, PHP 5)

zlib_get_coding_type — Returns the coding type used for output compression

Description

string zlib_get_coding_type ( void )

Returns the coding type used for output compression.

Return Values

Possible return values are gzip, deflate, or FALSE.

See Also

  • The zlib.output_compression directive

readgzfile
Credit Card Processing
Zlib Functions


Anonymous functions

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

Example #1 Anonymous function example

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
?>

Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon:

Example #2 Anonymous function variable assignment example

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:

Example #3 Closures and scoping

<?php
// A basic shopping cart which contains a list of added products
// and the quantity of each product. Includes a method which
// calculates the total price of the items in the cart using a
// closure as a callback.
class Cart
{
    const PRICE_BUTTER  = 1.00;
    const PRICE_MILK    = 3.00;
    const PRICE_EGGS    = 6.95;

    protected   $products = array();

    public function add($product, $quantity)
    {
        $this->products[$product] = $quantity;
    }

    public function getQuantity($product)
    {
        return isset($this->products[$product]) ? $this->products[$product] :
               FALSE;
    }

    public function getTotal($tax)
    {
        $total = 0.00;

        $callback =
            function ($quantity, $product) use ($tax, &$total)
            {
                $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                    strtoupper($product));
                $total += ($pricePerItem * $quantity) * ($tax + 1.0);
            };

        array_walk($this->products, $callback);
        return round($total, 2);;
    }
}

$my_cart = new Cart;

// Add some items to the cart
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);

// Print the total with a 5% sales tax.
print $my_cart->getTotal(0.05) . "\n";
// The result is 54.29
?>

Anonymous functions are currently implemented using the Closure class. This is an implementation detail and should not be relied upon.

Note: Anonymous functions are available since PHP 5.3.0.

Note: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure.

Internal (built-in) functions
Classes and Objects
Functions


Function arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions.

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported, see also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

Example #1 Passing arrays to functions

<?php
function takes_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>

Making arguments be passed by reference

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:

Example #2 Passing function parameters by reference

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

Default argument values

A function may define C++-style default values for scalar arguments as follows:

Example #3 Use of default parameters in functions

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

The above example will output:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

PHP also allows the use of arrays and the special type NULL as default values, for example:

Example #4 Using non-scalar types as default values

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
    $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
    return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet:

Example #5 Incorrect usage of default function arguments

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

echo makeyogurt("raspberry");   // won't work as expected
?>

The above example will output:

Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Making a bowl of raspberry .

Now, compare the above with this:

Example #6 Correct usage of default function arguments

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

echo makeyogurt("raspberry");   // works as expected
?>

The above example will output:

Making a bowl of acidophilus raspberry.

Note: As of PHP 5, default values may be passed by reference.

Variable-length argument lists

PHP 4 and above has support for variable-length argument lists in
user-defined functions. This is really quite easy, using the
func_num_args(),
func_get_arg(), and
func_get_args() functions.

No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal.

User-defined functions
Returning values
Functions


Internal (built-in) functions

PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use mysql_connect(), PHP must be compiled with MySQL support. There are many core functions that are included in every version of PHP, such as the string and variable functions. A call to phpinfo() or get_loaded_extensions() will show which extensions are loaded into PHP. Also note that many extensions are enabled by default and that the PHP manual is split up by extension. See the configuration, installation, and individual extension chapters, for information on how to set up PHP.

Reading and understanding a function's prototype is explained within the manual section titled how to read a function definition. It's important to realize what a function returns or if a function works directly on a passed in value. For example, str_replace() will return the modified string while usort() works on the actual passed in variable itself. Each manual page also has specific information for each function like information on function parameters, behavior changes, return values for both success and failure, and availability information. Knowing these important (yet often subtle) differences is crucial for writing correct PHP code.

Note: If the parameters given to a function are not what it expects, such as passing an array where a string is expected, the return value of the function is undefined. In this case it will likely return NULL but this is just a convention, and cannot be relied upon.

See also function_exists(), the function reference, get_extension_funcs(), and dl().

Variable functions
Anonymous functions
Functions


Returning values

Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return() for more information.

Note: If the return() is omitted the value NULL will be returned.

Example #1 Use of return()

<?php
function square($num)
{
    return $num * $num;
}
echo square(4);   // outputs '16'.
?>

A function can not return multiple values, but similar results can be obtained by returning an array.

Example #2 Returning an array to get multiple values

<?php
function small_numbers()
{
    return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>

To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable:

Example #3 Returning a reference from a function

<?php
function &returns_reference()
{
    return $someref;
}

$newref =& returns_reference();
?>

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

Function arguments
Variable functions
Functions


User-defined functions

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

Example #1 Pseudo code to demonstrate function uses

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

Any valid PHP code may appear inside a function, even other functions and class definitions.

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Tip

See also the Userland Naming Guide.

Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

Example #2 Conditional functions

<?php

$makefoo = true;

/* We can't call foo() from here
   since it doesn't exist yet,
   but we can call bar() */

bar();

if ($makefoo) {
  function foo()
  {
    echo "I don't exist until program execution reaches me.\n";
  }
}

/* Now we can safely call foo()
   since $makefoo evaluated to true */

if ($makefoo) foo();

function bar()
{
  echo "I exist immediately upon program start.\n";
}

?>

Example #3 Functions within functions

<?php
function foo()
{
  function bar()
  {
    echo "I don't exist until foo() is called.\n";
  }
}

/* We can't call bar() yet
   since it doesn't exist. */

foo();

/* Now we can call bar(),
   foo()'s processesing has
   made it accessible. */

bar();

?>

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

Note: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

Both variable number of arguments and default arguments are supported in functions. See also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

It is possible to call recursive functions in PHP. However avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script.

Example #4 Recursive functions

<?php
function recursion($a)
{
    if ($a < 20) {
        echo "$a\n";
        recursion($a + 1);
    }
}
?>

Functions
Function arguments
Functions


Variable functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

Example #1 Variable function example

<?php
function foo() {
    echo "In foo()<br />\n";
}

function bar($arg = '')
{
    echo "In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo
function echoit($string)
{
    echo $string;
}

$func = 'foo';
$func();        // This calls foo()

$func = 'bar';
$func('test');  // This calls bar()

$func = 'echoit';
$func('test');  // This calls echoit()
?>

An object method can also be called with the variable functions syntax.

Example #2 Variable method example

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

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

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

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

Returning values
Internal (built-in) functions
Functions


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GEOIP_COUNTRY_EDITION (integer)
GEOIP_REGION_EDITION_REV0 (integer)
GEOIP_CITY_EDITION_REV0 (integer)
GEOIP_ORG_EDITION (integer)
GEOIP_ISP_EDITION (integer)
GEOIP_CITY_EDITION_REV1 (integer)
GEOIP_REGION_EDITION_REV1 (integer)
GEOIP_PROXY_EDITION (integer)
GEOIP_ASNUM_EDITION (integer)
GEOIP_NETSPEED_EDITION (integer)
GEOIP_DOMAIN_EDITION (integer)

The following constants are for net speed:

GEOIP_UNKNOWN_SPEED (integer)
GEOIP_DIALUP_SPEED (integer)
GEOIP_CABLEDSL_SPEED (integer)
GEOIP_CORPORATE_SPEED (integer)
Resource Types
GeoIP Functions
GeoIP


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/geoip.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

This extension requires the GeoIP C library version 1.4.0 or higher to be installed. You can grab the latest version from » http://www.maxmind.com/app/c and compile it yourself.

By default, you will only have access to the Free GeoIP Country or GeoLite City databases. While this module can work with other types of database, you must buy a commercial license from » Maxmind.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
GeoIP


Predefined Constants

This extension has no constants defined.

Resource Types
Gettext Functions
Gettext


Installation

To include GNU gettext support in your PHP build you must add the option --with-gettext[=DIR] where DIR is the gettext install directory, defaults to /usr/local.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To use these functions you must download and install the GNU gettext package from » http://www.gnu.org/software/gettext/gettext.html

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Gettext


Getting Started

  • Introduction
    • What is PHP?
    • What can PHP do?
  • A simple tutorial
    • What do I need?
    • Your first PHP-enabled page
    • Something Useful
    • Dealing with Forms
    • Using old code with new versions of PHP
    • What's next?
Preface
Introduction


Adds new image to Gmagick object image list

Gmagick
Gmagick::addnoiseimage
Gmagick
PHP Manual

Gmagick::addimage

(PECL gmagick >= Unknown)

Gmagick::addimage — Adds new image to Gmagick object image list

Description

public void Gmagick::addimage ( Gmagick $Gmagick )

Adds new image to Gmagick object from the current position of the source object. After the operation iterator position is moved at the end of the list.

Parameters

source

The source Gmagick object

Return Values

The Gmagick object with image added

Errors/Exceptions

Throws an GmagickException on error.

Gmagick
Gmagick::addnoiseimage
Gmagick


Adds random noise to the image

Gmagick::addimage
Gmagick::annotateimage
Gmagick
PHP Manual

Gmagick::addnoiseimage

(PECL gmagick >= Unknown)

Gmagick::addnoiseimage — Adds random noise to the image

Description

public void Gmagick::addnoiseimage ( int $NOISE )

Adds random noise to the image.

Parameters

noise_type

The type of the noise. Refer to this list of noise constants.

Return Values

The Gmagick object with noise added.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::addimage
Gmagick::annotateimage
Gmagick


Annotates an image with text

Gmagick::addnoiseimage
Gmagick::blurimage
Gmagick
PHP Manual

Gmagick::annotateimage

(PECL gmagick >= Unknown)

Gmagick::annotateimage — Annotates an image with text

Description

public void Gmagick::annotateimage ( GmagickDraw $GmagickDraw , int $x , int $y , float $angle , string $text )

Annotates an image with text.

Parameters

GmagickDraw

The GmagickDraw object that contains settings for drawing the text

x

Horizontal offset in pixels to the left of text

y

Vertical offset in pixels to the baseline of text

angle

The angle at which to write the text

text

The string to draw

Return Values

The Gmagick object with annotation made.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::addnoiseimage
Gmagick::blurimage
Gmagick


Adds blur filter to image

Gmagick::annotateimage
Gmagick::borderimage
Gmagick
PHP Manual

Gmagick::blurimage

(PECL gmagick >= Unknown)

Gmagick::blurimage — Adds blur filter to image

Description

public void Gmagick::blurimage ( float $radius , float $sigma )

Adds blur filter to image.

Parameters

radius

Blur radius

sigma

Standard deviation

Return Values

The blurred Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::annotateimage
Gmagick::borderimage
Gmagick


Surrounds the image with a border

Gmagick::blurimage
Gmagick::charcoalimage
Gmagick
PHP Manual

Gmagick::borderimage

(PECL gmagick >= Unknown)

Gmagick::borderimage — Surrounds the image with a border

Description

public void Gmagick::borderimage ( GmagickPixel $color , int $width , int $height )

Surrounds the image with a border of the color defined by the bordercolor GmagickPixel object or a color string.

Parameters

color

GmagickPixel object or a string containing the border color

width

Border width

height

Border height

Return Values

The Gmagick object with border defined

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::blurimage
Gmagick::charcoalimage
Gmagick


Simulates a charcoal drawing

Gmagick::borderimage
Gmagick::chopimage
Gmagick
PHP Manual

Gmagick::charcoalimage

(PECL gmagick >= Unknown)

Gmagick::charcoalimage — Simulates a charcoal drawing

Description

public void Gmagick::charcoalimage ( float $radius , float $sigma )

Simulates a charcoal drawing.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels

Return Values

The Gmagick object with charcoal simulation

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::borderimage
Gmagick::chopimage
Gmagick


Removes a region of an image and trims

Gmagick::charcoalimage
Gmagick::clear
Gmagick
PHP Manual

Gmagick::chopimage

(PECL gmagick >= Unknown)

Gmagick::chopimage — Removes a region of an image and trims

Description

public void Gmagick::chopimage ( int $width , int $height , int $x , int $y )

Removes a region of an image and collapses the image to occupy the removed portion.

Parameters

width

Width of the chopped area

height

Height of the chopped area

x

X origo of the chopped area

y

Y origo of the chopped area

Return Values

The chopped Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::charcoalimage
Gmagick::clear
Gmagick


Clears all resources associated to Gmagick object

Gmagick::chopimage
Gmagick::commentimage
Gmagick
PHP Manual

Gmagick::clear

(PECL gmagick >= Unknown)

Gmagick::clear — Clears all resources associated to Gmagick object

Description

public void Gmagick::clear ( void )

Clears all resources associated to Gmagick object

Parameters

This function has no parameters.

Return Values

The cleared Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::chopimage
Gmagick::commentimage
Gmagick


Adds a comment to your image

Gmagick::clear
Gmagick::compositeimage
Gmagick
PHP Manual

Gmagick::commentimage

(PECL gmagick >= Unknown)

Gmagick::commentimage — Adds a comment to your image

Description

public void Gmagick::commentimage ( string $comment )

Adds a comment to your image.

Parameters

comment

The comment to add

Return Values

The Gmagick object with comment added.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::clear
Gmagick::compositeimage
Gmagick


Composite one image onto another

Gmagick::commentimage
Gmagick::__construct
Gmagick
PHP Manual

Gmagick::compositeimage

(PECL gmagick >= Unknown)

Gmagick::compositeimage — Composite one image onto another

Description

public void Gmagick::compositeimage ( Gmagick $source , int $COMPOSE , int $x , int $y )

Composite one image onto another at the specified offset.

Parameters

source

Gmagick object which holds the composite image

compose

Composite operator.

x

The column offset of the composited image

y

The row offset of the composited image

Return Values

The Gmagick object with compositions.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::commentimage
Gmagick::__construct
Gmagick


Runtime Configuration

This extension has no configuration directives defined in php.ini.

Installation
Predefined Constants
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Colortype constants
Gmagick::COLOR_BLACK (integer)
Black
Gmagick::COLOR_BLUE (integer)
Blue
Gmagick::COLOR_CYAN (integer)
Cyan
Gmagick::COLOR_GREEN (integer)
Green
Gmagick::COLOR_RED (integer)
Red
Gmagick::COLOR_YELLOW (integer)
Yellow
Gmagick::COLOR_MAGENTA (integer)
Magenta
Gmagick::COLOR_OPACITY (integer)
Opacity
Gmagick::COLOR_ALPHA (integer)
Alpha
Gmagick::COLOR_FUZZ (integer)
Fuzz
Composite Operator Constants
Gmagick::COMPOSITE_DEFAULT (integer)
The default composite operator
Gmagick::COMPOSITE_UNDEFINED (integer)
Undefined composite operator
Gmagick::COMPOSITE_NO (integer)
No composite operator defined
Gmagick::COMPOSITE_ADD (integer)
The result of image + image
Gmagick::COMPOSITE_ATOP (integer)
The result is the same shape as image, with composite image obscuring image where the image shapes overlap
Gmagick::COMPOSITE_BLEND (integer)
Blends the image
Gmagick::COMPOSITE_BUMPMAP (integer)
The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
Gmagick::COMPOSITE_CLEAR (integer)
Makes the target image transparent
Gmagick::COMPOSITE_COLORBURN (integer)
Darkens the destination image to reflect the source image
Gmagick::COMPOSITE_COLORDODGE (integer)
Brightens the destination image to reflect the source image
Gmagick::COMPOSITE_COLORIZE (integer)
Colorizes the target image using the composite image
Gmagick::COMPOSITE_COPYBLACK (integer)
Copies black from the source to target
Gmagick::COMPOSITE_COPYBLUE (integer)
Copies blue from the source to target
Gmagick::COMPOSITE_COPY (integer)
Copies the source image on the target image
Gmagick::COMPOSITE_COPYCYAN (integer)
Copies cyan from the source to target
Gmagick::COMPOSITE_COPYGREEN (integer)
Copies green from the source to target
Gmagick::COMPOSITE_COPYMAGENTA (integer)
Copies magenta from the source to target
Gmagick::COMPOSITE_COPYOPACITY (integer)
Copies opacity from the source to target
Gmagick::COMPOSITE_COPYRED (integer)
Copies red from the source to target
Gmagick::COMPOSITE_COPYYELLOW (integer)
Copies yellow from the source to target
Gmagick::COMPOSITE_DARKEN (integer)
Darkens the target image
Gmagick::COMPOSITE_DSTATOP (integer)
The part of the destination lying inside of the source is composited over the source and replaces the destination
Gmagick::COMPOSITE_DST (integer)
The target is left untouched
Gmagick::COMPOSITE_DSTIN (integer)
The parts inside the source replace the target
Gmagick::COMPOSITE_DSTOUT (integer)
The parts outside the source replace the target
Gmagick::COMPOSITE_DSTOVER (integer)
Target replaces the source
Gmagick::COMPOSITE_DIFFERENCE (integer)
Subtracts the darker of the two constituent colors from the lighter
Gmagick::COMPOSITE_DISPLACE (integer)
Shifts target image pixels as defined by the source
Gmagick::COMPOSITE_DISSOLVE (integer)
Dissolves the source in to the target
Gmagick::COMPOSITE_EXCLUSION (integer)
Produces an effect similar to that of Gmagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
Gmagick::COMPOSITE_HARDLIGHT (integer)
Multiplies or screens the colors, dependent on the source color value
Gmagick::COMPOSITE_HUE (integer)
Modifies the hue of the target as defined by source
Gmagick::COMPOSITE_IN (integer)
Composites source into the target
Gmagick::COMPOSITE_LIGHTEN (integer)
Lightens the target as defined by source
Gmagick::COMPOSITE_LUMINIZE (integer)
Luminizes the target as defined by source
Gmagick::COMPOSITE_MINUS (integer)
Substracts the source from the target
Gmagick::COMPOSITE_MODULATE (integer)
Modulates the target brightness, saturation and hue as defined by source
Gmagick::COMPOSITE_MULTIPLY (integer)
Multiplies the target to the source
Gmagick::COMPOSITE_OUT (integer)
Composites outer parts of the source on the target
Gmagick::COMPOSITE_OVER (integer)
Composites source over the target
Gmagick::COMPOSITE_OVERLAY (integer)
Overlays the source on the target
Gmagick::COMPOSITE_PLUS (integer)
Adds the source to the target
Gmagick::COMPOSITE_REPLACE (integer)
Replaces the target with the source
Gmagick::COMPOSITE_SATURATE (integer)
Saturates the target as defined by the source
Gmagick::COMPOSITE_SCREEN (integer)
The source and destination are complemented and then multiplied and then replace the destination
Gmagick::COMPOSITE_SOFTLIGHT (integer)
Darkens or lightens the colors, dependent on the source
Gmagick::COMPOSITE_SRCATOP (integer)
The part of the source lying inside of the destination is composited onto the destination
Gmagick::COMPOSITE_SRC (integer)
The source is copied to the destination
Gmagick::COMPOSITE_SRCIN (integer)
The part of the source lying inside of the destination replaces the destination
Gmagick::COMPOSITE_SRCOUT (integer)
The part of the source lying outside of the destination replaces the destination
Gmagick::COMPOSITE_SRCOVER (integer)
The source replaces the destination
Gmagick::COMPOSITE_SUBTRACT (integer)
Subtract the colors in the source image from the destination image
Gmagick::COMPOSITE_THRESHOLD (integer)
The source is composited on the target as defined by source threshold
Gmagick::COMPOSITE_XOR (integer)
The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source
Montage Mode constants
Gmagick::MONTAGEMODE_FRAME (integer)
Gmagick::MONTAGEMODE_UNFRAME (integer)
Gmagick::MONTAGEMODE_CONCATENATE (integer)
Style constants
Gmagick::STYLE_NORMAL (integer)
Gmagick::STYLE_ITALIC (integer)
Gmagick::STYLE_OBLIQUE (integer)
Gmagick::STYLE_ANY (integer)
Filter constants
Gmagick::FILTER_UNDEFINED (integer)
Gmagick::FILTER_POINT (integer)
Gmagick::FILTER_BOX (integer)
Gmagick::FILTER_TRIANGLE (integer)
Gmagick::FILTER_HERMITE (integer)
Gmagick::FILTER_HANNING (integer)
Gmagick::FILTER_HAMMING (integer)
Gmagick::FILTER_BLACKMAN (integer)
Gmagick::FILTER_GAUSSIAN (integer)
Gmagick::FILTER_QUADRATIC (integer)
Gmagick::FILTER_CUBIC (integer)
Gmagick::FILTER_CATROM (integer)
Gmagick::FILTER_MITCHELL (integer)
Gmagick::FILTER_LANCZOS (integer)
Gmagick::FILTER_BESSEL (integer)
Gmagick::FILTER_SINC (integer)
Image type constants
Gmagick::IMGTYPE_UNDEFINED (integer)
Gmagick::IMGTYPE_BILEVEL (integer)
Gmagick::IMGTYPE_GRAYSCALE (integer)
Gmagick::IMGTYPE_GRAYSCALEMATTE (integer)
Gmagick::IMGTYPE_PALETTE (integer)
Gmagick::IMGTYPE_PALETTEMATTE (integer)
Gmagick::IMGTYPE_TRUECOLOR (integer)
Gmagick::IMGTYPE_TRUECOLORMATTE (integer)
Gmagick::IMGTYPE_COLORSEPARATION (integer)
Gmagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
Gmagick::IMGTYPE_OPTIMIZE (integer)
Resolution constants
Gmagick::RESOLUTION_UNDEFINED (integer)
Gmagick::RESOLUTION_PIXELSPERINCH (integer)
Gmagick::RESOLUTION_PIXELSPERCENTIMETER (integer)
Compression constants
Gmagick::COMPRESSION_UNDEFINED (integer)
Gmagick::COMPRESSION_NO (integer)
Gmagick::COMPRESSION_BZIP (integer)
Gmagick::COMPRESSION_FAX (integer)
Gmagick::COMPRESSION_GROUP4 (integer)
Gmagick::COMPRESSION_JPEG (integer)
Gmagick::COMPRESSION_JPEG2000 (integer)
Gmagick::COMPRESSION_LOSSLESSJPEG (integer)
Gmagick::COMPRESSION_LZW (integer)
Gmagick::COMPRESSION_RLE (integer)
Gmagick::COMPRESSION_ZIP (integer)
Paint constants
Gmagick::PAINT_POINT (integer)
Gmagick::PAINT_REPLACE (integer)
Gmagick::PAINT_FLOODFILL (integer)
Gmagick::PAINT_FILLTOBORDER (integer)
Gmagick::PAINT_RESET (integer)
Gravity constants
Gmagick::GRAVITY_NORTHWEST (integer)
Gmagick::GRAVITY_NORTH (integer)
Gmagick::GRAVITY_NORTHEAST (integer)
Gmagick::GRAVITY_WEST (integer)
Gmagick::GRAVITY_CENTER (integer)
Gmagick::GRAVITY_EAST (integer)
Gmagick::GRAVITY_SOUTHWEST (integer)
Gmagick::GRAVITY_SOUTH (integer)
Gmagick::GRAVITY_SOUTHEAST (integer)
Stretch constants
Gmagick::STRETCH_NORMAL (integer)
Gmagick::STRETCH_ULTRACONDENSED (integer)
Gmagick::STRETCH_CONDENSED (integer)
Gmagick::STRETCH_SEMICONDENSED (integer)
Gmagick::STRETCH_SEMIEXPANDED (integer)
Gmagick::STRETCH_EXPANDED (integer)
Gmagick::STRETCH_EXTRAEXPANDED (integer)
Gmagick::STRETCH_ULTRAEXPANDED (integer)
Gmagick::STRETCH_ANY (integer)
Align constants
Gmagick::ALIGN_UNDEFINED (integer)
Gmagick::ALIGN_LEFT (integer)
Gmagick::ALIGN_CENTER (integer)
Gmagick::ALIGN_RIGHT (integer)
Decoration constants
Gmagick::DECORATION_NO (integer)
Gmagick::DECORATION_UNDERLINE (integer)
Gmagick::DECORATION_OVERLINE (integer)
Gmagick::DECORATION_LINETROUGH (integer)
Noise constants
Gmagick::NOISE_UNIFORM (integer)
Gmagick::NOISE_GAUSSIAN (integer)
Gmagick::NOISE_MULTIPLICATIVEGAUSSIAN (integer)
Gmagick::NOISE_IMPULSE (integer)
Gmagick::NOISE_LAPLACIAN (integer)
Gmagick::NOISE_POISSON (integer)
Channel constants
Gmagick::CHANNEL_UNDEFINED (integer)
Gmagick::CHANNEL_RED (integer)
Gmagick::CHANNEL_GRAY (integer)
Gmagick::CHANNEL_CYAN (integer)
Gmagick::CHANNEL_GREEN (integer)
Gmagick::CHANNEL_MAGENTA (integer)
Gmagick::CHANNEL_BLUE (integer)
Gmagick::CHANNEL_YELLOW (integer)
Gmagick::CHANNEL_ALPHA (integer)
Gmagick::CHANNEL_OPACITY (integer)
Gmagick::CHANNEL_MATTE (integer)
Gmagick::CHANNEL_BLACK (integer)
Gmagick::CHANNEL_INDEX (integer)
Gmagick::CHANNEL_ALL (integer)
Metric constants
Gmagick::METRIC_UNDEFINED (integer)
Gmagick::METRIC_MEANABSOLUTEERROR (integer)
Gmagick::METRIC_MEANSQUAREERROR (integer)
Gmagick::METRIC_PEAKABSOLUTEERROR (integer)
Gmagick::METRIC_PEAKSIGNALTONOISERATIO (integer)
Gmagick::METRIC_ROOTMEANSQUAREDERROR (integer)
Pixel constants
Gmagick::PIXEL_CHAR (integer)
Gmagick::PIXEL_DOUBLE (integer)
Gmagick::PIXEL_FLOAT (integer)
Gmagick::PIXEL_INTEGER (integer)
Gmagick::PIXEL_LONG (integer)
Gmagick::PIXEL_QUANTUM (integer)
Gmagick::PIXEL_SHORT (integer)
Colorspace constants
Gmagick::COLORSPACE_UNDEFINED (integer)
Gmagick::COLORSPACE_RGB (integer)
Gmagick::COLORSPACE_GRAY (integer)
Gmagick::COLORSPACE_TRANSPARENT (integer)
Gmagick::COLORSPACE_OHTA (integer)
Gmagick::COLORSPACE_LAB (integer)
Gmagick::COLORSPACE_XYZ (integer)
Gmagick::COLORSPACE_YCBCR (integer)
Gmagick::COLORSPACE_YCC (integer)
Gmagick::COLORSPACE_YIQ (integer)
Gmagick::COLORSPACE_YPBPR (integer)
Gmagick::COLORSPACE_YUV (integer)
Gmagick::COLORSPACE_CMYK (integer)
Gmagick::COLORSPACE_SRGB (integer)
Gmagick::COLORSPACE_HSB (integer)
Gmagick::COLORSPACE_HSL (integer)
Gmagick::COLORSPACE_HWB (integer)
Gmagick::COLORSPACE_REC601LUMA (integer)
Gmagick::COLORSPACE_REC709LUMA (integer)
Gmagick::COLORSPACE_LOG (integer)
Virtual Pixel Method constants
Gmagick::VIRTUALPIXELMETHOD_UNDEFINED (integer)
Gmagick::VIRTUALPIXELMETHOD_BACKGROUND (integer)
Gmagick::VIRTUALPIXELMETHOD_CONSTANT (integer)
Gmagick::VIRTUALPIXELMETHOD_EDGE (integer)
Gmagick::VIRTUALPIXELMETHOD_MIRROR (integer)
Gmagick::VIRTUALPIXELMETHOD_TILE (integer)
Gmagick::VIRTUALPIXELMETHOD_TRANSPARENT (integer)
Preview constants
Gmagick::PREVIEW_UNDEFINED (integer)
Gmagick::PREVIEW_ROTATE (integer)
Gmagick::PREVIEW_SHEAR (integer)
Gmagick::PREVIEW_ROLL (integer)
Gmagick::PREVIEW_HUE (integer)
Gmagick::PREVIEW_SATURATION (integer)
Gmagick::PREVIEW_BRIGHTNESS (integer)
Gmagick::PREVIEW_GAMMA (integer)
Gmagick::PREVIEW_SPIFF (integer)
Gmagick::PREVIEW_DULL (integer)
Gmagick::PREVIEW_GRAYSCALE (integer)
Gmagick::PREVIEW_QUANTIZE (integer)
Gmagick::PREVIEW_DESPECKLE (integer)
Gmagick::PREVIEW_REDUCENOISE (integer)
Gmagick::PREVIEW_ADDNOISE (integer)
Gmagick::PREVIEW_SHARPEN (integer)
Gmagick::PREVIEW_BLUR (integer)
Gmagick::PREVIEW_THRESHOLD (integer)
Gmagick::PREVIEW_EDGEDETECT (integer)
Gmagick::PREVIEW_SPREAD (integer)
Gmagick::PREVIEW_SOLARIZE (integer)
Gmagick::PREVIEW_SHADE (integer)
Gmagick::PREVIEW_RAISE (integer)
Gmagick::PREVIEW_SEGMENT (integer)
Gmagick::PREVIEW_SWIRL (integer)
Gmagick::PREVIEW_IMPLODE (integer)
Gmagick::PREVIEW_WAVE (integer)
Gmagick::PREVIEW_OILPAINT (integer)
Gmagick::PREVIEW_CHARCOALDRAWING (integer)
Gmagick::PREVIEW_JPEG (integer)
Rendering Intent constants
Gmagick::RENDERINGINTENT_UNDEFINED (integer)
Gmagick::RENDERINGINTENT_SATURATION (integer)
Gmagick::RENDERINGINTENT_PERCEPTUAL (integer)
Gmagick::RENDERINGINTENT_ABSOLUTE (integer)
Gmagick::RENDERINGINTENT_RELATIVE (integer)
Fillrule constants
Gmagick::FILLRULE_UNDEFINED (integer)
Gmagick::FILLRULE_EVENODD (integer)
Gmagick::FILLRULE_NONZERO (integer)
Pathunit constants
Gmagick::PATHUNITS_UNDEFINED (integer)
Gmagick::PATHUNITS_USERSPACE (integer)
Gmagick::PATHUNITS_USERSPACEONUSE (integer)
Gmagick::PATHUNITS_OBJECTBOUNDINGBOX (integer)
Linecap constants
Gmagick::LINECAP_UNDEFINED (integer)
Gmagick::LINECAP_BUTT (integer)
Gmagick::LINECAP_ROUND (integer)
Gmagick::LINECAP_SQUARE (integer)
Line Join constants
Gmagick::LINEJOIN_UNDEFINED (integer)
Gmagick::LINEJOIN_MITER (integer)
Gmagick::LINEJOIN_ROUND (integer)
Gmagick::LINEJOIN_BEVEL (integer)
Resourcetype constants
Gmagick::RESOURCETYPE_UNDEFINED (integer)
Gmagick::RESOURCETYPE_AREA (integer)
Gmagick::RESOURCETYPE_DISK (integer)
Gmagick::RESOURCETYPE_FILE (integer)
Gmagick::RESOURCETYPE_MAP (integer)
Gmagick::RESOURCETYPE_MEMORY (integer)
Orientation constants
Gmagick::ORIENTATION_UNDEFINED (integer)
Gmagick::ORIENTATION_TOPLEFT (integer)
Gmagick::ORIENTATION_TOPRIGHT (integer)
Gmagick::ORIENTATION_BOTTOMRIGHT (integer)
Gmagick::ORIENTATION_BOTTOMLEFT (integer)
Gmagick::ORIENTATION_LEFTTOP (integer)
Gmagick::ORIENTATION_RIGHTTOP (integer)
Gmagick::ORIENTATION_RIGHTBOTTOM (integer)
Gmagick::ORIENTATION_LEFTBOTTOM (integer)
Runtime Configuration
Examples
Gmagick


The Gmagick constructor

Gmagick::compositeimage
Gmagick::cropimage
Gmagick
PHP Manual

Gmagick::__construct

(PECL gmagick >= Unknown)

Gmagick::__construct — The Gmagick constructor

Description

Gmagick::__construct ([ string $filename ] )

The Gmagick constructor.

Parameters

filename

The path to an image to load or array of paths

Return Values

Returns a new Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::compositeimage
Gmagick::cropimage
Gmagick


Extracts a region of the image

Gmagick::__construct
Gmagick::cropthumbnailimage
Gmagick
PHP Manual

Gmagick::cropimage

(PECL gmagick >= Unknown)

Gmagick::cropimage — Extracts a region of the image

Description

public void Gmagick::cropimage ( int $width , int $height , int $x , int $y )

Extracts a region of the image.

Parameters

width

The width of the crop

height

The height of the crop

x

The X coordinate of the cropped region's top left corner

y

The Y coordinate of the cropped region's top left corner

Return Values

The cropped Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::__construct
Gmagick::cropthumbnailimage
Gmagick


Creates a crop thumbnail

Gmagick::cropimage
Gmagick::current
Gmagick
PHP Manual

Gmagick::cropthumbnailimage

(PECL gmagick >= Unknown)

Gmagick::cropthumbnailimage — Creates a crop thumbnail

Description

public void Gmagick::cropthumbnailimage ( int $width , int $height )

Creates a fixed size thumbnail by first scaling the image down and cropping a specified area from the center.

Parameters

width

The width of the thumbnail

height

The Height of the thumbnail

Return Values

The cropped Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::cropimage
Gmagick::current
Gmagick


The current purpose

Gmagick::cropthumbnailimage
Gmagick::cyclecolormapimage
Gmagick
PHP Manual

Gmagick::current

(PECL gmagick >= Unknown)

Gmagick::current — The current purpose

Description

public void Gmagick::current ( void )

Returns reference to the current gmagick object with image pointer at the correct sequence.

Parameters

This function has no parameters.

Return Values

Returns self on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::cropthumbnailimage
Gmagick::cyclecolormapimage
Gmagick


Displaces an image's colormap

Gmagick::current
Gmagick::deconstructimages
Gmagick
PHP Manual

Gmagick::cyclecolormapimage

(PECL gmagick >= Unknown)

Gmagick::cyclecolormapimage — Displaces an image's colormap

Description

public void Gmagick::cyclecolormapimage ( float $displace )

Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.

Parameters

displace

The amount to displace the colormap.

Return Values

Returns self on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::current
Gmagick::deconstructimages
Gmagick


Returns certain pixel differences between images

Gmagick::cyclecolormapimage
Gmagick::despeckleimage
Gmagick
PHP Manual

Gmagick::deconstructimages

(PECL gmagick >= Unknown)

Gmagick::deconstructimages — Returns certain pixel differences between images

Description

public void Gmagick::deconstructimages ( void )

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

Parameters

This function has no parameters.

Return Values

Returns self on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::cyclecolormapimage
Gmagick::despeckleimage
Gmagick


The despeckleimage purpose

Gmagick::deconstructimages
Gmagick::destroy
Gmagick
PHP Manual

Gmagick::despeckleimage

(PECL gmagick >= Unknown)

Gmagick::despeckleimage — The despeckleimage purpose

Description

public void Gmagick::despeckleimage ( void )

Reduces the speckle noise in an image while preserving the edges of the original image.

Parameters

This function has no parameters.

Return Values

The despeckled Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Examples

Example #1 Gmagick::despeckleimage example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method

Gmagick::deconstructimages
Gmagick::destroy
Gmagick


The destroy purpose

Gmagick::despeckleimage
Gmagick::drawimage
Gmagick
PHP Manual

Gmagick::destroy

(PECL gmagick >= Unknown)

Gmagick::destroy — The destroy purpose

Description

public void Gmagick::destroy ( void )

Destroys the Gmagick object and frees all resources associated with it

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::despeckleimage
Gmagick::drawimage
Gmagick


Renders the GmagickDraw object on the current image

Gmagick::destroy
Gmagick::edgeimage
Gmagick
PHP Manual

Gmagick::drawimage

(PECL gmagick >= Unknown)

Gmagick::drawimage — Renders the GmagickDraw object on the current image

Description

public void Gmagick::drawimage ( GmagickDraw $GmagickDraw )

Renders the GmagickDraw object on the current image

Parameters

GmagickDraw

The drawing operations to render on the image.

Return Values

The drawn Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::destroy
Gmagick::edgeimage
Gmagick


Enhance edges within the image

Gmagick::drawimage
Gmagick::embossimage
Gmagick
PHP Manual

Gmagick::edgeimage

(PECL gmagick >= Unknown)

Gmagick::edgeimage — Enhance edges within the image

Description

public void Gmagick::edgeimage ( float $radius )

Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected.

Parameters

radius

The radius of the operation.

Return Values

The Gmagick object with edges enhanced.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::drawimage
Gmagick::embossimage
Gmagick


Returns a grayscale image with a three-dimensional effect

Gmagick::edgeimage
Gmagick::enhanceimage
Gmagick
PHP Manual

Gmagick::embossimage

(PECL gmagick >= Unknown)

Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect

Description

public void Gmagick::embossimage ( float $radius , float $sigma )

Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you.

Parameters

radius

The radius of the effect

sigma

The sigma of the effect

Return Values

The embossed Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::edgeimage
Gmagick::enhanceimage
Gmagick


Improves the quality of a noisy image

Gmagick::embossimage
Gmagick::equalizeimage
Gmagick
PHP Manual

Gmagick::enhanceimage

(PECL gmagick >= Unknown)

Gmagick::enhanceimage — Improves the quality of a noisy image

Description

public void Gmagick::enhanceimage ( void )

Applies a digital filter that improves the quality of a noisy image.

Return Values

The enhanced Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::embossimage
Gmagick::equalizeimage
Gmagick


Equalizes the image histogram

Gmagick::enhanceimage
Gmagick::flipimage
Gmagick
PHP Manual

Gmagick::equalizeimage

(PECL gmagick >= Unknown)

Gmagick::equalizeimage — Equalizes the image histogram

Description

public void Gmagick::equalizeimage ( void )

Equalizes the image histogram.

Return Values

The equalized Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::enhanceimage
Gmagick::flipimage
Gmagick


Examples

The following shows some common Gmagick image operations.

Example #1 Gmagick Example

<?php
//Instantiate a new Gmagick object
$image = new Gmagick('example.jpg');

//Make thumbnail from image loaded. 0 for either axes preserves aspect ratio
$image->thumbnailImage(100, 0);

//Create a border around the image, then simulate how the image will look like as an oil painting
//Notice the chaining of mutator methods which is supported in gmagick
$image->borderImage("yellow", 8, 8)->oilPaintImage(0.3);

//Write the current image at the current state to a file
$image->write('example_thumbnail.jpg');
?>
Predefined Constants
Gmagick
Gmagick


Creates a vertical mirror image

Gmagick::equalizeimage
Gmagick::flopimage
Gmagick
PHP Manual

Gmagick::flipimage

(PECL gmagick >= Unknown)

Gmagick::flipimage — Creates a vertical mirror image

Description

public void Gmagick::flipimage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

Return Values

The flipped Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::equalizeimage
Gmagick::flopimage
Gmagick


The flopimage purpose

Gmagick::flipimage
Gmagick::frameimage
Gmagick
PHP Manual

Gmagick::flopimage

(PECL gmagick >= Unknown)

Gmagick::flopimage — The flopimage purpose

Description

public void Gmagick::flopimage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

Return Values

The flopped Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::flipimage
Gmagick::frameimage
Gmagick


Adds a simulated three-dimensional border

Gmagick::flopimage
Gmagick::gammaimage
Gmagick
PHP Manual

Gmagick::frameimage

(PECL gmagick >= Unknown)

Gmagick::frameimage — Adds a simulated three-dimensional border

Description

public void Gmagick::frameimage ( GmagickPixel $color , int $width , int $height , int $inner_bevel , int $outer_bevel )

Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.

Parameters

color

GmagickPixel object or a float representing the matte color

width

The width of the border

height

The height of the border

inner_bevel

The inner bevel width

outer_bevel

The outer bevel width

Return Values

The framed Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::flopimage
Gmagick::gammaimage
Gmagick


Gamma-corrects an image

Gmagick::frameimage
Gmagick::getcopyright
Gmagick
PHP Manual

Gmagick::gammaimage

(PECL gmagick >= Unknown)

Gmagick::gammaimage — Gamma-corrects an image

Description

public void Gmagick::gammaimage ( float $gamma )

Gamma-corrects an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.

Parameters

gamma

The amount of gamma-correction.

Return Values

The gamma corrected Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::frameimage
Gmagick::getcopyright
Gmagick


Returns the GraphicsMagick API copyright as a string

Gmagick::gammaimage
Gmagick::getfilename
Gmagick
PHP Manual

Gmagick::getcopyright

(PECL gmagick >= Unknown)

Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string

Description

public void Gmagick::getcopyright ( void )

Returns the GraphicsMagick API copyright as a string.

Return Values

Returns a string containing the copyright notice of GraphicsMagick and Magickwand C API.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::gammaimage
Gmagick::getfilename
Gmagick


The filename associated with an image sequence

Gmagick::getcopyright
Gmagick::getimagebackgroundcolor
Gmagick
PHP Manual

Gmagick::getfilename

(PECL gmagick >= Unknown)

Gmagick::getfilename — The filename associated with an image sequence

Description

public void Gmagick::getfilename ( void )

Returns the filename associated with an image sequence.

Return Values

Returns a string on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getcopyright
Gmagick::getimagebackgroundcolor
Gmagick


Returns the image background color

Gmagick::getfilename
Gmagick::getimageblueprimary
Gmagick
PHP Manual

Gmagick::getimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::getimagebackgroundcolor — Returns the image background color

Description

public void Gmagick::getimagebackgroundcolor ( void )

Returns the image background color.

Parameters

This function has no parameters.

Return Values

Returns an GmagickPixel set to the background color of the image.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getfilename
Gmagick::getimageblueprimary
Gmagick


Returns the chromaticy blue primary point

Gmagick::getimagebackgroundcolor
Gmagick::getimagebordercolor
Gmagick
PHP Manual

Gmagick::getimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::getimageblueprimary — Returns the chromaticy blue primary point

Description

public void Gmagick::getimageblueprimary ( void )

Returns the chromaticity blue primary point for the image.

Parameters

x

The chromaticity blue primary x-point.

y

The chromaticity blue primary y-point.

Return Values

Array consisting of "x" and "y" coordinates of point.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagebackgroundcolor
Gmagick::getimagebordercolor
Gmagick


Returns the image border color

Gmagick::getimageblueprimary
Gmagick::getimagechanneldepth
Gmagick
PHP Manual

Gmagick::getimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::getimagebordercolor — Returns the image border color

Description

public void Gmagick::getimagebordercolor ( void )

Returns the image border color.

Parameters

This function has no parameters.

Return Values

GmagickPixel object representing the color of the border

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageblueprimary
Gmagick::getimagechanneldepth
Gmagick


Gets the depth for a particular image channel

Gmagick::getimagebordercolor
Gmagick::getimagecolors
Gmagick
PHP Manual

Gmagick::getimagechanneldepth

(PECL gmagick >= Unknown)

Gmagick::getimagechanneldepth — Gets the depth for a particular image channel

Description

public void Gmagick::getimagechanneldepth ( void )

Gets the depth for a particular image channel.

Parameters

This function has no parameters.

Return Values

Depth of image channel

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagebordercolor
Gmagick::getimagecolors
Gmagick


Returns the color of the specified colormap index

Gmagick::getimagechanneldepth
Gmagick::getimagecolorspace
Gmagick
PHP Manual

Gmagick::getimagecolors

(PECL gmagick >= Unknown)

Gmagick::getimagecolors — Returns the color of the specified colormap index

Description

public void Gmagick::getimagecolors ( void )

Returns the color of the specified colormap index.

Parameters

This function has no parameters.

Return Values

The number of colors in image.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagechanneldepth
Gmagick::getimagecolorspace
Gmagick


Gets the image colorspace

Gmagick::getimagecolors
Gmagick::getimagecompose
Gmagick
PHP Manual

Gmagick::getimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::getimagecolorspace — Gets the image colorspace

Description

public void Gmagick::getimagecolorspace ( void )

Gets the image colorspace.

Parameters

This function has no parameters.

Return Values

Colorspace

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagecolors
Gmagick::getimagecompose
Gmagick


Returns the composite operator associated with the image

Gmagick::getimagecolorspace
Gmagick::getimagedelay
Gmagick
PHP Manual

Gmagick::getimagecompose

(PECL gmagick >= Unknown)

Gmagick::getimagecompose — Returns the composite operator associated with the image

Description

public void Gmagick::getimagecompose ( void )

Returns the composite operator associated with the image.

Parameters

This function has no parameters.

Return Values

Returns the composite operator associated with the image.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagecolorspace
Gmagick::getimagedelay
Gmagick


Gets the image delay

Gmagick::getimagecompose
Gmagick::getimagedepth
Gmagick
PHP Manual

Gmagick::getimagedelay

(PECL gmagick >= Unknown)

Gmagick::getimagedelay — Gets the image delay

Description

public void Gmagick::getimagedelay ( void )

Gets the image delay

Parameters

This function has no parameters.

Return Values

Returns the composite operator associated with the image.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagecompose
Gmagick::getimagedepth
Gmagick


Gets the depth of the image

Gmagick::getimagedelay
Gmagick::getimagedispose
Gmagick
PHP Manual

Gmagick::getimagedepth

(PECL gmagick >= Unknown)

Gmagick::getimagedepth — Gets the depth of the image

Description

public void Gmagick::getimagedepth ( void )

Gets the depth of the image.

Parameters

This function has no parameters.

Return Values

Image depth

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagedelay
Gmagick::getimagedispose
Gmagick


Gets the image disposal method

Gmagick::getimagedepth
Gmagick::getimageextrema
Gmagick
PHP Manual

Gmagick::getimagedispose

(PECL gmagick >= Unknown)

Gmagick::getimagedispose — Gets the image disposal method

Description

public void Gmagick::getimagedispose ( void )

Gets the image disposal method

Parameters

This function has no parameters.

Return Values

Returns the dispose method on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagedepth
Gmagick::getimageextrema
Gmagick


Gets the extrema for the image

Gmagick::getimagedispose
Gmagick::getimagefilename
Gmagick
PHP Manual

Gmagick::getimageextrema

(PECL gmagick >= Unknown)

Gmagick::getimageextrema — Gets the extrema for the image

Description

public void Gmagick::getimageextrema ( void )

Returns an associative array with the keys "min" and "max". Throws an GmagickException on error.

Parameters

This function has no parameters.

Return Values

Returns an associative array with the keys "min" and "max".

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagedispose
Gmagick::getimagefilename
Gmagick


Returns the filename of a particular image in a sequence

Gmagick::getimageextrema
Gmagick::getimageformat
Gmagick
PHP Manual

Gmagick::getimagefilename

(PECL gmagick >= Unknown)

Gmagick::getimagefilename — Returns the filename of a particular image in a sequence

Description

public void Gmagick::getimagefilename ( void )

Returns the filename of a particular image in a sequence

Parameters

This function has no parameters.

Return Values

Returns a string with the filename of the image

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageextrema
Gmagick::getimageformat
Gmagick


Returns the format of a particular image in a sequence

Gmagick::getimagefilename
Gmagick::getimagegamma
Gmagick
PHP Manual

Gmagick::getimageformat

(PECL gmagick >= Unknown)

Gmagick::getimageformat — Returns the format of a particular image in a sequence

Description

public void Gmagick::getimageformat ( void )

Returns the format of a particular image in a sequence.

Parameters

This function has no parameters.

Return Values

Returns a string containing the image format on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagefilename
Gmagick::getimagegamma
Gmagick


Gets the image gamma

Gmagick::getimageformat
Gmagick::getimagegreenprimary
Gmagick
PHP Manual

Gmagick::getimagegamma

(PECL gmagick >= Unknown)

Gmagick::getimagegamma — Gets the image gamma

Description

public void Gmagick::getimagegamma ( void )

Gets the image gamma

Parameters

This function has no parameters.

Return Values

Returns the image gamma on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageformat
Gmagick::getimagegreenprimary
Gmagick


Returns the chromaticy green primary point

Gmagick::getimagegamma
Gmagick::getimageheight
Gmagick
PHP Manual

Gmagick::getimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::getimagegreenprimary — Returns the chromaticy green primary point

Description

public void Gmagick::getimagegreenprimary ( void )

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

Parameters

This function has no parameters.

Return Values

Returns an array with the keys "x" and "y" on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagegamma
Gmagick::getimageheight
Gmagick


Returns the image height

Gmagick::getimagegreenprimary
Gmagick::getimagehistogram
Gmagick
PHP Manual

Gmagick::getimageheight

(PECL gmagick >= Unknown)

Gmagick::getimageheight — Returns the image height

Description

public void Gmagick::getimageheight ( void )

Returns the image height

Parameters

This function has no parameters.

Return Values

Returns the image height in pixels.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagegreenprimary
Gmagick::getimagehistogram
Gmagick


Gets the image histogram

Gmagick::getimageheight
Gmagick::getimageindex
Gmagick
PHP Manual

Gmagick::getimagehistogram

(PECL gmagick >= Unknown)

Gmagick::getimagehistogram — Gets the image histogram

Description

public void Gmagick::getimagehistogram ( void )

Returns the image histogram as an array of GmagickPixel objects. Throw an GmagickException on error.

Parameters

This function has no parameters.

Return Values

Returns the image histogram as an array of GmagickPixel objects.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageheight
Gmagick::getimageindex
Gmagick


Gets the index of the current active image

Gmagick::getimagehistogram
Gmagick::getimageinterlacescheme
Gmagick
PHP Manual

Gmagick::getimageindex

(PECL gmagick >= Unknown)

Gmagick::getimageindex — Gets the index of the current active image

Description

public void Gmagick::getimageindex ( void )

Returns the index of the current active image within the Gmagick object.

Parameters

This function has no parameters.

Return Values

Index of current active image

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagehistogram
Gmagick::getimageinterlacescheme
Gmagick


Gets the image interlace scheme

Gmagick::getimageindex
Gmagick::getimageiterations
Gmagick
PHP Manual

Gmagick::getimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::getimageinterlacescheme — Gets the image interlace scheme

Description

public void Gmagick::getimageinterlacescheme ( void )

Gets the image interlace scheme.

Parameters

This function has no parameters.

Return Values

Returns the interlace scheme as an integer on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageindex
Gmagick::getimageiterations
Gmagick


Gets the image iterations

Gmagick::getimageinterlacescheme
Gmagick::getimagematte
Gmagick
PHP Manual

Gmagick::getimageiterations

(PECL gmagick >= Unknown)

Gmagick::getimageiterations — Gets the image iterations

Description

public void Gmagick::getimageiterations ( void )

Gets the image iterations.

Parameters

This function has no parameters.

Return Values

Returns the image iterations as an integer.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageinterlacescheme
Gmagick::getimagematte
Gmagick


Return if the image has a matte channel

Gmagick::getimageiterations
Gmagick::getimagemattecolor
Gmagick
PHP Manual

Gmagick::getimagematte

(PECL gmagick >= Unknown)

Gmagick::getimagematte — Return if the image has a matte channel

Description

public void Gmagick::getimagematte ( void )

Returns TRUE if the image has a matte channel otherwise false.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the image has a matte channel otherwise false.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageiterations
Gmagick::getimagemattecolor
Gmagick


Returns the image matte color

Gmagick::getimagematte
Gmagick::getimageprofile
Gmagick
PHP Manual

Gmagick::getimagemattecolor

(PECL gmagick >= Unknown)

Gmagick::getimagemattecolor — Returns the image matte color

Description

public void Gmagick::getimagemattecolor ( void )

Returns GmagickPixel object on success. Throw an GmagickException on error.

Parameters

This function has no parameters.

Return Values

Returns GmagickPixel object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagematte
Gmagick::getimageprofile
Gmagick


Returns the named image profile.

Gmagick::getimagemattecolor
Gmagick::getimageredprimary
Gmagick
PHP Manual

Gmagick::getimageprofile

(PECL gmagick >= Unknown)

Gmagick::getimageprofile — Returns the named image profile.

Description

public void Gmagick::getimageprofile ( void )

Returns the named image profile.

Parameters

This function has no parameters.

Return Values

Returns a string containing the image profile.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagemattecolor
Gmagick::getimageredprimary
Gmagick


Returns the chromaticity red primary point

Gmagick::getimageprofile
Gmagick::getimagerenderingintent
Gmagick
PHP Manual

Gmagick::getimageredprimary

(PECL gmagick >= Unknown)

Gmagick::getimageredprimary — Returns the chromaticity red primary point

Description

public void Gmagick::getimageredprimary ( void )

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Parameters

This function has no parameters.

Return Values

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageprofile
Gmagick::getimagerenderingintent
Gmagick


Gets the image rendering intent

Gmagick::getimageredprimary
Gmagick::getimageresolution
Gmagick
PHP Manual

Gmagick::getimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::getimagerenderingintent — Gets the image rendering intent

Description

public void Gmagick::getimagerenderingintent ( void )

Gets the image rendering intent

Parameters

This function has no parameters.

Return Values

Extracts a region of the image and returns it as a a new wand

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageredprimary
Gmagick::getimageresolution
Gmagick


Gets the image X and Y resolution

Gmagick::getimagerenderingintent
Gmagick::getimagescene
Gmagick
PHP Manual

Gmagick::getimageresolution

(PECL gmagick >= Unknown)

Gmagick::getimageresolution — Gets the image X and Y resolution

Description

public void Gmagick::getimageresolution ( void )

Returns the resolution as an array.

Parameters

This function has no parameters.

Return Values

Returns the resolution as an array.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagerenderingintent
Gmagick::getimagescene
Gmagick


Gets the image scene

Gmagick::getimageresolution
Gmagick::getimagesignature
Gmagick
PHP Manual

Gmagick::getimagescene

(PECL gmagick >= Unknown)

Gmagick::getimagescene — Gets the image scene

Description

public void Gmagick::getimagescene ( void )

Gets the image scene.

Parameters

This function has no parameters.

Return Values

Returns the image scene.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageresolution
Gmagick::getimagesignature
Gmagick


Generates an SHA-256 message digest

Gmagick::getimagescene
Gmagick::getimagetype
Gmagick
PHP Manual

Gmagick::getimagesignature

(PECL gmagick >= Unknown)

Gmagick::getimagesignature — Generates an SHA-256 message digest

Description

public void Gmagick::getimagesignature ( void )

Generates an SHA-256 message digest for the image pixel stream.

Parameters

This function has no parameters.

Return Values

Returns a string containing the SHA-256 hash of the file.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagescene
Gmagick::getimagetype
Gmagick


Gets the potential image type.

Gmagick::getimagesignature
Gmagick::getimageunits
Gmagick
PHP Manual

Gmagick::getimagetype

(PECL gmagick >= Unknown)

Gmagick::getimagetype — Gets the potential image type.

Description

public void Gmagick::getimagetype ( void )

Gets the potential image type.

Parameters

This function has no parameters.

Return Values

Returns the potential image type.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagesignature
Gmagick::getimageunits
Gmagick


Gets the image units of resolution

Gmagick::getimagetype
Gmagick::getimagewhitepoint
Gmagick
PHP Manual

Gmagick::getimageunits

(PECL gmagick >= Unknown)

Gmagick::getimageunits — Gets the image units of resolution

Description

public void Gmagick::getimageunits ( void )

Gets the image units of resolution.

Parameters

This function has no parameters.

Return Values

Returns the image units of resolution.

Gmagick::getimagetype
Gmagick::getimagewhitepoint
Gmagick


Returns the chromaticity white point

Gmagick::getimageunits
Gmagick::getimagewidth
Gmagick
PHP Manual

Gmagick::getimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::getimagewhitepoint — Returns the chromaticity white point

Description

public void Gmagick::getimagewhitepoint ( void )

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Parameters

This function has no parameters.

Return Values

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimageunits
Gmagick::getimagewidth
Gmagick


Returns the width of the image

Gmagick::getimagewhitepoint
Gmagick::getpackagename
Gmagick
PHP Manual

Gmagick::getimagewidth

(PECL gmagick >= Unknown)

Gmagick::getimagewidth — Returns the width of the image

Description

public void Gmagick::getimagewidth ( void )

Returns the width of the image.

Parameters

This function has no parameters.

Return Values

Returns the image width.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagewhitepoint
Gmagick::getpackagename
Gmagick


Returns the GraphicsMagick package name.

Gmagick::getimagewidth
Gmagick::getquantumdepth
Gmagick
PHP Manual

Gmagick::getpackagename

(PECL gmagick >= Unknown)

Gmagick::getpackagename — Returns the GraphicsMagick package name.

Description

public void Gmagick::getpackagename ( void )

Returns the GraphicsMagick package name.

Parameters

This function has no parameters.

Return Values

Returns the GraphicsMagick package name as a string.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getimagewidth
Gmagick::getquantumdepth
Gmagick


Returns the Gmagick quantum depth as a string.

Gmagick::getpackagename
Gmagick::getreleasedate
Gmagick
PHP Manual

Gmagick::getquantumdepth

(PECL gmagick >= Unknown)

Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string.

Description

public void Gmagick::getquantumdepth ( void )

Returns the Gmagick quantum depth as a string.

Parameters

This function has no parameters.

Return Values

Returns the Gmagick quantum depth as a string.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getpackagename
Gmagick::getreleasedate
Gmagick


Returns the GraphicsMagick release date as a string.

Gmagick::getquantumdepth
Gmagick::getsamplingfactors
Gmagick
PHP Manual

Gmagick::getreleasedate

(PECL gmagick >= Unknown)

Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string.

Description

public void Gmagick::getreleasedate ( void )

Returns the GraphicsMagick release date as a string.

Parameters

This function has no parameters.

Return Values

Returns the GraphicsMagick release date as a string.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getquantumdepth
Gmagick::getsamplingfactors
Gmagick


Gets the horizontal and vertical sampling factor.

Gmagick::getreleasedate
Gmagick::getsize
Gmagick
PHP Manual

Gmagick::getsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor.

Description

public void Gmagick::getsamplingfactors ( void )

Gets the horizontal and vertical sampling factor.

Parameters

This function has no parameters.

Return Values

Returns an associative array with the horizontal and vertical sampling factors of the image.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getreleasedate
Gmagick::getsize
Gmagick


Returns the size associated with the Gmagick object

Gmagick::getsamplingfactors
Gmagick::getversion
Gmagick
PHP Manual

Gmagick::getsize

(PECL gmagick >= Unknown)

Gmagick::getsize — Returns the size associated with the Gmagick object

Description

public void Gmagick::getsize ( void )

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

Parameters

This function has no parameters.

Return Values

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getsamplingfactors
Gmagick::getversion
Gmagick


Returns the GraphicsMagick API version

Gmagick::getsize
Gmagick::hasnextimage
Gmagick
PHP Manual

Gmagick::getversion

(PECL gmagick >= Unknown)

Gmagick::getversion — Returns the GraphicsMagick API version

Description

public void Gmagick::getversion ( void )

Returns the GraphicsMagick API version as a string and as a number.

Parameters

This function has no parameters.

Return Values

Returns the GraphicsMagick API version as a string and as a number.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getsize
Gmagick::hasnextimage
Gmagick


Checks if the object has more images

Gmagick::getversion
Gmagick::haspreviousimage
Gmagick
PHP Manual

Gmagick::hasnextimage

(PECL gmagick >= Unknown)

Gmagick::hasnextimage — Checks if the object has more images

Description

public void Gmagick::hasnextimage ( void )

Returns TRUE if the object has more images when traversing the list in the forward direction.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the object has more images when traversing the list in the forward direction, returns FALSE if there are none.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::getversion
Gmagick::haspreviousimage
Gmagick


Checks if the object has a previous image

Gmagick::hasnextimage
Gmagick::implodeimage
Gmagick
PHP Manual

Gmagick::haspreviousimage

(PECL gmagick >= Unknown)

Gmagick::haspreviousimage — Checks if the object has a previous image

Description

public void Gmagick::haspreviousimage ( void )

Returns TRUE if the object has more images when traversing the list in the reverse direction

Parameters

This function has no parameters.

Return Values

Returns TRUE if the object has more images when traversing the list in the reverse direction, returns FALSE if there are none.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::hasnextimage
Gmagick::implodeimage
Gmagick


Creates a new image as a copy

Gmagick::haspreviousimage
Gmagick::labelimage
Gmagick
PHP Manual

Gmagick::implodeimage

(PECL gmagick >= Unknown)

Gmagick::implodeimage — Creates a new image as a copy

Description

public void Gmagick::implodeimage ( float $radius )

Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage.

Parameters

radius

The radius of the implode

Return Values

Returns imploded Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::haspreviousimage
Gmagick::labelimage
Gmagick


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/gmagick.

Note: The official name of this extension is gmagick.

For Windows, the build of the Gmagick extension is available » here

Requirements
Runtime Configuration
Installing/Configuring


Adds a label to an image.

Gmagick::implodeimage
Gmagick::levelimage
Gmagick
PHP Manual

Gmagick::labelimage

(PECL gmagick >= Unknown)

Gmagick::labelimage — Adds a label to an image.

Description

public void Gmagick::labelimage ( string $label )

Adds a label to an image.

Parameters

label

The label to add

Return Values

Gmagick with label.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::implodeimage
Gmagick::levelimage
Gmagick


Adjusts the levels of an image

Gmagick::labelimage
Gmagick::magnifyimage
Gmagick
PHP Manual

Gmagick::levelimage

(PECL gmagick >= Unknown)

Gmagick::levelimage — Adjusts the levels of an image

Description

public void Gmagick::levelimage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel ] )

Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.

Parameters

blackPoint

The image black point

gamma

The gamma value

whitePoint

The image white point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Return Values

Gmagick object with image levelled.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::labelimage
Gmagick::magnifyimage
Gmagick


Scales an image proportionally 2x

Gmagick::levelimage
Gmagick::mapimage
Gmagick
PHP Manual

Gmagick::magnifyimage

(PECL gmagick >= Unknown)

Gmagick::magnifyimage — Scales an image proportionally 2x

Description

public void Gmagick::magnifyimage ( void )

Conveniently scales an image proportionally to twice its original size.

Parameters

This function has no parameters.

Return Values

Magnified Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::levelimage
Gmagick::mapimage
Gmagick


Replaces the colors of an image with the closest color from a reference image.

Gmagick::magnifyimage
Gmagick::medianfilterimage
Gmagick
PHP Manual

Gmagick::mapimage

(PECL gmagick >= Unknown)

Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image.

Description

public void Gmagick::mapimage ( gmagick $gmagick , int $dither )

Replaces the colors of an image with the closest color from a reference image.

Parameters

gmagick

The reference image

dither

Set this integer value to something other than zero to dither the mapped image

Return Values

Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::magnifyimage
Gmagick::medianfilterimage
Gmagick


Applies a digital filter

Gmagick::mapimage
Gmagick::minifyimage
Gmagick
PHP Manual

Gmagick::medianfilterimage

(PECL gmagick >= Unknown)

Gmagick::medianfilterimage — Applies a digital filter

Description

public void Gmagick::medianfilterimage ( float $radius )

Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.

Parameters

radius

The radius of the pixel neighborhood.

Return Values

Gmagick object with median filter applied.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::mapimage
Gmagick::minifyimage
Gmagick


Scales an image proportionally to half its size

Gmagick::medianfilterimage
Gmagick::modulateimage
Gmagick
PHP Manual

Gmagick::minifyimage

(PECL gmagick >= Unknown)

Gmagick::minifyimage — Scales an image proportionally to half its size

Description

public void Gmagick::minifyimage ( void )

A convenient method that scales an image proportionally to one-half its original size

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::medianfilterimage
Gmagick::modulateimage
Gmagick


Control the brightness, saturation, and hue

Gmagick::minifyimage
Gmagick::motionblurimage
Gmagick
PHP Manual

Gmagick::modulateimage

(PECL gmagick >= Unknown)

Gmagick::modulateimage — Control the brightness, saturation, and hue

Description

public void Gmagick::modulateimage ( float $brightness , float $saturation , float $hue )

Lets you control the brightness, saturation, and hue of an image. Hue is the percentage of absolute rotation from the current position. For example 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a clockwise rotation of 90 degrees, with 0 and 200 both resulting in a rotation of 180 degrees.

Parameters

brightness

The percent change in brighness (-100 thru +100).

saturation

The percent change in saturation (-100 thru +100)

hue

The percent change in hue (-100 thru +100)

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::minifyimage
Gmagick::motionblurimage
Gmagick


Simulates motion blur

Gmagick::modulateimage
Gmagick::newimage
Gmagick
PHP Manual

Gmagick::motionblurimage

(PECL gmagick >= Unknown)

Gmagick::motionblurimage — Simulates motion blur

Description

public void Gmagick::motionblurimage ( float $radius , float $sigma , float $angle )

Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage() selects a suitable radius for you. Angle gives the angle of the blurring motion.

Parameters

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::modulateimage
Gmagick::newimage
Gmagick


Creates a new image

Gmagick::motionblurimage
Gmagick::nextimage
Gmagick
PHP Manual

Gmagick::newimage

(PECL gmagick >= Unknown)

Gmagick::newimage — Creates a new image

Description

public void Gmagick::newimage ( int $width , int $height , mixed $background , string $format )

Creates a new image with the specified background color

Parameters

width

Width of the new image

height

Height of the new image

background

The background color used for this image (as float)

format

Image format.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::motionblurimage
Gmagick::nextimage
Gmagick


Moves to the next image

Gmagick::newimage
Gmagick::normalizeimage
Gmagick
PHP Manual

Gmagick::nextimage

(PECL gmagick >= Unknown)

Gmagick::nextimage — Moves to the next image

Description

public void Gmagick::nextimage ( void )

Associates the next image in the image list with an Gmagick object.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::newimage
Gmagick::normalizeimage
Gmagick


Enhances the contrast of a color image

Gmagick::nextimage
Gmagick::oilpaintimage
Gmagick
PHP Manual

Gmagick::normalizeimage

(PECL gmagick >= Unknown)

Gmagick::normalizeimage — Enhances the contrast of a color image

Description

public void Gmagick::normalizeimage ([ int $channel ] )

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

Parameters

channel

Identify which channel to normalize

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::nextimage
Gmagick::oilpaintimage
Gmagick


Simulates an oil painting

Gmagick::normalizeimage
Gmagick::previousimage
Gmagick
PHP Manual

Gmagick::oilpaintimage

(PECL gmagick >= Unknown)

Gmagick::oilpaintimage — Simulates an oil painting

Description

public void Gmagick::oilpaintimage ( float $radius )

Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

Parameters

radius

The radius of the circular neighborhood.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::normalizeimage
Gmagick::previousimage
Gmagick


Move to the previous image in the object

Gmagick::oilpaintimage
Gmagick::profileimage
Gmagick
PHP Manual

Gmagick::previousimage

(PECL gmagick >= Unknown)

Gmagick::previousimage — Move to the previous image in the object

Description

public void Gmagick::previousimage ( void )

Assocates the previous image in an image list with the Gmagick object.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::oilpaintimage
Gmagick::profileimage
Gmagick


Adds or removes a profile from an image

Gmagick::previousimage
Gmagick::quantizeimage
Gmagick
PHP Manual

Gmagick::profileimage

(PECL gmagick >= Unknown)

Gmagick::profileimage — Adds or removes a profile from an image

Description

public void Gmagick::profileimage ( string $name , string $profile )

Adds or removes a ICC, IPTC, or generic profile from an image. If the profile is NULL, it is removed from the image otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.

Parameters

name

Name of profile to add or remove: ICC, IPTC, or generic profile.

profile

The profile.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::previousimage
Gmagick::quantizeimage
Gmagick


Analyzes the colors within a reference image

Gmagick::profileimage
Gmagick::quantizeimages
Gmagick
PHP Manual

Gmagick::quantizeimage

(PECL gmagick >= Unknown)

Gmagick::quantizeimage — Analyzes the colors within a reference image

Description

public void Gmagick::quantizeimage ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )

Analyzes the colors within a reference image and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

Parameters

numColors

The number of colors.

colorspace

Perform color reduction in this colorspace, typically RGBColorspace.

treeDepth

Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number_colors) is required. To expand the color tree completely, use a value of 8.

dither

A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.

measureError

A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::profileimage
Gmagick::quantizeimages
Gmagick


The quantizeimages purpose

Gmagick::quantizeimage
Gmagick::queryfontmetrics
Gmagick
PHP Manual

Gmagick::quantizeimages

(PECL gmagick >= Unknown)

Gmagick::quantizeimages — The quantizeimages purpose

Description

public void Gmagick::quantizeimages ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )

Analyzes the colors within a sequence of images and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

Parameters

numColors

The number of colors.

colorspace

Perform color reduction in this colorspace, typically RGBColorspace.

treeDepth

Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number_colors) is required. To expand the color tree completely, use a value of 8.

dither

A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.

measureError

A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::quantizeimage
Gmagick::queryfontmetrics
Gmagick


Returns an array representing the font metrics

Gmagick::quantizeimages
Gmagick::queryfonts
Gmagick
PHP Manual

Gmagick::queryfontmetrics

(PECL gmagick >= Unknown)

Gmagick::queryfontmetrics — Returns an array representing the font metrics

Description

public void Gmagick::queryfontmetrics ( void )

MagickQueryFontMetrics() returns an array representing the font metrics.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::quantizeimages
Gmagick::queryfonts
Gmagick


Returns the configured fonts

Gmagick::queryfontmetrics
Gmagick::queryformats
Gmagick
PHP Manual

Gmagick::queryfonts

(PECL gmagick >= Unknown)

Gmagick::queryfonts — Returns the configured fonts

Description

public void Gmagick::queryfonts ( void )

Returns fonts supported by Gmagick.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::queryfontmetrics
Gmagick::queryformats
Gmagick


Returns formats supported by Gmagick.

Gmagick::queryfonts
Gmagick::radialblurimage
Gmagick
PHP Manual

Gmagick::queryformats

(PECL gmagick >= Unknown)

Gmagick::queryformats — Returns formats supported by Gmagick.

Description

public void Gmagick::queryformats ( string $pattern )

Returns formats supported by Gmagick.

Parameters

pattern

Specifies a pointer to a text string containing a pattern.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::queryfonts
Gmagick::radialblurimage
Gmagick


Radial blurs an image

Gmagick::queryformats
Gmagick::raiseimage
Gmagick
PHP Manual

Gmagick::radialblurimage

(PECL gmagick >= Unknown)

Gmagick::radialblurimage — Radial blurs an image

Description

public void Gmagick::radialblurimage ( float $angle [, int $channel ] )

Radial blurs an image.

Parameters

angle

The angle of the blur in degrees.

channel

Related channel

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::queryformats
Gmagick::raiseimage
Gmagick


Creates a simulated 3d button-like effect

Gmagick::radialblurimage
Gmagick::read
Gmagick
PHP Manual

Gmagick::raiseimage

(PECL gmagick >= Unknown)

Gmagick::raiseimage — Creates a simulated 3d button-like effect

Description

public void Gmagick::raiseimage ( int $width , int $height , int $x , int $y , bool $raise )

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.

Parameters

width

Width of the area to raise.

height

Height of the area to raise.

x

X coordinate

y

Y coordinate

raise

A value other than zero creates a 3-D raise effect, otherwise it has a lowered effect.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::radialblurimage
Gmagick::read
Gmagick


Reads image from filename

Gmagick::raiseimage
Gmagick::readimage
Gmagick
PHP Manual

Gmagick::read

(PECL gmagick >= Unknown)

Gmagick::read — Reads image from filename

Description

public void Gmagick::read ( string $filename )

Reads image from filename.

Parameters

filename

The image filename.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::raiseimage
Gmagick::readimage
Gmagick


Reads image from filename

Gmagick::read
Gmagick::readimageblob
Gmagick
PHP Manual

Gmagick::readimage

(PECL gmagick >= Unknown)

Gmagick::readimage — Reads image from filename

Description

public void Gmagick::readimage ( string $filename )

Reads image from filename.

Parameters

filename

The image filename.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::read
Gmagick::readimageblob
Gmagick


Reads image from a binary string

Gmagick::readimage
Gmagick::readimagefile
Gmagick
PHP Manual

Gmagick::readimageblob

(PECL gmagick >= Unknown)

Gmagick::readimageblob — Reads image from a binary string

Description

public void Gmagick::readimageblob ( string $imageContents [, string $filename ] )

Reads image from a binary string.

Parameters

imageContents

Content of image

filename

The image filename.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::readimage
Gmagick::readimagefile
Gmagick


The readimagefile purpose

Gmagick::readimageblob
Gmagick::reducenoiseimage
Gmagick
PHP Manual

Gmagick::readimagefile

(PECL gmagick >= Unknown)

Gmagick::readimagefile — The readimagefile purpose

Description

public void Gmagick::readimagefile ( string $fp )

Reads an image or image sequence from an open file descriptor.

Parameters

fp

The file descriptor.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::readimageblob
Gmagick::reducenoiseimage
Gmagick


Smooths the contours of an image

Gmagick::readimagefile
Gmagick::removeimage
Gmagick
PHP Manual

Gmagick::reducenoiseimage

(PECL gmagick >= Unknown)

Gmagick::reducenoiseimage — Smooths the contours of an image

Description

public void Gmagick::reducenoiseimage ( float $radius )

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and Gmagick::reduceNoiseImage() selects a suitable radius for you.

Parameters

radius

The radius of the pixel neighborhood.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::readimagefile
Gmagick::removeimage
Gmagick


Removes an image from the image list

Gmagick::reducenoiseimage
Gmagick::removeimageprofile
Gmagick
PHP Manual

Gmagick::removeimage

(PECL gmagick >= Unknown)

Gmagick::removeimage — Removes an image from the image list

Description

public void Gmagick::removeimage ( void )

Removes an image from the image list.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::reducenoiseimage
Gmagick::removeimageprofile
Gmagick


Removes the named image profile and returns it

Gmagick::removeimage
Gmagick::resampleimage
Gmagick
PHP Manual

Gmagick::removeimageprofile

(PECL gmagick >= Unknown)

Gmagick::removeimageprofile — Removes the named image profile and returns it

Description

public void Gmagick::removeimageprofile ( string $name )

Removes the named image profile and returns it.

Parameters

name

Name of profile to return: ICC, IPTC, or generic profile.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::removeimage
Gmagick::resampleimage
Gmagick


Requirements

This extension works best with GraphicsMagick version 1.4+ and PHP 5.1.3+. Gmagick should work with earlier versions up to GraphicsMagick 1.2.6 but some features and formats are not supported for these versions. Windows version of GraphicsMagick is available from the GraphicsMagick website. To read about the difference between ImageMagick and GraphicsMagick, check this out: » FAQ .

Installing/Configuring
Installation
Installing/Configuring


Resample image to desired resolution

Gmagick::removeimageprofile
Gmagick::resizeimage
Gmagick
PHP Manual

Gmagick::resampleimage

(PECL gmagick >= Unknown)

Gmagick::resampleimage — Resample image to desired resolution

Description

public void Gmagick::resampleimage ( float $xResolution , float $yResolution , int $filter , float $blur )

Resample image to desired resolution.

Parameters

xResolution

The new image x resolution.

yResolution

The new image y resolution.

filter

Image filter to use.

blur

The blur factor where larger than 1 is blurry, smaller than 1 is sharp.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::removeimageprofile
Gmagick::resizeimage
Gmagick


Scales an image

Gmagick::resampleimage
Gmagick::rollimage
Gmagick
PHP Manual

Gmagick::resizeimage

(PECL gmagick >= Unknown)

Gmagick::resizeimage — Scales an image

Description

public void Gmagick::resizeimage ( int $width , int $height , int $filter , float $blur [, bool $fit ] )

Scales an image to the desired dimensions with a filter.

Parameters

width

The number of columns in the scaled image.

height

The number of rows in the scaled image.

filter

Image filter to use.

blur

The blur factor where larger than 1 is blurry, lesser than 1 is sharp.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::resampleimage
Gmagick::rollimage
Gmagick


Offsets an image

Gmagick::resizeimage
Gmagick::rotateimage
Gmagick
PHP Manual

Gmagick::rollimage

(PECL gmagick >= Unknown)

Gmagick::rollimage — Offsets an image

Description

public void Gmagick::rollimage ( int $x , int $y )

Offsets an image as defined by x and y.

Parameters

x

The x offset.

y

The y offset.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::resizeimage
Gmagick::rotateimage
Gmagick


Rotates an image

Gmagick::rollimage
Gmagick::scaleimage
Gmagick
PHP Manual

Gmagick::rotateimage

(PECL gmagick >= Unknown)

Gmagick::rotateimage — Rotates an image

Description

public void Gmagick::rotateimage ( mixed $color , float $degrees )

Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.

Parameters

color

The background pixel.

degrees

The number of degrees to rotate the image.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::rollimage
Gmagick::scaleimage
Gmagick


Scales the size of an image

Gmagick::rotateimage
Gmagick::separateimagechannel
Gmagick
PHP Manual

Gmagick::scaleimage

(PECL gmagick >= Unknown)

Gmagick::scaleimage — Scales the size of an image

Description

public void Gmagick::scaleimage ( int $width , int $height )

Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param.

Parameters

width

The number of columns in the scaled image.

height

The number of rows in the scaled image.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::rotateimage
Gmagick::separateimagechannel
Gmagick


Separates a channel from the image

Gmagick::scaleimage
Gmagick::setfilename
Gmagick
PHP Manual

Gmagick::separateimagechannel

(PECL gmagick >= Unknown)

Gmagick::separateimagechannel — Separates a channel from the image

Description

public void Gmagick::separateimagechannel ( int $channel )

Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.

Parameters

channel

Identify which channel to extract: RedChannel, GreenChannel, BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, BlackChannel.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::scaleimage
Gmagick::setfilename
Gmagick


Sets the filename before you read or write the image

Gmagick::separateimagechannel
Gmagick::setimagebackgroundcolor
Gmagick
PHP Manual

Gmagick::setfilename

(PECL gmagick >= Unknown)

Gmagick::setfilename — Sets the filename before you read or write the image

Description

public void Gmagick::setfilename ( string $filename )

Sets the filename before you read or write an image file.

Parameters

filename

The image filename.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::separateimagechannel
Gmagick::setimagebackgroundcolor
Gmagick


Sets the image background color.

Gmagick::setfilename
Gmagick::setimageblueprimary
Gmagick
PHP Manual

Gmagick::setimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::setimagebackgroundcolor — Sets the image background color.

Description

public void Gmagick::setimagebackgroundcolor ( GmagickPixel $color )

Sets the image background color.

Parameters

color

The background pixel wand.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setfilename
Gmagick::setimageblueprimary
Gmagick


Sets the image chromaticity blue primary point.

Gmagick::setimagebackgroundcolor
Gmagick::setimagebordercolor
Gmagick
PHP Manual

Gmagick::setimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point.

Description

public void Gmagick::setimageblueprimary ( float $x , float $y )

Sets the image chromaticity blue primary point.

Parameters

x

The blue primary x-point.

y

The blue primary y-point.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagebackgroundcolor
Gmagick::setimagebordercolor
Gmagick


Sets the image border color.

Gmagick::setimageblueprimary
Gmagick::setimagechanneldepth
Gmagick
PHP Manual

Gmagick::setimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::setimagebordercolor — Sets the image border color.

Description

public void Gmagick::setimagebordercolor ( GmagickPixel $color )

Sets the image border color.

Parameters

color

The border pixel wand.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimageblueprimary
Gmagick::setimagechanneldepth
Gmagick


Sets the depth of a particular image channel

Gmagick::setimagebordercolor
Gmagick::setimagecolorspace
Gmagick
PHP Manual

Gmagick::setimagechanneldepth

(PECL gmagick >= Unknown)

Gmagick::setimagechanneldepth — Sets the depth of a particular image channel

Description

public void Gmagick::setimagechanneldepth ( int $channel , int $depth )

Sets the depth of a particular image channel.

Parameters

channel

Identify which channel to extract: RedChannel, GreenChannel, BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, BlackChannel.

depth

The image depth in bits.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagebordercolor
Gmagick::setimagecolorspace
Gmagick


Sets the image colorspace

Gmagick::setimagechanneldepth
Gmagick::setimagecompose
Gmagick
PHP Manual

Gmagick::setimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::setimagecolorspace — Sets the image colorspace

Description

public void Gmagick::setimagecolorspace ( int $colorspace )

Sets the image colorspace.

Parameters

colorspace

The image colorspace: UndefinedColorspace, RGBColorspace, GRAYColorspace, TransparentColorspace, OHTAColorspace, XYZColorspace, YCbCrColorspace, YCCColorspace, YIQColorspace, YPbPrColorspace, YPbPrColorspace, YUVColorspace, CMYKColorspace, sRGBColorspace, HSLColorspace, or HWBColorspace.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagechanneldepth
Gmagick::setimagecompose
Gmagick


Sets the image composite operator

Gmagick::setimagecolorspace
Gmagick::setimagedelay
Gmagick
PHP Manual

Gmagick::setimagecompose

(PECL gmagick >= Unknown)

Gmagick::setimagecompose — Sets the image composite operator

Description

public void Gmagick::setimagecompose ( int $composite )

Sets the image composite operator.

Parameters

composite

The image composite operator.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagecolorspace
Gmagick::setimagedelay
Gmagick


Sets the image delay

Gmagick::setimagecompose
Gmagick::setimagedepth
Gmagick
PHP Manual

Gmagick::setimagedelay

(PECL gmagick >= Unknown)

Gmagick::setimagedelay — Sets the image delay

Description

public void Gmagick::setimagedelay ( int $delay )

Sets the image delay

Parameters

delay

The image delay in 1/100th of a second.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagecompose
Gmagick::setimagedepth
Gmagick


Sets the image depth

Gmagick::setimagedelay
Gmagick::setimagedispose
Gmagick
PHP Manual

Gmagick::setimagedepth

(PECL gmagick >= Unknown)

Gmagick::setimagedepth — Sets the image depth

Description

public void Gmagick::setimagedepth ( float $depth )

Sets the image depth

Parameters

depth

The image depth in bits: 8, 16, or 32.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagedelay
Gmagick::setimagedispose
Gmagick


Sets the image disposal method

Gmagick::setimagedepth
Gmagick::setimagefilename
Gmagick
PHP Manual

Gmagick::setimagedispose

(PECL gmagick >= Unknown)

Gmagick::setimagedispose — Sets the image disposal method

Description

public void Gmagick::setimagedispose ( int $disposeType )

Sets the image disposal method.

Parameters

disposeType

The image disposal type.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagedepth
Gmagick::setimagefilename
Gmagick


Sets the filename of a particular image in a sequence

Gmagick::setimagedispose
Gmagick::setimageformat
Gmagick
PHP Manual

Gmagick::setimagefilename

(PECL gmagick >= Unknown)

Gmagick::setimagefilename — Sets the filename of a particular image in a sequence

Description

public void Gmagick::setimagefilename ( string $filename )

Sets the filename of a particular image in a sequence.

Parameters

filename

The image filename.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagedispose
Gmagick::setimageformat
Gmagick


Sets the format of a particular image

Gmagick::setimagefilename
Gmagick::setimagegamma
Gmagick
PHP Manual

Gmagick::setimageformat

(PECL gmagick >= Unknown)

Gmagick::setimageformat — Sets the format of a particular image

Description

public void Gmagick::setimageformat ( string $imageFormat )

Sets the format of a particular image in a sequence.

Parameters

imageFormat

The image format.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagefilename
Gmagick::setimagegamma
Gmagick


Sets the image gamma

Gmagick::setimageformat
Gmagick::setimagegreenprimary
Gmagick
PHP Manual

Gmagick::setimagegamma

(PECL gmagick >= Unknown)

Gmagick::setimagegamma — Sets the image gamma

Description

public void Gmagick::setimagegamma ( float $gamma )

Sets the image gamma.

Parameters

gamma

The image gamma.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimageformat
Gmagick::setimagegreenprimary
Gmagick


TSets the image chromaticity green primary point.

Gmagick::setimagegamma
Gmagick::setimageindex
Gmagick
PHP Manual

Gmagick::setimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::setimagegreenprimary — TSets the image chromaticity green primary point.

Description

public void Gmagick::setimagegreenprimary ( float $x , float $y )

Sets the image chromaticity green primary point.

Parameters

x

The chromaticity green primary x-point.

y

The chromaticity green primary y-point.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagegamma
Gmagick::setimageindex
Gmagick


Set the iterator to the position in the image list specified with the index parameter

Gmagick::setimagegreenprimary
Gmagick::setimageinterlacescheme
Gmagick
PHP Manual

Gmagick::setimageindex

(PECL gmagick >= Unknown)

Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter

Description

public void Gmagick::setimageindex ( int $index )

Set the iterator to the position in the image list specified with the index parameter.

Parameters

index

The scene number.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagegreenprimary
Gmagick::setimageinterlacescheme
Gmagick


Sets the interlace scheme of the image.

Gmagick::setimageindex
Gmagick::setimageiterations
Gmagick
PHP Manual

Gmagick::setimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image.

Description

public void Gmagick::setimageinterlacescheme ( int $interlace )

Sets the interlace scheme of the image.

Parameters

interlace

The image interlace scheme: NoInterlace, LineInterlace, PlaneInterlace, PartitionInterlace.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimageindex
Gmagick::setimageiterations
Gmagick


Sets the image iterations.

Gmagick::setimageinterlacescheme
Gmagick::setimageprofile
Gmagick
PHP Manual

Gmagick::setimageiterations

(PECL gmagick >= Unknown)

Gmagick::setimageiterations — Sets the image iterations.

Description

public void Gmagick::setimageiterations ( int $iterations )

Sets the image iterations.

Parameters

iterations

The image delay in 1/100th of a second.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimageinterlacescheme
Gmagick::setimageprofile
Gmagick


Adds a named profile to the Gmagick object

Gmagick::setimageiterations
Gmagick::setimageredprimary
Gmagick
PHP Manual

Gmagick::setimageprofile

(PECL gmagick >= Unknown)

Gmagick::setimageprofile — Adds a named profile to the Gmagick object

Description

public void Gmagick::setimageprofile ( string $name , string $profile )

Adds a named profile to the Gmagick object. If a profile with the same name already exists, it is replaced. This method differs from the Gmagick::ProfileImage() method in that it does not apply any CMS color profiles.

Parameters

name

Name of profile to add or remove: ICC, IPTC, or generic profile.

profile

The profile.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimageiterations
Gmagick::setimageredprimary
Gmagick


Sets the image chromaticity red primary point.

Gmagick::setimageprofile
Gmagick::setimagerenderingintent
Gmagick
PHP Manual

Gmagick::setimageredprimary

(PECL gmagick >= Unknown)

Gmagick::setimageredprimary — Sets the image chromaticity red primary point.

Description

public void Gmagick::setimageredprimary ( float $x , float $y )

Sets the image chromaticity red primary point.

Parameters

x

The red primary x-point.

y

The red primary y-point.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimageprofile
Gmagick::setimagerenderingintent
Gmagick


Sets the image rendering intent

Gmagick::setimageredprimary
Gmagick::setimageresolution
Gmagick
PHP Manual

Gmagick::setimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::setimagerenderingintent — Sets the image rendering intent

Description

public void Gmagick::setimagerenderingintent ( int $rendering_intent )

Sets the image rendering intent.

Parameters

rendering_intent

The image rendering intent: UndefinedIntent, SaturationIntent, PerceptualIntent, AbsoluteIntent, or RelativeIntent.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimageredprimary
Gmagick::setimageresolution
Gmagick


Sets the image resolution

Gmagick::setimagerenderingintent
Gmagick::setimagescene
Gmagick
PHP Manual

Gmagick::setimageresolution

(PECL gmagick >= Unknown)

Gmagick::setimageresolution — Sets the image resolution

Description

public void Gmagick::setimageresolution ( float $xResolution , float $yResolution )

Sets the image resolution.

Parameters

xResolution

The image x resolution.

yResolution

The image y resolution.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagerenderingintent
Gmagick::setimagescene
Gmagick


Sets the image scene

Gmagick::setimageresolution
Gmagick::setimagetype
Gmagick
PHP Manual

Gmagick::setimagescene

(PECL gmagick >= Unknown)

Gmagick::setimagescene — Sets the image scene

Description

public void Gmagick::setimagescene ( string $scene )

Sets the image scene.

Parameters

scene

The image scene number.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimageresolution
Gmagick::setimagetype
Gmagick


Sets the image type

Gmagick::setimagescene
Gmagick::setimageunits
Gmagick
PHP Manual

Gmagick::setimagetype

(PECL gmagick >= Unknown)

Gmagick::setimagetype — Sets the image type

Description

public void Gmagick::setimagetype ( string $imgType )

Sets the image type.

Parameters

imgType

The image type: UndefinedType, BilevelType, GrayscaleType, GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType, TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType, or OptimizeType.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagescene
Gmagick::setimageunits
Gmagick


Sets the image units of resolution.

Gmagick::setimagetype
Gmagick::setimagewhitepoint
Gmagick
PHP Manual

Gmagick::setimageunits

(PECL gmagick >= Unknown)

Gmagick::setimageunits — Sets the image units of resolution.

Description

public void Gmagick::setimageunits ( int $resolution )

Sets the image units of resolution.

Parameters

resolution

The image units of resolution : Undefinedresolution, PixelsPerInchResolution, or PixelsPerCentimeterResolution.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagetype
Gmagick::setimagewhitepoint
Gmagick


Sets the image chromaticity white point.

Gmagick::setimageunits
Gmagick::setsamplingfactors
Gmagick
PHP Manual

Gmagick::setimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::setimagewhitepoint — Sets the image chromaticity white point.

Description

public void Gmagick::setimagewhitepoint ( float $x , float $y )

Sets the image chromaticity white point.

Parameters

x

The white x-point.

y

The white y-point.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimageunits
Gmagick::setsamplingfactors
Gmagick


Sets the image sampling factors.

Gmagick::setimagewhitepoint
Gmagick::setsize
Gmagick
PHP Manual

Gmagick::setsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::setsamplingfactors — Sets the image sampling factors.

Description

public void Gmagick::setsamplingfactors ( array $factors )

Sets the image sampling factors.

Parameters

factors

An array of doubles representing the sampling factor for each color component (in RGB order).

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setimagewhitepoint
Gmagick::setsize
Gmagick


Sets the size of the Gmagick object

Gmagick::setsamplingfactors
Gmagick::shearimage
Gmagick
PHP Manual

Gmagick::setsize

(PECL gmagick >= Unknown)

Gmagick::setsize — Sets the size of the Gmagick object

Description

public void Gmagick::setsize ( int $columns , int $rows )

Sets the size of the Gmagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK.

Parameters

columns

The width in pixels.

rows

The height in pixels.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setsamplingfactors
Gmagick::shearimage
Gmagick


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
Introduction
Requirements
Gmagick


Creating a parallelogram

Gmagick::setsize
Gmagick::solarizeimage
Gmagick
PHP Manual

Gmagick::shearimage

(PECL gmagick >= Unknown)

Gmagick::shearimage — Creating a parallelogram

Description

public void Gmagick::shearimage ( mixed $color , float $xShear , float $yShear )

Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

Parameters

color

The background pixel wand.

xShear

The number of degrees to shear the image.

yShear

The number of degrees to shear the image.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::setsize
Gmagick::solarizeimage
Gmagick


Applies a solarizing effect to the image

Gmagick::shearimage
Gmagick::spreadimage
Gmagick
PHP Manual

Gmagick::solarizeimage

(PECL gmagick >= Unknown)

Gmagick::solarizeimage — Applies a solarizing effect to the image

Description

public void Gmagick::solarizeimage ( float $threshold )

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization.

Parameters

threshold

Define the extent of the solarization.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::shearimage
Gmagick::spreadimage
Gmagick


Randomly displaces each pixel in a block

Gmagick::solarizeimage
Gmagick::stripimage
Gmagick
PHP Manual

Gmagick::spreadimage

(PECL gmagick >= Unknown)

Gmagick::spreadimage — Randomly displaces each pixel in a block

Description

public void Gmagick::spreadimage ( float $radius )

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

Parameters

radius

Choose a random pixel in a neighborhood of this extent.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::solarizeimage
Gmagick::stripimage
Gmagick


Strips an image of all profiles and comments

Gmagick::spreadimage
Gmagick::swirlimage
Gmagick
PHP Manual

Gmagick::stripimage

(PECL gmagick >= Unknown)

Gmagick::stripimage — Strips an image of all profiles and comments

Description

public void Gmagick::stripimage ( void )

Strips an image of all profiles and comments.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::spreadimage
Gmagick::swirlimage
Gmagick


Swirls the pixels about the center of the image

Gmagick::stripimage
Gmagick::thumbnailimage
Gmagick
PHP Manual

Gmagick::swirlimage

(PECL gmagick >= Unknown)

Gmagick::swirlimage — Swirls the pixels about the center of the image

Description

public void Gmagick::swirlimage ( float $degrees )

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

Parameters

degrees

Define the tightness of the swirling effect.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::stripimage
Gmagick::thumbnailimage
Gmagick


Changes the size of an image

Gmagick::swirlimage
Gmagick::trimimage
Gmagick
PHP Manual

Gmagick::thumbnailimage

(PECL gmagick >= Unknown)

Gmagick::thumbnailimage — Changes the size of an image

Description

public void Gmagick::thumbnailimage ( int $width , int $height )

Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small low cost thumbnail images suited for display on the Web. If TRUE is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until the match or are smaller than the parameter given for the side.

Parameters

width

Image width

height

Image height

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::swirlimage
Gmagick::trimimage
Gmagick


Remove edges from the image

Gmagick::thumbnailimage
Gmagick::write
Gmagick
PHP Manual

Gmagick::trimimage

(PECL gmagick >= Unknown)

Gmagick::trimimage — Remove edges from the image

Description

public void Gmagick::trimimage ( float $fuzz )

Remove edges that are the background color from the image.

Parameters

fuzz

By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.

Return Values

The Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::thumbnailimage
Gmagick::write
Gmagick


Writes an image to the specified filename

Gmagick::trimimage
Gmagick::writeimage
Gmagick
PHP Manual

Gmagick::write

(PECL gmagick >= Unknown)

Gmagick::write — Writes an image to the specified filename

Description

public void Gmagick::write ( string $filename )

Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Gmagick::ReadImage() or Gmagick::SetImageFilename().

Parameters

filename

The image filename.

Return Values

The Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::trimimage
Gmagick::writeimage
Gmagick


Writes an image to the specified filename

Gmagick::write
GmagickDraw
Gmagick
PHP Manual

Gmagick::writeimage

(PECL gmagick >= Unknown)

Gmagick::writeimage — Writes an image to the specified filename

Description

public void Gmagick::writeimage ( string $filename )

Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Gmagick::ReadImage() or Gmagick::SetImageFilename().

Parameters

filename

The image filename.

Return Values

The Gmagick object

Errors/Exceptions

Throws an GmagickException on error.

Gmagick::write
GmagickDraw
Gmagick


Draws text on the image

GmagickDraw
GmagickDraw::arc
GmagickDraw
PHP Manual

GmagickDraw::annotate

(PECL gmagick >= Unknown)

GmagickDraw::annotate — Draws text on the image

Description

public void GmagickDraw::annotate ( float $x , float $y , string $text )

Draws text on the image.

Parameters

x

x ordinate to left of text

y

y ordinate to text baseline

text

text to draw

Return Values

The GmagickDraw object on success.

GmagickDraw
GmagickDraw::arc
GmagickDraw


Draws an arc

GmagickDraw::annotate
GmagickDraw::bezier
GmagickDraw
PHP Manual

GmagickDraw::arc

(PECL gmagick >= Unknown)

GmagickDraw::arc — Draws an arc

Description

public void GmagickDraw::arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )

Draws an arc falling within a specified bounding rectangle on the image.

Parameters

sx

starting x ordinate of bounding rectangle

sy

starting y ordinate of bounding rectangle

ex

ending x ordinate of bounding rectangle

ey

ending y ordinate of bounding rectangle

sd

starting degrees of rotation

ed

ending degrees of rotation

Return Values

The GmagickDraw object on success.

GmagickDraw::annotate
GmagickDraw::bezier
GmagickDraw


Draws a bezier curve

GmagickDraw::arc
GmagickDraw::ellipse
GmagickDraw
PHP Manual

GmagickDraw::bezier

(PECL gmagick >= Unknown)

GmagickDraw::bezier — Draws a bezier curve

Description

public void GmagickDraw::bezier ( array $coordinate_array )

Draws a bezier curve through a set of points on the image.

Parameters

coordinate_array

Coordinates array

Return Values

The GmagickDraw object on success

GmagickDraw::arc
GmagickDraw::ellipse
GmagickDraw


Draws an ellipse on the image

GmagickDraw::bezier
GmagickDraw::getfillcolor
GmagickDraw
PHP Manual

GmagickDraw::ellipse

(PECL gmagick >= Unknown)

GmagickDraw::ellipse — Draws an ellipse on the image

Description

public void GmagickDraw::ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )

Draws an ellipse on the image.

Parameters

ox

origin x ordinate

oy

origin y ordinate

rx

radius in x

ry

radius in y

start

starting rotation in degrees

end

ending rotation in degrees

Return Values

The GmagickDraw object on success

GmagickDraw::bezier
GmagickDraw::getfillcolor
GmagickDraw


Returns the fill color

GmagickDraw::ellipse
GmagickDraw::getfillopacity
GmagickDraw
PHP Manual

GmagickDraw::getfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::getfillcolor — Returns the fill color

Description

public void GmagickDraw::getfillcolor ( void )

Returns the fill color used for drawing filled objects.

Parameters

This function has no parameters.

Return Values

The GmagickPixel fill color used for drawing filled objects.

GmagickDraw::ellipse
GmagickDraw::getfillopacity
GmagickDraw


Returns the opacity used when drawing

GmagickDraw::getfillcolor
GmagickDraw::getfont
GmagickDraw
PHP Manual

GmagickDraw::getfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::getfillopacity — Returns the opacity used when drawing

Description

public void GmagickDraw::getfillopacity ( void )

Returns the opacity used when drawing

Parameters

This function has no parameters.

Return Values

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

GmagickDraw::getfillcolor
GmagickDraw::getfont
GmagickDraw


Returns the font

GmagickDraw::getfillopacity
GmagickDraw::getfontsize
GmagickDraw
PHP Manual

GmagickDraw::getfont

(PECL gmagick >= Unknown)

GmagickDraw::getfont — Returns the font

Description

public void GmagickDraw::getfont ( void )

Returns a string specifying the font used when annotating with text.

Parameters

This function has no parameters.

Return Values

Returns a string on success and false if no font is set.

GmagickDraw::getfillopacity
GmagickDraw::getfontsize
GmagickDraw


Returns the font pointsize

GmagickDraw::getfont
GmagickDraw::getfontstyle
GmagickDraw
PHP Manual

GmagickDraw::getfontsize

(PECL gmagick >= Unknown)

GmagickDraw::getfontsize — Returns the font pointsize

Description

public void GmagickDraw::getfontsize ( void )

Returns the font pointsize used when annotating with text.

Parameters

This function has no parameters.

Return Values

Returns the font size associated with the current GmagickDraw object.

GmagickDraw::getfont
GmagickDraw::getfontstyle
GmagickDraw


Returns the font style

GmagickDraw::getfontsize
GmagickDraw::getfontweight
GmagickDraw
PHP Manual

GmagickDraw::getfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::getfontstyle — Returns the font style

Description

public void GmagickDraw::getfontstyle ( void )

Returns the font style used when annotating with text.

Parameters

This function has no parameters.

Return Values

Returns the font style constant (STYLE_) associated with the GmagickDraw object or 0 if no style is set.

GmagickDraw::getfontsize
GmagickDraw::getfontweight
GmagickDraw


Returns the font weight

GmagickDraw::getfontstyle
GmagickDraw::getstrokecolor
GmagickDraw
PHP Manual

GmagickDraw::getfontweight

(PECL gmagick >= Unknown)

GmagickDraw::getfontweight — Returns the font weight

Description

public void GmagickDraw::getfontweight ( void )

Returns the font weight used when annotating with text.

Parameters

This function has no parameters.

Return Values

Returns an int on success and 0 if no weight is set.

GmagickDraw::getfontstyle
GmagickDraw::getstrokecolor
GmagickDraw


Returns the color used for stroking object outlines

GmagickDraw::getfontweight
GmagickDraw::getstrokeopacity
GmagickDraw
PHP Manual

GmagickDraw::getstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines

Description

public void GmagickDraw::getstrokecolor ( void )

Returns the color used for stroking object outlines.

Parameters

This function has no parameters.

Return Values

Returns an GmagickPixel object which describes the color

GmagickDraw::getfontweight
GmagickDraw::getstrokeopacity
GmagickDraw


Returns the opacity of stroked object outlines

GmagickDraw::getstrokecolor
GmagickDraw::getstrokewidth
GmagickDraw
PHP Manual

GmagickDraw::getstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines

Description

public void GmagickDraw::getstrokeopacity ( void )

Returns the opacity of stroked object outlines.

Parameters

This function has no parameters.

Return Values

Returns a double describing the opacity.

GmagickDraw::getstrokecolor
GmagickDraw::getstrokewidth
GmagickDraw


Returns the width of the stroke used to draw object outlines

GmagickDraw::getstrokeopacity
GmagickDraw::gettextdecoration
GmagickDraw
PHP Manual

GmagickDraw::getstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines

Description

public void GmagickDraw::getstrokewidth ( void )

Returns the width of the stroke used to draw object outlines.

Parameters

This function has no parameters.

Return Values

Returns a double describing the stroke width.

GmagickDraw::getstrokeopacity
GmagickDraw::gettextdecoration
GmagickDraw


Returns the text decoration

GmagickDraw::getstrokewidth
GmagickDraw::gettextencoding
GmagickDraw
PHP Manual

GmagickDraw::gettextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::gettextdecoration — Returns the text decoration

Description

public void GmagickDraw::gettextdecoration ( void )

Returns the decoration applied when annotating with text.

Parameters

This function has no parameters.

Return Values

Returns one of the DECORATION_ constants and 0 if no decoration is set.

GmagickDraw::getstrokewidth
GmagickDraw::gettextencoding
GmagickDraw


Returns the code set used for text annotations

GmagickDraw::gettextdecoration
GmagickDraw::line
GmagickDraw
PHP Manual

GmagickDraw::gettextencoding

(PECL gmagick >= Unknown)

GmagickDraw::gettextencoding — Returns the code set used for text annotations

Description

public void GmagickDraw::gettextencoding ( void )

Returns a string which specifies the code set used for text annotations.

Parameters

This function has no parameters.

Return Values

Returns a string specifying the code set or false if text encoding is not set.

GmagickDraw::gettextdecoration
GmagickDraw::line
GmagickDraw


The line purpose

GmagickDraw::gettextencoding
GmagickDraw::point
GmagickDraw
PHP Manual

GmagickDraw::line

(PECL gmagick >= Unknown)

GmagickDraw::line — The line purpose

Description

public void GmagickDraw::line ( float $sx , float $sy , float $ex , float $ey )

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

Parameters

sx

starting x ordinate

sy

starting y ordinate

ex

ending x ordinate

ey

ending y ordinate

Return Values

The GmagickDraw object on success

GmagickDraw::gettextencoding
GmagickDraw::point
GmagickDraw


Draws a point

GmagickDraw::line
GmagickDraw::polygon
GmagickDraw
PHP Manual

GmagickDraw::point

(PECL gmagick >= Unknown)

GmagickDraw::point — Draws a point

Description

public void GmagickDraw::point ( float $x , float $y )

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

Parameters

x

target x coordinate

y

target y coordinate

Return Values

The GmagickDraw object on success

GmagickDraw::line
GmagickDraw::polygon
GmagickDraw


Draws a polygon

GmagickDraw::point
GmagickDraw::polyline
GmagickDraw
PHP Manual

GmagickDraw::polygon

(PECL gmagick >= Unknown)

GmagickDraw::polygon — Draws a polygon

Description

public void GmagickDraw::polygon ( array $coordinates )

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parameters

coordinates

coordinate array

Return Values

The GmagickDraw object on success

GmagickDraw::point
GmagickDraw::polyline
GmagickDraw


Draws a polyline

GmagickDraw::polygon
GmagickDraw::rectangle
GmagickDraw
PHP Manual

GmagickDraw::polyline

(PECL gmagick >= Unknown)

GmagickDraw::polyline — Draws a polyline

Description

public void GmagickDraw::polyline ( array $coordinate_array )

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parameters

coordinate_array

The array of coordinates

Return Values

The GmagickDraw object on success

GmagickDraw::polygon
GmagickDraw::rectangle
GmagickDraw


Draws a rectangle

GmagickDraw::polyline
GmagickDraw::rotate
GmagickDraw
PHP Manual

GmagickDraw::rectangle

(PECL gmagick >= Unknown)

GmagickDraw::rectangle — Draws a rectangle

Description

public void GmagickDraw::rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

Parameters

x1

x ordinate of first coordinate

y1

y ordinate of first coordinate

x2

x ordinate of second coordinate

y2

y ordinate of second coordinate

Return Values

The GmagickDraw object on success

GmagickDraw::polyline
GmagickDraw::rotate
GmagickDraw


Applies the specified rotation to the current coordinate space

GmagickDraw::rectangle
GmagickDraw::roundrectangle
GmagickDraw
PHP Manual

GmagickDraw::rotate

(PECL gmagick >= Unknown)

GmagickDraw::rotate — Applies the specified rotation to the current coordinate space

Description

public void GmagickDraw::rotate ( float $degrees )

Applies the specified rotation to the current coordinate space.

Parameters

degrees

degrees of rotation

Return Values

The GmagickDraw object on success

GmagickDraw::rectangle
GmagickDraw::roundrectangle
GmagickDraw


Draws a rounded rectangle

GmagickDraw::rotate
GmagickDraw::scale
GmagickDraw
PHP Manual

GmagickDraw::roundrectangle

(PECL gmagick >= Unknown)

GmagickDraw::roundrectangle — Draws a rounded rectangle

Description

public void GmagickDraw::roundrectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )

Draws a rounded rectangle given two coordinates, x and y corner radiuses and using the current stroke, stroke width, and fill settings.

Parameters

x1

x ordinate of first coordinate

y1

y ordinate of first coordinate

x2

x ordinate of second coordinate

y2

y ordinate of second coordinate

rx

radius of corner in horizontal direction

ry

radius of corner in vertical direction

Return Values

The GmagickDraw object on success

GmagickDraw::rotate
GmagickDraw::scale
GmagickDraw


Adjusts the scaling factor

GmagickDraw::roundrectangle
GmagickDraw::setfillcolor
GmagickDraw
PHP Manual

GmagickDraw::scale

(PECL gmagick >= Unknown)

GmagickDraw::scale — Adjusts the scaling factor

Description

public void GmagickDraw::scale ( float $x , float $y )

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

Parameters

x

horizontal scale factor

y

vertical scale factor

Return Values

The GmagickDraw object on success

GmagickDraw::roundrectangle
GmagickDraw::setfillcolor
GmagickDraw


Sets the fill color to be used for drawing filled objects.

GmagickDraw::scale
GmagickDraw::setfillopacity
GmagickDraw
PHP Manual

GmagickDraw::setfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects.

Description

public void GmagickDraw::setfillcolor ( string $color )

Sets the fill color to be used for drawing filled objects.

Parameters

color

GmagickPixel indicating color to use for filling.

Return Values

The GmagickDraw object on success

GmagickDraw::scale
GmagickDraw::setfillopacity
GmagickDraw


The setfillopacity purpose

GmagickDraw::setfillcolor
GmagickDraw::setfont
GmagickDraw
PHP Manual

GmagickDraw::setfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::setfillopacity — The setfillopacity purpose

Description

public void GmagickDraw::setfillopacity ( float $fill_opacity )

Sets the opacity to use when drawing using the fill color or fill texture. Setting it to 1.0 will make fill full opaque.

Parameters

fill_opacity

Fill opacity

Return Values

The GmagickDraw object on success

GmagickDraw::setfillcolor
GmagickDraw::setfont
GmagickDraw


Sets the fully-specified font to use when annotating with text.

GmagickDraw::setfillopacity
GmagickDraw::setfontsize
GmagickDraw
PHP Manual

GmagickDraw::setfont

(PECL gmagick >= Unknown)

GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text.

Description

public void GmagickDraw::setfont ( string $font )

Sets the fully-specified font to use when annotating with text

Parameters

font

font name

Return Values

The GmagickDraw object on success

GmagickDraw::setfillopacity
GmagickDraw::setfontsize
GmagickDraw


Sets the font pointsize to use when annotating with text.

GmagickDraw::setfont
GmagickDraw::setfontstyle
GmagickDraw
PHP Manual

GmagickDraw::setfontsize

(PECL gmagick >= Unknown)

GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text.

Description

public void GmagickDraw::setfontsize ( float $pointsize )

Sets the font pointsize to use when annotating with text.

Parameters

pointsize

Text pointsize

Return Values

The GmagickDraw object on success

GmagickDraw::setfont
GmagickDraw::setfontstyle
GmagickDraw


Sets the font style to use when annotating with text

GmagickDraw::setfontsize
GmagickDraw::setfontweight
GmagickDraw
PHP Manual

GmagickDraw::setfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::setfontstyle — Sets the font style to use when annotating with text

Description

public void GmagickDraw::setfontstyle ( string $style )

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

Parameters

style

Font style (NormalStyle, ItalicStyle, ObliqueStyle, AnyStyle)

Return Values

The GmagickDraw object on success

GmagickDraw::setfontsize
GmagickDraw::setfontweight
GmagickDraw


Sets the font weight

GmagickDraw::setfontstyle
GmagickDraw::setstrokecolor
GmagickDraw
PHP Manual

GmagickDraw::setfontweight

(PECL gmagick >= Unknown)

GmagickDraw::setfontweight — Sets the font weight

Description

public void GmagickDraw::setfontweight ( int $weight )

Sets the font weight to use when annotating with text.

Parameters

weight

Font weight (valid range 100-900)

Return Values

The GmagickDraw object on success

GmagickDraw::setfontstyle
GmagickDraw::setstrokecolor
GmagickDraw


Sets the color used for stroking object outlines.

GmagickDraw::setfontweight
GmagickDraw::setstrokeopacity
GmagickDraw
PHP Manual

GmagickDraw::setstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines.

Description

public void GmagickDraw::setstrokecolor ( GmagickPixel $color )

Sets the color used for stroking object outlines.

Parameters

color

GmagickPixel representing the color for the stroke.

Return Values

The GmagickDraw object on success

GmagickDraw::setfontweight
GmagickDraw::setstrokeopacity
GmagickDraw


Specifies the opacity of stroked object outlines.

GmagickDraw::setstrokecolor
GmagickDraw::setstrokewidth
GmagickDraw
PHP Manual

GmagickDraw::setstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines.

Description

public void GmagickDraw::setstrokeopacity ( float $stroke_opacity )

Specifies the opacity of stroked object outlines.

Parameters

stroke_opacity

Stroke opacity. The value 1.0 is opaque.

Return Values

The GmagickDraw object on success

GmagickDraw::setstrokecolor
GmagickDraw::setstrokewidth
GmagickDraw


Sets the width of the stroke used to draw object outlines.

GmagickDraw::setstrokeopacity
GmagickDraw::settextdecoration
GmagickDraw
PHP Manual

GmagickDraw::setstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines.

Description

public void GmagickDraw::setstrokewidth ( float $width )

Sets the width of the stroke used to draw object outlines

Parameters

width

Stroke width

Return Values

The GmagickDraw object on success

GmagickDraw::setstrokeopacity
GmagickDraw::settextdecoration
GmagickDraw


Specifies a decoration

GmagickDraw::setstrokewidth
GmagickDraw::settextencoding
GmagickDraw
PHP Manual

GmagickDraw::settextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::settextdecoration — Specifies a decoration

Description

public void GmagickDraw::settextdecoration ( int $decoration )

Specifies a decoration to be applied when annotating with text.

Parameters

int

Text decoration. One of NoDecoration, UnderlineDecoration, OverlineDecoration, or LineThroughDecoration

Return Values

The GmagickDraw object on success

GmagickDraw::setstrokewidth
GmagickDraw::settextencoding
GmagickDraw


Specifies specifies the text code set

GmagickDraw::settextdecoration
GmagickPixel
GmagickDraw
PHP Manual

GmagickDraw::settextencoding

(PECL gmagick >= Unknown)

GmagickDraw::settextencoding — Specifies specifies the text code set

Description

public void GmagickDraw::settextencoding ( string $encoding )

Specifies specifies the code set to use for text annotations. The only character encoding which may be specified at this time is "UTF-8" for representing Unicode as a sequence of bytes. Specify an empty string to set text encoding to the system's default. Successful text annotation using Unicode may require fonts designed to support Unicode.

Parameters

encoding

Character string specifying text encoding

Return Values

The GmagickDraw object on success

GmagickDraw::settextdecoration
GmagickPixel
GmagickDraw


The GmagickPixel constructor

GmagickPixel
GmagickPixel::getcolor
GmagickPixel
PHP Manual

GmagickPixel::__construct

(PECL gmagick >= Unknown)

GmagickPixel::__construct — The GmagickPixel constructor

Description

GmagickPixel::__construct ([ string $color ] )

Constructs an GmagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

Parameters

color

The optional color string to use as the initial value of this object.

Return Values

The GmagickPixel object on success.

GmagickPixel
GmagickPixel::getcolor
GmagickPixel


Returns the color

GmagickPixel::__construct
GmagickPixel::getcolorcount
GmagickPixel
PHP Manual

GmagickPixel::getcolor

(PECL gmagick >= Unknown)

GmagickPixel::getcolor — Returns the color

Description

public void GmagickPixel::getcolor ([ bool $as_array [, bool $normalize_array ]] )

Returns the color described by the GmagickPixel object, as an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

Parameters

as_array

True to indicate return of array instead of string

normalize_array

Normalize the color values

Return Values

An array of channel values, each normalized if TRUE is given as param. Throws GmagickPixelException on error.

GmagickPixel::__construct
GmagickPixel::getcolorcount
GmagickPixel


Returns the color count associated with this color

GmagickPixel::getcolor
GmagickPixel::getcolorvalue
GmagickPixel
PHP Manual

GmagickPixel::getcolorcount

(PECL gmagick >= Unknown)

GmagickPixel::getcolorcount — Returns the color count associated with this color

Description

public void GmagickPixel::getcolorcount ([ bool $as_array [, bool $normalize_array ]] )

Returns the color count associated with this color

Parameters

This function has no parameters.

Return Values

Returns the color count as an integer on success, throws GmagickPixelException on failure.

GmagickPixel::getcolor
GmagickPixel::getcolorvalue
GmagickPixel


Gets the normalized value of the provided color channel

GmagickPixel::getcolorcount
GmagickPixel::setcolor
GmagickPixel
PHP Manual

GmagickPixel::getcolorvalue

(PECL gmagick >= Unknown)

GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel

Description

public void GmagickPixel::getcolorvalue ( int $color )

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

Parameters

color

The channel to check, specified as one of the Gmagick channel constants.

Return Values

The value of the channel, as a normalized floating-point number, throwing GmagickPixelException on error.

GmagickPixel::getcolorcount
GmagickPixel::setcolor
GmagickPixel


Sets the color

GmagickPixel::getcolorvalue
GmagickPixel::setcolorvalue
GmagickPixel
PHP Manual

GmagickPixel::setcolor

(PECL gmagick >= Unknown)

GmagickPixel::setcolor — Sets the color

Description

public void GmagickPixel::setcolor ( string $color )

Sets the color described by the GmagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.).

Parameters

color

The color definition to use in order to initialise the GmagickPixel object.

Return Values

The GmagickPixel object on success.

GmagickPixel::getcolorvalue
GmagickPixel::setcolorvalue
GmagickPixel


Sets the normalized value of one of the channels

GmagickPixel::setcolor
Cairo
GmagickPixel
PHP Manual

GmagickPixel::setcolorvalue

(PECL gmagick >= Unknown)

GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

Description

public void GmagickPixel::setcolorvalue ( int $color , float $value )

Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to a GmagickPixel object.

Parameters

color

One of the Gmagick channel color constants.

value

The value to set this channel to, ranging from 0 to 1.

Return Values

The GmagickPixel object on success.

GmagickPixel::setcolor
Cairo
GmagickPixel


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GMP_ROUND_ZERO (integer)
GMP_ROUND_PLUSINF (integer)
GMP_ROUND_MINUSINF (integer)
GMP_VERSION (string)
The GMP library version
Resource Types
Examples
GMP


Examples

Example #1 Factorial function using GMP

<?php
function fact($x)
{
    $return = 1;
    for ($i=2; $i < $x; $i++) {
        $return = gmp_mul($return, $i);
    }
    return $return;
}

echo gmp_strval(fact(1000)) . "\n";
?>

This will calculate factorial of 1000 (pretty big number) very fast.

Predefined Constants
GMP Functions
GMP


Installation

In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You can download the GMP library from » http://gmplib.org/#DOWNLOAD. This site also has the GMP manual available.

You will need GMP version 2 or better to use these functions. Some functions may require more recent version of the GMP library.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

Most GPM functions operate on or return GMP number resources.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
GMP


Predefined Constants

GNUPG_SIG_MODE_NORMAL (integer)
GNUPG_SIG_MODE_DETACH (integer)
GNUPG_SIG_MODE_CLEAR (integer)
GNUPG_VALIDITY_UNKNOWN (integer)
GNUPG_VALIDITY_UNDEFINED (integer)
GNUPG_VALIDITY_NEVER (integer)
GNUPG_VALIDITY_MARGINAL (integer)
GNUPG_VALIDITY_FULL (integer)
GNUPG_VALIDITY_ULTIMATE (integer)
GNUPG_PROTOCOL_OpenPGP (integer)
GNUPG_PROTOCOL_CMS (integer)
GNUPG_SIGSUM_VALID (integer)
GNUPG_SIGSUM_GREEN (integer)
GNUPG_SIGSUM_RED (integer)
GNUPG_SIGSUM_KEY_REVOKED (integer)
GNUPG_SIGSUM_KEY_EXPIRED (integer)
GNUPG_SIGSUM_KEY_MISSING (integer)
GNUPG_SIGSUM_SIG_EXPIRED (integer)
GNUPG_SIGSUM_CRL_MISSING (integer)
GNUPG_SIGSUM_CRL_TOO_OLD (integer)
GNUPG_SIGSUM_BAD_POLICY (integer)
GNUPG_SIGSUM_SYS_ERROR (integer)
GNUPG_ERROR_WARNING (integer)
GNUPG_ERROR_EXCEPTION (integer)
GNUPG_ERROR_SILENT (integer)
Resource Types
Examples
GnuPG


Examples

Table of Contents

  • Clearsign text
Predefined Constants
Clearsign text
GnuPG


Clearsign text

This example will clearsign a given text.

Example #1 gnupg clearsign example (procedural)

<?php
// init gnupg
$res = gnupg_init();
// not really needed. Clearsign is default
gnupg_setsignmode($res,GNUPG_SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = gnupg_sign($res,"just a test");
echo $signed;
?>

Example #2 gnupg clearsign example (OO)

<?php
// new class
$gnupg = new gnupg();
// not really needed. Clearsign is default
$gnupg->setsignmode(gnupg::SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
$gnupg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = $gnupg->sign("just a test");
echo $signed;
?>

Example #3 keylistiterator

This extension also comes with an Iterator for your keyring.

<?php
// create a new iterator for listing all public keys that matches 'example'
$iterator = new gnupg_keylistiterator("example");
foreach($iterator as $fingerprint => $userid){
    echo $fingerprint." -> ".$userid."\n";
}
?>
Examples
GnuPG Functions
Examples


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/gnupg.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

The gnupg extension requires PHP 4.3. To use this extension in an OO style, PHP 5 is required.

This extension requires the » gpgme library

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
GnuPG


Builtin Fonts And Encodings

Table of Contents

  • Builtin Fonts
  • Builtin Encodings
Basic PECL/haru example
Builtin Fonts
haru


Builtin Encodings

Single-byte character set encodings
Name | Description
StandardEncoding | The default encoding of PDF.
MacRomanEncoding | The standard encoding of Mac OS.
WinAnsiEncoding | The standard encoding of Windows.
FontSpecific | The font built-in encoding.
ISO8859-2 | Latin2 (East European)
ISO8859-3 | Latin3 (South European)
ISO8859-4 | Latin4 (North European)
ISO8859-5 | Cyrillic
ISO8859-6 | Arabic
ISO8859-7 | Greek
ISO8859-8 | Hebrew
ISO8859-9 | Latin5 (Turkish)
ISO8859-10 | Latin6 (Nordic)
ISO8859-11 | Thai
ISO8859-13 | Latin7 (Baltic Rim)
ISO8859-14 | Latin8 (Celtic)
ISO8859-15 | Latin9
ISO8859-16 | Latin10
CP1250 | MS Windows Codepage 1250.
CP1251 | MS Windows Codepage 1251.
CP1252 | MS Windows Codepage 1252.
CP1253 | MS Windows Codepage 1253.
CP1254 | MS Windows Codepage 1254.
CP1255 | MS Windows Codepage 1255.
CP1256 | MS Windows Codepage 1256.
CP1257 | MS Windows Codepage 1257.
CP1258 | MS Windows Codepage 1258.
KOI8-R | Cyrillic character set.
Multi-byte character set encodings
Name | Description
GB-EUC-H | EUC-CN encoding.
GB-EUC-V | Vertical writing version of GB-EUC-H.
GBK-EUC-H | Microsoft Code Page 936 (lfCharSet 0x86) GBK encoding.
GBK-EUC-V | Vertical writing version of GBK-EUC-H.
ETen-B5-H | Microsoft Code Page 950 (lfCharSet 0x88) Big Five character set with ETen extensions.
ETen-B5-V | Vertical writing version of ETen-B5-H.
90ms-RKSJ-H | Microsoft Code Page 932, JIS X 0208 character.
90ms-RKSJ-V | Vertical writing version of 90ms-RKSJ-V.
90msp-RKSJ-H | Microsoft Code Page 932, JIS X 0208 character (proportional).
EUC-H | JIS X 0208 character set, EUC-JP encoding.
EUC-V | Vertical writing version of EUC-H.
KSC-EUC-H | KS X 1001:1992 character set, EUC-KR encoding.
KSC-EUC-V | Vertical writing version of KSC-EUC-V.
KSCms-UHC-H | Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 character set plus 8822 additional hangul, Unified Hangul Code (UHC) encoding (proportional).
KSCms-UHC-HW-H | Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 character set plus 8822 additional hangul, Unified Hangul Code (UHC) encoding (fixed width).
KSCms-UHC-HW-V | Vertical writing version of KSCms-UHC-HW-H.
Builtin Fonts
HaruException
Builtin Fonts And Encodings


Builtin Fonts

These Base14 fonts are built-in into PDF and all viewers can display them. Using these fonts may decrease the size of the result file and make the processing faster, avoiding loading external fonts. However the fonts support only latin1 character set and you have to load external fonts if you need to use an other character set.

The Base14 fonts:

  • Courier

  • Courier-Bold

  • Courier-Oblique

  • Courier-BoldOblique

  • Helvetica

  • Helvetica-Bold

  • Helvetica-Oblique

  • Helvetica-BoldOblique

  • Times-Roman

  • Times-Bold

  • Times-Italic

  • Times-BoldItalic

  • Symbol

  • ZapfDingbats

Builtin Fonts And Encodings
Builtin Encodings
Builtin Fonts And Encodings


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
haru


Examples

Table of Contents

  • Basic PECL/haru example
Predefined Constants
Basic PECL/haru example
haru


Basic PECL/haru example

Example #1 Fancy "Hello world"

<?php

$doc = new HaruDoc;

$doc->setPageMode(HaruDoc::PAGE_MODE_USE_THUMBS); /* show thumbnails */

$page = $doc->addPage(); /* add page to the document */
$page->setSize(HaruPage::SIZE_A4, HaruPage::LANDSCAPE); /* set the page to use A4 landscape format */

$courier = $doc->getFont("Courier-Bold"); /* we'll use the bundled font a few lines below */

$page->setRGBStroke(0, 0, 0); /* set colors */
$page->setRGBFill(0.7, 0.8, 0.9);
$page->rectangle(150, 150, 550, 250); /* draw a rectangle */

$page->fillStroke(); /* fill and stroke it */

$page->setDash(array(3, 3), 0); /* set dash style for lines at this page */
$page->setFontAndSize($courier, 60); /* set font and size */

$page->setRGBStroke(0.5, 0.5, 0.1); /* set line color */
$page->setRGBFill(1, 1, 1); /* set filling color */

$page->setTextRenderingMode(HaruPage::FILL_THEN_STROKE); /* fill and stroke text */

/* print the text */
$page->beginText();
$page->textOut(210, 270, "Hello World!");
$page->endText();

$doc->save("/tmp/test.pdf"); /* save the document into a file */

?>

Open the result document in your favourite PDF viewer and you should see a light-blue rectangle and white "Hello World!" on it.

Examples
Builtin Fonts And Encodings
Examples


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/haru.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You need to install libharu first to be able to use PECL/haru. PECL/haru is tested with libharu 2.0.8, older versions might or might not work for you. PECL/haru also requires PHP 5.1.3 or newer.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
haru


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

HASH_HMAC (integer)
Optional flag for hash_init(). Indicates that the HMAC digest-keying algorithm should be applied to the current hashing context.
Resource Types
Hash Functions
Hash


Requirements

The Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2. It may be explicitly disabled by using the --disable-hash switch to configure. Earlier versions of PHP may incorporate the Hash extension by installing the » PECL module.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension defines a Hashing Context resource returned by hash_init().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Hash


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

htscanner Configure Options
Name | Default | Changeable | Changelog
htscanner.config_file | ".htscanner" | PHP_INI_SYSTEM |
htscanner.default_docroot | "/" | PHP_INI_SYSTEM |
htscanner.default_ttl | "300" | PHP_INI_SYSTEM |
htscanner."stop_on_error" | "Off" | PHP_INI_SYSTEM |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

htscanner.config_file string

Filename to use as configuration file.

htscanner.default_docroot string

Default document root.

htscanner.default_ttl int

Cache time out for the configuration data, in seconds.

htscanner.stop_on_error int

Stop on error (parse error, cannot set an ini setting).

Installation
Resource Types
Installing/Configuring


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/htscanner

Requirements
Runtime Configuration
Installing/Configuring


Requirements

PHP version 5.2.0 or greater.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension has no resource types defined.

Runtime Configuration
inclued
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
htscanner


Predefined Constants

This extension has no constants defined.

Resource Types
i18n Functions
i18n


Requirements

The Unicode Extension.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
i18n


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

InterBase configuration options
Name | Default | Changeable | Changelog
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.default_db | NULL | PHP_INI_SYSTEM | Available since PHP 5.0.0.
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ibase.allow_persistent boolean

Whether to allow persistent connections to Firebird/InterBase.

ibase.max_persistent integer

The maximum number of persistent Firebird/InterBase connections per process. New connections created with ibase_pconnect() will be non-persistent if this number would be exceeded.

ibase.max_links integer

The maximum number of Firebird/InterBase connections per process, including persistent connections.

ibase.default_db string

The default database to connect to when ibase_[p]connect() is called without specifying a database name. If this value is set and SQL safe mode is enabled, no other connections than to this database will be allowed.

ibase.default_user string

The user name to use when connecting to a database if no user name is specified.

ibase.default_password string

The password to use when connecting to a database if no password is specified.

ibase.default_charset string

The character set to use when connecting to a database if no character set is specified.

ibase.timestampformat string

ibase.dateformat string

ibase.timeformat string

These directives are used to set the date and time formats that are used when returning dates and times from a result set, or when binding arguments to date and time parameters.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The following constants can be passed to ibase_trans() to specify transaction behaviour.

Firebird/InterBase transaction flags
Constant | Description
IBASE_DEFAULT | The default transaction settings are to be used. This default is determined by the client library, which defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT in most cases.
IBASE_READ | Starts a read-only transaction.
IBASE_WRITE | Starts a read-write transaction.
IBASE_CONSISTENCY | Starts a transaction with the isolation level set to 'consistency', which means the transaction cannot read from tables that are being modified by other concurrent transactions.
IBASE_CONCURRENCY | Starts a transaction with the isolation level set to 'concurrency' (or 'snapshot'), which means the transaction has access to all tables, but cannot see changes that were committed by other transactions after the transaction was started.
IBASE_COMMITTED | Starts a transaction with the isolation level set to 'read committed'. This flag should be combined with either IBASE_REC_VERSION or IBASE_REC_NO_VERSION. This isolation level allows access to changes that were committed after the transaction was started. If IBASE_REC_NO_VERSION was specified, only the latest version of a row can be read. If IBASE_REC_VERSION was specified, a row can even be read when a modification to it is pending in a concurrent transaction.
IBASE_WAIT | Indicated that a transaction should wait and retry when a conflict occurs.
IBASE_NOWAIT | Indicated that a transaction should fail immediately when a conflict occurs.

The following constants can be passed to ibase_fetch_row(), ibase_fetch_assoc() or ibase_fetch_object() to specify fetch behaviour.

Firebird/InterBase fetch flags
Constant | Description
IBASE_FETCH_BLOBS | Also available as IBASE_TEXTfor backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers.
IBASE_FETCH_ARRAYS | Causes arrays to be fetched inline. Otherwise, array identifiers are returned. Array identifiers can only be used as arguments to INSERT operations, as no functions to handle array identifiers are currently available.
IBASE_UNIXTIME | Causes date and time fields not to be returned as strings, but as UNIX timestamps (the number of seconds since the epoch, which is 1-Jan-1970 0:00 UTC). Might be problematic if used with dates before 1970 on some systems.

The following constants are used to pass requests and options to the service
API functions (ibase_server_info(), ibase_db_info(),
ibase_backup(), ibase_restore()
and ibase_maintain_db()). Please refer to
the Firebird/InterBase manuals for the meaning of these options.

IBASE_BKP_IGNORE_CHECKSUMS
IBASE_BKP_IGNORE_LIMBO
IBASE_BKP_METADATA_ONLY
IBASE_BKP_NO_GARBAGE_COLLECT
IBASE_BKP_OLD_DESCRIPTIONS
IBASE_BKP_NON_TRANSPORTABLE
IBASE_BKP_CONVERT
Options to ibase_backup()
IBASE_RES_DEACTIVATE_IDX
IBASE_RES_NO_SHADOW
IBASE_RES_NO_VALIDITY
IBASE_RES_ONE_AT_A_TIME
IBASE_RES_REPLACE
IBASE_RES_CREATE
IBASE_RES_USE_ALL_SPACE
Options to ibase_restore()
IBASE_PRP_PAGE_BUFFERS
IBASE_PRP_SWEEP_INTERVAL
IBASE_PRP_SHUTDOWN_DB
IBASE_PRP_DENY_NEW_TRANSACTIONS
IBASE_PRP_DENY_NEW_ATTACHMENTS
IBASE_PRP_RESERVE_SPACE
IBASE_PRP_RES_USE_FULL
IBASE_PRP_RES
IBASE_PRP_WRITE_MODE
IBASE_PRP_WM_ASYNC
IBASE_PRP_WM_SYNC
IBASE_PRP_ACCESS_MODE
IBASE_PRP_AM_READONLY
IBASE_PRP_AM_READWRITE
IBASE_PRP_SET_SQL_DIALECT
IBASE_PRP_ACTIVATE
IBASE_PRP_DB_ONLINE
IBASE_RPR_CHECK_DB
IBASE_RPR_IGNORE_CHECKSUM
IBASE_RPR_KILL_SHADOWS
IBASE_RPR_MEND_DB
IBASE_RPR_VALIDATE_DB
IBASE_RPR_FULL
IBASE_RPR_SWEEP_DB
Options to ibase_maintain_db()
IBASE_STS_DATA_PAGES
IBASE_STS_DB_LOG
IBASE_STS_HDR_PAGES
IBASE_STS_IDX_PAGES
IBASE_STS_SYS_RELATIONS
Options to ibase_db_info()
IBASE_SVC_SERVER_VERSION
IBASE_SVC_IMPLEMENTATION
IBASE_SVC_GET_ENV
IBASE_SVC_GET_ENV_LOCK
IBASE_SVC_GET_ENV_MSG
IBASE_SVC_USER_DBPATH
IBASE_SVC_SVR_DB_INFO
IBASE_SVC_GET_USERS
Options to ibase_server_info()

Resource Types
Firebird/InterBase Functions
Firebird/InterBase


Installation

To enable InterBase support configure PHP --with-interbase[=DIR], where DIR is the InterBase base install directory, which defaults to /usr/interbase.

Note: Note to Win32 Users
In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: gds32.dll
In case you installed the InterBase database server on the same machine PHP is running on, you will have this DLL already. Therefore you don't need to worry because gds32.dll will already be in the PATH.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Firebird/InterBase


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

ibm_db2 Configure Options
Name | Default | Changeable | Changelog
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Available since ibm_db2 1.0.2.
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.8.0.

Here's a short explanation of the configuration directives.

ibm_db2.binmode integer

This option controls the mode used for converting to and from binary data in the PHP application.

  • 1 (DB2_BINARY)

  • 2 (DB2_CONVERT)

  • 3 (DB2_PASSTHRU)

ibm_db2.i5_all_pconnect integer

This option overrides i5 db2_connect() full open and close in the PHP application. When ibm_db2.i5_all_pconnect = 1, all db2 connections become persistent (db2_pconnect()). On i5/OS, db2_pconnect() performs dramatically better with lower machine stress over db2_connect(). This is a convenience override of db2_connect() to evoke db2_pconnect() without PHP source code changes.

  • 0 db2_connect() default full open and close

  • 1 db2_connect() override to db2_pconnect() for persistent connection only

ibm_db2.i5_allow_commit integer

This option controls the commit mode used for i5 schema collections in the PHP application.

  • 0 no commit (see i5_commit for override)

  • 1 allow commit (see i5_commit for override)

ibm_db2.i5_dbcs_alloc integer

This option controls the internal ibm_db2 allocation scheme for large DBCS column buffers.

  • 0 no expanded allocations (see i5_dbcs_alloc for override)

  • 1 use expanded allocations (see i5_dbcs_alloc for override)

ibm_db2.instance_name string

On Linux and UNIX operating systems, this option defines the name of the instance to use for cataloged database connections. If this option is set, its value overrides the DB2INSTANCE environment variable setting.

This option is ignored on Windows operating systems.

ibm_db2.i5_ignore_userid integer

This option overrides i5 db2_(p)connect userid and password in the PHP application. When ibm_db2.i5_ignore_userid = 1, all db2 (p)connections become null userid and null password. Therefore Apache jobs connect with the current profile (NOBODY). Use of this override is only for simple DB2 based websites that never require profile switching and therefore can avoid all overhead of server mode additional QSQSRVR jobs. This is a convenience override of db2_(p)connect to set the userid and password values to null without PHP source code changes. This override can be used in combination with ibm_db2.i5_all_pconnect = 1.

  • 0 db2_(p)connect with specified userid and password

  • 1 db2_(p)connect override connect with null userid and null password

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

DB2_BINARY (integer)
Specifies that binary data shall be returned as is. This is the default mode.
DB2_CONVERT (integer)
Specifies that binary data shall be converted to a hexadecimal encoding and returned as an ASCII string.
DB2_PASSTHRU (integer)
Specifies that binary data shall be converted to a NULL value.
DB2_SCROLLABLE (integer)
Specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.
DB2_FORWARD_ONLY (integer)
Specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.
DB2_PARAM_IN (integer)
Specifies the PHP variable should be bound as an IN parameter for a stored procedure.
DB2_PARAM_OUT (integer)
Specifies the PHP variable should be bound as an OUT parameter for a stored procedure.
DB2_PARAM_INOUT (integer)
Specifies the PHP variable should be bound as an INOUT parameter for a stored procedure.
DB2_PARAM_FILE (integer)
Specifies that the column should be bound directly to a file for input.
DB2_AUTOCOMMIT_ON (integer)
Specifies that autocommit should be turned on.
DB2_AUTOCOMMIT_OFF (integer)
Specifies that autocommit should be turned off.
DB2_DOUBLE (integer)
Specifies that the variable should be bound as a DOUBLE, FLOAT, or REAL data type.
DB2_LONG (integer)
Specifies that the variable should be bound as a SMALLINT, INTEGER, or BIGINT data type.
DB2_CHAR (integer)
Specifies that the variable should be bound as a CHAR or VARCHAR data type.
DB2_CASE_NATURAL (integer)
Specifies that column names will be returned in their natural case.
DB2_CASE_LOWER (integer)
Specifies that column names will be returned in lower case.
DB2_CASE_UPPER (integer)
Specifies that column names will be returned in upper case.
DB2_DEFERRED_PREPARE_ON (integer)
Specifies that deferred prepare should be turned on for the specified statement resource.
DB2_DEFERRED_PREPARE_OFF (integer)
Specifies that deferred prepare should be turned off for the specified statement resource.
Resource Types
IBM DB2 Functions
IBM DB2


Installation

To build the ibm_db2 extension, the DB2 application development header files and libraries must be installed on your system. DB2 does not install these by default, so you may have to return to your DB2 installer and add this option. The header files are included with the DB2 Application Development Client freely available for download from the IBM DB2 Universal Database » support site.

If you add the DB2 application development header files and libraries to a Linux or Unix operating system on which DB2 was already installed, you must issue the command db2iupdt -e to update the symbolic links to the header files and libraries in your DB2 instances.

ibm_db2 is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the ibm_db2 extension for PHP. Issue the configure command to point to the location of your DB2 header files and libraries as follows:

bash$ ./configure --with-IBM_DB2=/path/to/DB2
The configure command defaults to /opt/IBM/db2/V8.1.

Note: Note for IIS users
If you are using the ibm_db2 driver with Microsoft Internet Information Server (IIS) you may have to do the following:

  • Install DB2 with extended operating system security.
  • Add the PHP binary path to the PATH system environment variable (default C:\php\).
  • Create another system environment variable equal to the path where the PHP.INI file is located (eg: PHPRC = C:\php\).
  • Add the IUSR_COMPUTERNAME to the DB2USERS group.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To connect to IBM DB2 Universal Database for Linux, UNIX, and Windows, or IBM Cloudscape, or Apache Derby, you must install an IBM DB2 Universal Database client on the same computer on which you are running PHP. The extension has been developed and tested with DB2 Version 8.2.

To connect to IBM DB2 Universal Database for z/OS or iSeries, you also require IBM DB2 Connect or the equivalent DRDA gateway software.

Requirements on Linux or Unix

The user invoking the PHP executable or SAPI must specify the DB2 instance before accessing these functions. You can set the name of the DB2 instance in php.ini using the ibm_db2.instance_name configuration option, or you can source the DB2 instance profile before invoking the PHP executable.

If you created a DB2 instance named db2inst1 in /home/db2inst1/, for example, you can add the following line to php.ini:

ibm_db2.instance_name=db2inst1
If you do not set this option in php.ini, you must issue the following command to modify your environment variables to enable access to DB2:
bash$ source /home/db2inst1/sqllib/db2profile
To enable your PHP-enabled Web server to access these functions, you must either set the ibm_db2.instance_name configuration option in php.ini, or source the DB2 instance environment in your Web server start script (typically /etc/init.d/httpd or /etc/init.d/apache).

Installing/Configuring
Installation
Installing/Configuring


Resource Types

The ibm_db2 extension returns connection resources, statement resources, and result set resources.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
IBM DB2


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Iconv configuration options
Name | Default | Changeable | Changelog
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Warning

Some systems (like IBM AIX) use "ISO8859-1" instead of "ISO-8859-1" so this value has to be used in configuration options and function parameters.

Note: Configuration option iconv.input_encoding is currently not used for anything.

Installation
Resource Types
Installing/Configuring


Predefined Constants

Since PHP 4.3.0 it is possible to identify at runtime which iconv implementation is adopted by this extension.

iconv constants
Name | Type | Description
ICONV_IMPL | string | The implementation name
ICONV_VERSION | string | The implementation version

Note: Writing implementation-dependent scripts with these constants is strongly discouraged.

Since PHP 5.0.0, the following constants are also available:

iconv constants available since PHP 5.0.0
Name | Type | Description
ICONV_MIME_DECODE_STRICT | integer | A bitmask used for iconv_mime_decode()
ICONV_MIME_DECODE_CONTINUE_ON_ERROR | integer | A bitmask used for iconv_mime_decode()

Resource Types
iconv Functions
iconv


Installation

To use functions provided by this module, the PHP binary must be built with the following configure line: --with-iconv[=DIR].

Note: Note to Windows® Users
In order to enable this module on a Windows® environment, you need to put a DLL file named iconv.dll or iconv-1.3.dll (prior to 4.2.1) which is bundled with the PHP/Win32 binary package into a directory specified by the PATH environment variable or one of the system directories of your Windows® installation. This module is part of PHP as of PHP 5 thus iconv.dll and php_iconv.dll is not needed anymore.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You will need nothing if the system you are using is one of the recent POSIX-compliant systems because standard C libraries that are supplied in them must provide iconv facility. Otherwise, you have to get the » libiconv library installed in your system.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
iconv


Predefined Constants

Most of the id3 functions either let you specify or return a tag version. In order to specify the version please use on of these constants.

ID3_V1_0 (integer)
ID3_V1_0 is used if you are working with ID3 V1.0 tags. These tags may contain the fields title, artist, album, genre, year and comment.
ID3_V1_1 (integer)
ID3_V1_1 is used if you are working with ID3 V1.1 tags. These tags may all information contained in v1.0 tags plus the track number.
ID3_V2_1 (integer)
ID3_V2_1 is used if you are working with ID3 V2.1 tags.
ID3_V2_2 (integer)
ID3_V2_2 is used if you are working with ID3 V2.2 tags.
ID3_V2_3 (integer)
ID3_V2_3 is used if you are working with ID3 V2.3 tags.
ID3_V2_4 (integer)
ID3_V2_4 is used if you are working with ID3 V2.4 tags.
ID3_BEST (integer)
ID3_BEST is used if would like to let the id3 functions determine which tag version should be used.

Resource Types
ID3 Functions
ID3


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/id3.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
ID3


Returns a description for the picture in a picture frame

KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_AttachedPictureFrame::getMimeType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::getDescription

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame

Description

public string KTaglib_ID3v2_AttachedPictureFrame::getDescription ( void )

Returns the attached description for a picture frame in an ID3v2.x frame.

Return Values

Returns a description for the picture in a picture frame

KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_AttachedPictureFrame::getMimeType
KTaglib_ID3v2_AttachedPictureFrame


Returns the mime type of the picture

KTaglib_ID3v2_AttachedPictureFrame::getDescription
KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::getMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture

Description

public string KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( void )

Returns the mime type of the image represented by the attached picture frame.

Please notice that this method might return different types. While ID3v2.2 have a mime type that doesn't start with "image/", ID3v2.3 and v2.4 usually start with "image/". Therefore the method might return "image/png" for IDv2.3 frames and just "PNG" for ID3v2.2 frames.

Notice that even the frame is an attached picture, the mime type might not be set and therefore an empty string might be returned.

Return Values

Returns the mime type of the image represented by the attached picture frame.

KTaglib_ID3v2_AttachedPictureFrame::getDescription
KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame


Returns the type of the image

KTaglib_ID3v2_AttachedPictureFrame::getMimeType
KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::getType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image

Description

public int KTaglib_ID3v2_AttachedPictureFrame::getType ( void )

Returns the type of the image.

The ID3v2 specification allows an AttachedPictureFrame to set the type of an image. This can be e.g. FrontCover or FileIcon. Please refer to the KTagLib_ID3v2_AttachedPictureFrame class description for a list of available types.

Return Values

Returns the integer representation of the type.

KTaglib_ID3v2_AttachedPictureFrame::getMimeType
KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame


Saves the picture to a file

KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::savePicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file

Description

public bool KTaglib_ID3v2_AttachedPictureFrame::savePicture ( string $filename )

Saves the attached picture to the given filename.

Return Values

Returns true on success, otherwise false

KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame


Set's the mime type of the picture

KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame::setPicture
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::setMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture

Description

public string KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( string $type )

Sets the mime type of the image. This should in most cases be "image/png" or "image/jpeg".

KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame::setPicture
KTaglib_ID3v2_AttachedPictureFrame


Sets the frame picture to the given image

KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame::setType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::setPicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image

Description

public void KTaglib_ID3v2_AttachedPictureFrame::setPicture ( string $filename )

Sets the picture to the give image. The image is loaded from the given filename. Please note that the picture is not saved unless you call the save method of the corresponding file object.

Return Values

Returns true on success, otherwise false

KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame::setType
KTaglib_ID3v2_AttachedPictureFrame


Set the type of the image

KTaglib_ID3v2_AttachedPictureFrame::setPicture
oggvorbis
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::setType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image

Description

public void KTaglib_ID3v2_AttachedPictureFrame::setType ( int $type )

Sets the type of the image. This can be e.g. FrontCover or FileIcon. Please refer to the KTaglib_ID3v2_AttachedPictureFrame class description for a list of available types and their constant mappings.

KTaglib_ID3v2_AttachedPictureFrame::setPicture
oggvorbis
KTaglib_ID3v2_AttachedPictureFrame


Returns the size of the frame in bytes

KTaglib_ID3v2_Frame
KTaglib_ID3v2_Frame::__toString
KTaglib_ID3v2_Frame
PHP Manual

KTaglib_ID3v2_Frame::getSize

(0.0.1)

KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes

Description

public int KTaglib_ID3v2_Frame::getSize ( void )

Returns the size of the frame in bytes. Please refer to id3.org to see what ID3v2 frames are and how they are defined.

Return Values

Returns the size of the frame in bytes

KTaglib_ID3v2_Frame
KTaglib_ID3v2_Frame::__toString
KTaglib_ID3v2_Frame


Returns a string representation of the frame

KTaglib_ID3v2_Frame::getSize
KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_Frame
PHP Manual

KTaglib_ID3v2_Frame::__toString

(0.0.1)

KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame

Description

public string KTaglib_ID3v2_Frame::__toString ( void )

Returns a string representation of the frame. This might be just the frame id, but might contain more information. Please see the ktaglib documentation for more information

Return Values

Returns a string representation of the frame.

KTaglib_ID3v2_Frame::getSize
KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_Frame


Add a frame to the ID3v2 tag

KTaglib_ID3v2_Tag
KTaglib_ID3v2_Tag::getFrameList
KTaglib_ID3v2_Tag
PHP Manual

KTaglib_ID3v2_Tag::addFrame

(0.0.1)

KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag

Description

public bool KTaglib_ID3v2_Tag::addFrame ( KTagLib_ID3v2_Frame $frame )

Adds a frame to the ID3v2 tag. The frame must be a valid KTagLib_ID3v2_Frame object. To save the tag, the save function needs to be invoked.

Return Values

Returns true on success, otherwise false.

KTaglib_ID3v2_Tag
KTaglib_ID3v2_Tag::getFrameList
KTaglib_ID3v2_Tag


Returns an array of ID3v2 frames, associated with the ID3v2 tag

KTaglib_ID3v2_Tag::addFrame
KTaglib_ID3v2_Frame
KTaglib_ID3v2_Tag
PHP Manual

KTaglib_ID3v2_Tag::getFrameList

(0.0.1)

KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag

Description

public array KTaglib_ID3v2_Tag::getFrameList ( void )

Returns an array of ID3v2 frames, associated with the ID3v2 tag.

Return Values

Return an array of KTaglib_ID3v2_Frame objects

KTaglib_ID3v2_Tag::addFrame
KTaglib_ID3v2_Frame
KTaglib_ID3v2_Tag


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Note: Make sure that the Informix environment variables INFORMIXDIR and INFORMIXSERVER are available to the PHP ifx driver, and that the INFORMIX bin directory is in the PATH. Check this by running a script that contains a call to phpinfo() before you start testing. The phpinfo() output should list these environment variables. This is true for both CGI php and Apache mod_php. You may have to set these environment variables in your Apache startup script.
The Informix shared libraries should also be available to the loader (check LD_LIBRARY_PATH or ld.so.conf/ldconfig).

Note: Some notes on the use of BLOBs (TEXT and BYTE columns)
BLOBs are normally addressed by BLOB identifiers. Select queries return a "blob id" for every BYTE and TEXT column. You can get at the contents with "string_var = ifx_get_blob($blob_id);" if you choose to get the BLOBs in memory (with: "ifx_blobinfile(0);"). If you prefer to receive the content of BLOB columns in a file, use "ifx_blobinfile(1);", and "ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O to get at the blob contents.
For insert/update queries you must create these "blob id's" yourself with "ifx_create_blob();". You then plug the blob id's into an array, and replace the blob columns with a question mark (?) in the query string. For updates/inserts, you are responsible for setting the blob contents with ifx_update_blob().
The behaviour of BLOB columns can be altered by configuration variables that also can be set at runtime:
configuration variable: ifx.textasvarchar
configuration variable: ifx.byteasvarchar
runtime functions:
ifx_textasvarchar(0): use blob id's for select queries with TEXT columns
ifx_byteasvarchar(0): use blob id's for select queries with BYTE columns
ifx_textasvarchar(1): return TEXT columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.
ifx_byteasvarchar(1): return BYTE columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.
configuration variable: ifx.blobinfile
runtime function:
ifx_blobinfile_mode(0): return BYTE columns in memory, the blob id lets you get at the contents.
ifx_blobinfile_mode(1): return BYTE columns in a file, the blob id lets you get at the file name.
If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE columns in select queries just like normal (but rather long) VARCHAR fields. Since all strings are "counted" in PHP, this remains "binary safe". It is up to you to handle this correctly. The returned data can contain anything, you are responsible for the contents.
If you set ifx_blobinfile to 1, use the file name returned by ifx_get_blob(..) to get at the blob contents. Note that in this case YOU ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX when fetching the row. Every new row fetched will create new temporary files for every BYTE column.
The location of the temporary files can be influenced by the environment variable "blobdir", default is "." (the current directory). Something like: putenv(blobdir=tmpblob"); will ease the cleaning up of temp files accidentally left behind (their names all start with "blb").

Note: Automatically trimming "char" (SQLCHAR and SQLNCHAR) data
This can be set with the configuration variable
ifx.charasvarchar: if set to 1 trailing spaces will be automatically trimmed, to save you some "chopping".

Note: NULL values
The configuration variable ifx.nullformat (and the runtime function ifx_nullformat()) when set to TRUE will return NULL columns as the string "NULL", when set to FALSE they return the empty string. This allows you to discriminate between NULL columns and empty columns.

Informix configuration options
Name | Default | Changeable | Changelog
ifx.allow_persistent | "1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_persistent | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_links | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_host | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_user | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_password | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.blobinfile | "1" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.textasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.byteasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.charasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.nullformat | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ifx.allow_persistent boolean

Whether to allow persistent Informix connections.

ifx.max_persistent integer

The maximum number of persistent Informix connections per process.

ifx.max_links integer

The maximum number of Informix connections per process, including persistent connections.

ifx.default_host string

The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.blobinfile boolean

Set to TRUE if you want to return blob columns in a file, FALSE if you want them in memory. You can override the setting at runtime with ifx_blobinfile_mode().

ifx.textasvarchar boolean

Set to TRUE if you want to return TEXT columns as normal strings in select statements, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.byteasvarchar boolean

Set to TRUE if you want to return BYTE columns as normal strings in select queries, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.charasvarchar boolean

Set to TRUE if you want to trim trailing spaces from CHAR columns when fetching them.

ifx.nullformat boolean

Set to TRUE if you want to return NULL columns as the literal string "NULL", FALSE if you want them returned as the empty string "". You can override this setting at runtime with ifx_nullformat().

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

IFX_SCROLL (integer)
IFX_HOLD (integer)
IFX_LO_RDONLY (integer)
IFX_LO_WRONLY (integer)
IFX_LO_APPEND (integer)
IFX_LO_RDWR (integer)
IFX_LO_BUFFER (integer)
IFX_LO_NOBUFFER (integer)
Resource Types
Informix Functions
Informix


Installation

To be able to use the functions defined in this module you must compile your PHP interpreter using the configure line --with-informix[=DIR], where DIR is the Informix base install directory, defaults to nothing.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

Note: Configuration notes
You need a version of ESQL/C to compile the PHP Informix driver. ESQL/C versions from 7.2x on should be OK. ESQL/C is now part of the Informix Client SDK.
Make sure that the "INFORMIXDIR" variable has been set, and that $INFORMIXDIR/bin is in your PATH before you run the "configure" script.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Informix


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Image Configure Options
Name | Default | Changeable | Changelog
gd.jpeg_ignore_warning | "0" | PHP_INI_ALL | Available since PHP 5.1.3.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

gd.jpeg_ignore_warning bool

Ignore warnings created by jpeg2wbmp() and imagecreatefromjpeg()

See also the exif configuration directives.

Warning

Image functions are very memory intensive. Be sure to set memory_limit high enough.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GD_VERSION (string)
The GD version PHP was compiled against. (Available as of PHP 5.2.4)
GD_MAJOR_VERSION (integer)
The GD major version PHP was compiled against. (Available as of PHP 5.2.4)
GD_MINOR_VERSION (integer)
The GD minor version PHP was compiled against. (Available as of PHP 5.2.4)
GD_RELEASE_VERSION (integer)
The GD release version PHP was compiled against. (Available as of PHP 5.2.4)
GD_EXTRA_VERSION (string)
The GD "extra" version (beta/rc..) PHP was compiled against. (Available as of PHP 5.2.4)
GD_BUNDLED (integer)
When the bundled version of GD is used this is 1 otherwise its set to 0.
IMG_GIF (integer)
Used as a return value by imagetypes()
IMG_JPG (integer)
Used as a return value by imagetypes()
IMG_JPEG (integer)
Used as a return value by imagetypes()

Note: This constant has the same value as IMG_JPG

IMG_PNG (integer)
Used as a return value by imagetypes()
IMG_WBMP (integer)
Used as a return value by imagetypes()
IMG_XPM (integer)
Used as a return value by imagetypes()
IMG_COLOR_TILED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_STYLED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_BRUSHED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_STYLEDBRUSHED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_TRANSPARENT (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_ARC_ROUNDED (integer)
A style constant used by the imagefilledarc() function.

Note: This constant has the same value as IMG_ARC_PIE

IMG_ARC_PIE (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_CHORD (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_NOFILL (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_EDGED (integer)
A style constant used by the imagefilledarc() function.
IMG_GD2_RAW (integer)
A type constant used by the imagegd2() function.
IMG_GD2_COMPRESSED (integer)
A type constant used by the imagegd2() function.
IMG_EFFECT_REPLACE (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_ALPHABLEND (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_NORMAL (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_OVERLAY (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_FILTER_NEGATE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GRAYSCALE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_BRIGHTNESS (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_CONTRAST (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_COLORIZE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EDGEDETECT (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GAUSSIAN_BLUR (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SELECTIVE_BLUR (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EMBOSS (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_MEAN_REMOVAL (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SMOOTH (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_PIXELATE (integer)
Special GD filter used by the imagefilter() function. (Available as of PHP 5.3.0)
IMAGETYPE_GIF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG2000 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PNG (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PSD (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_BMP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_WBMP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_XBM (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_II (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_MM (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_IFF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JB2 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPC (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JP2 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPX (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWC (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_ICO (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. (Available as of PHP 5.3.0)
PNG_NO_FILTER (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_NONE (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_SUB (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_UP (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_AVG (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_PAETH (integer)
A special PNG filter, used by the imagepng() function.
PNG_ALL_FILTERS (integer)
A special PNG filter, used by the imagepng() function.
Resource Types
Examples
GD


Examples

Table of Contents

  • PNG creation with PHP
  • Adding watermarks to images using alpha channels
  • Using imagecopymerge to create a translucent watermark
Predefined Constants
PNG creation with PHP
GD


PNG creation with PHP

Examples
Adding watermarks to images using alpha channels
Examples
PHP Manual

Example #1 PNG creation with PHP

<?php

header("Content-type: image/png");
$string = $_GET['text'];
$im     = imagecreatefrompng("images/button1.png");
$orange = imagecolorallocate($im, 220, 210, 60);
$px     = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $orange);
imagepng($im);
imagedestroy($im);

?>

This example would be called from a page with a tag like: <img src="button.php?text=text">. The above button.php script then takes this "text" string and overlays it on top of a base image which in this case is "images/button1.png" and outputs the resulting image. This is a very convenient way to avoid having to draw new button images every time you want to change the text of a button. With this method they are dynamically generated.

Examples
Adding watermarks to images using alpha channels
Examples


Adding watermarks to images using alpha channels

PNG creation with PHP
Using imagecopymerge to create a translucent watermark
Examples
PHP Manual

Example #1 Adding watermarks to images using alpha channels

<?php
// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefrompng('stamp.png');
$im = imagecreatefromjpeg('photo.jpeg');

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Copy the stamp image onto our photo using the margin offsets and the photo
// width to calculate positioning of the stamp.
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Adding watermarks to images using alpha channels

This example is a common way to add watermarks and stamps to photos and copyrighted images. Note that the presence of an alpha channel in the stamp image as the text is anti-aliased. This is preserved during copying.

PNG creation with PHP
Using imagecopymerge to create a translucent watermark
Examples


Using imagecopymerge to create a translucent watermark

Adding watermarks to images using alpha channels
GD and Image Functions
Examples
PHP Manual

Example #1 Using imagecopymerge() to create a translucent watermark

<?php
// Load the stamp and the photo to apply the watermark to
$im = imagecreatefromjpeg('photo.jpeg');

// First we create our stamp image manually from GD
$stamp = imagecreatetruecolor(100, 70);
imagefilledrectangle($stamp, 0, 0, 99, 69, 0x0000FF);
imagefilledrectangle($stamp, 9, 9, 90, 60, 0xFFFFFF);
$im = imagecreatefromjpeg('photo.jpeg');
imagestring($stamp, 5, 20, 20, 'libGD', 0x0000FF);
imagestring($stamp, 3, 20, 40, '(c) 2007-9', 0x0000FF);

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Merge the stamp onto our photo with an opacity (transparency) of 50%
imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 50);

// Save the image to file and free memory
imagepng($im, 'photo_stamp.png');
imagedestroy($im);

?>
Using imagecopymerge() to create a translucent watermark

This example uses imagecopymerge() to merge the stamp with our original image. Using this we can set the opacity of our stamp - in our example we've set it to 50% opacity (another term for transparency). In practice this would be useful in copyright protection as semi-transparent watermarks are hard to remove yet allow viewers to see the image.

Adding watermarks to images using alpha channels
GD and Image Functions
Examples


Installation

To enable GD-support configure PHP --with-gd[=DIR], where DIR is the GD base install directory. To use the recommended bundled version of the GD library (which was first bundled in PHP 4.3.0), use the configure option --with-gd. GD library requires libpng and libjpeg to compile.

In Windows, you'll include the GD2 DLL php_gd2.dll as an extension in php.ini. The GD1 DLL php_gd.dll was removed in PHP 4.3.2. Also note that the preferred truecolor image functions, such as imagecreatetruecolor(), require GD2.

Enhance the capabilities of GD to handle more image formats by specifying the --with-XXXX configure switch to your PHP configure line.

Supported image formats
Image Format | Configure Switch
jpeg-6b | To enable support for jpeg-6b add --with-jpeg-dir=DIR.
png | To enable support for png add --with-png-dir=DIR. Note, libpng requires the zlib library, therefore add --with-zlib-dir[=DIR] to your configure line.
xpm | To enable support for xpm add --with-xpm-dir=DIR. If configure is not able to find the required libraries, you may add the path to your X11 libraries.

Note: When compiling PHP with libpng, you must use the same version that was linked with the GD library.

Enhance the capabilities of GD to deal with different fonts by specifying the --with-XXXX configure switch to your PHP configure line.

Supported font libraries
Font library | Configure Switch
FreeType 1.x | To enable support for FreeType 1.x add --with-ttf[=DIR].
FreeType 2 | To enable support for FreeType 2 add --with-freetype-dir=DIR.
T1lib | To enable support for T1lib (Postscript Type 1 fonts) add --with-t1lib[=DIR].
Native TrueType string function | To enable support for native TrueType string function add --enable-gd-native-ttf.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

If you have the GD library (available at » http://www.libgd.org/) you will also be able to create and manipulate images.

The format of images you are able to manipulate depend on the version of GD you install, and any other libraries GD might need to access those image formats. Versions of GD older than gd-1.6 support GIF format images, and do not support PNG, where versions greater than gd-1.6 and less than gd-2.0.28 support PNG, not GIF. GIF support was re-enabled in gd-2.0.28.

Note: Since PHP 4.3 there is a bundled version of the GD lib. This bundled version has some additional features like alpha blending, and should be used in preference to the external library since its codebase is better maintained and more stable.

Note: Support for GD 1.x has been removed as of PHP 6.0.0, which requires GD 2.0.33 or later.

You may wish to enhance GD to handle more image formats.

Supported image formats
Image format | Library to download | Notes
gif |  | Only supported in GD versions older than gd-1.6 and newer than gd-2.0.28. Read-only GIF support is available with PHP 4.3.0 and the bundled GD-library. Write support is available since PHP 4.3.9 and PHP 5.0.1.
jpeg-6b | » ftp://ftp.uu.net/graphics/jpeg/ | When building the jpeg-v6b library (prior to building PHP) you must use the --enable-shared option in the configure step. If you do not, you will receive an error saying libjpeg.(a|so) not found when you get to the configure step of building PHP.
png | » http://www.libpng.org/pub/png/libpng.html | Only supported in GD versions greater than gd-1.6.
xpm | » ftp://metalab.unc.edu/pub/Linux/libs/X/!INDEX.html | It's likely you have this library already available, if your system has an installed X-Environment.

You may wish to enhance GD to deal with different fonts. The following font libraries are supported:

Supported font libraries
Font library | Download | Notes
FreeType 1.x | » http://www.freetype.org/ | Support removed as of PHP 6.0.0
FreeType 2 | » http://www.freetype.org/ |
T1lib | » ftp://sunsite.unc.edu/pub/Linux/libs/graphics/) | Support for Postscript Type 1 fonts.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension defines two resource types: an image identifier and a font identifier.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
GD


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

COLOR_* constants

Colortype constants. These constants are mainly used with ImagickPixel.

imagick::COLOR_BLACK (integer)
Black color
imagick::COLOR_BLUE (integer)
Blue color
imagick::COLOR_CYAN (integer)
Cyan color
imagick::COLOR_GREEN (integer)
Green color
imagick::COLOR_RED (integer)
Red color
imagick::COLOR_YELLOW (integer)
Yellow color
imagick::COLOR_MAGENTA (integer)
Magenta color
imagick::COLOR_OPACITY (integer)
Color's opacity
imagick::COLOR_ALPHA (integer)
Color's alpha
imagick::COLOR_FUZZ (integer)
Color's fuzz
DISPOSE constants

Dispose type constants

imagick::DISPOSE_UNRECOGNIZED (integer)
Unrecognized dispose type
imagick::DISPOSE_UNDEFINED (integer)
Undefined dispose type
imagick::DISPOSE_NONE (integer)
No dispose type defined
imagick::DISPOSE_BACKGROUND (integer)
Dispose background
imagick::DISPOSE_PREVIOUS (integer)
Dispose previous
Composite Operator Constants
imagick::COMPOSITE_DEFAULT (integer)
The default composite operator
imagick::COMPOSITE_UNDEFINED (integer)
Undefined composite operator
imagick::COMPOSITE_NO (integer)
No composite operator defined
imagick::COMPOSITE_ADD (integer)
The result of image + image
imagick::COMPOSITE_ATOP (integer)
The result is the same shape as image, with composite image obscuring image where the image shapes overlap
imagick::COMPOSITE_BLEND (integer)
Blends the image
imagick::COMPOSITE_BUMPMAP (integer)
The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
imagick::COMPOSITE_CLEAR (integer)
Makes the target image transparent
imagick::COMPOSITE_COLORBURN (integer)
Darkens the destination image to reflect the source image
imagick::COMPOSITE_COLORDODGE (integer)
Brightens the destination image to reflect the source image
imagick::COMPOSITE_COLORIZE (integer)
Colorizes the target image using the composite image
imagick::COMPOSITE_COPYBLACK (integer)
Copies black from the source to target
imagick::COMPOSITE_COPYBLUE (integer)
Copies blue from the source to target
imagick::COMPOSITE_COPY (integer)
Copies the source image on the target image
imagick::COMPOSITE_COPYCYAN (integer)
Copies cyan from the source to target
imagick::COMPOSITE_COPYGREEN (integer)
Copies green from the source to target
imagick::COMPOSITE_COPYMAGENTA (integer)
Copies magenta from the source to target
imagick::COMPOSITE_COPYOPACITY (integer)
Copies opacity from the source to target
imagick::COMPOSITE_COPYRED (integer)
Copies red from the source to target
imagick::COMPOSITE_COPYYELLOW (integer)
Copies yellow from the source to target
imagick::COMPOSITE_DARKEN (integer)
Darkens the target image
imagick::COMPOSITE_DSTATOP (integer)
The part of the destination lying inside of the source is composited over the source and replaces the destination
imagick::COMPOSITE_DST (integer)
The target is left untouched
imagick::COMPOSITE_DSTIN (integer)
The parts inside the source replace the target
imagick::COMPOSITE_DSTOUT (integer)
The parts outside the source replace the target
imagick::COMPOSITE_DSTOVER (integer)
Target replaces the source
imagick::COMPOSITE_DIFFERENCE (integer)
Subtracts the darker of the two constituent colors from the lighter
imagick::COMPOSITE_DISPLACE (integer)
Shifts target image pixels as defined by the source
imagick::COMPOSITE_DISSOLVE (integer)
Dissolves the source in to the target
imagick::COMPOSITE_EXCLUSION (integer)
Produces an effect similar to that of imagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
imagick::COMPOSITE_HARDLIGHT (integer)
Multiplies or screens the colors, dependent on the source color value
imagick::COMPOSITE_HUE (integer)
Modifies the hue of the target as defined by source
imagick::COMPOSITE_IN (integer)
Composites source into the target
imagick::COMPOSITE_LIGHTEN (integer)
Lightens the target as defined by source
imagick::COMPOSITE_LUMINIZE (integer)
Luminizes the target as defined by source
imagick::COMPOSITE_MINUS (integer)
Substracts the source from the target
imagick::COMPOSITE_MODULATE (integer)
Modulates the target brightness, saturation and hue as defined by source
imagick::COMPOSITE_MULTIPLY (integer)
Multiplies the target to the source
imagick::COMPOSITE_OUT (integer)
Composites outer parts of the source on the target
imagick::COMPOSITE_OVER (integer)
Composites source over the target
imagick::COMPOSITE_OVERLAY (integer)
Overlays the source on the target
imagick::COMPOSITE_PLUS (integer)
Adds the source to the target
imagick::COMPOSITE_REPLACE (integer)
Replaces the target with the source
imagick::COMPOSITE_SATURATE (integer)
Saturates the target as defined by the source
imagick::COMPOSITE_SCREEN (integer)
The source and destination are complemented and then multiplied and then replace the destination
imagick::COMPOSITE_SOFTLIGHT (integer)
Darkens or lightens the colors, dependent on the source
imagick::COMPOSITE_SRCATOP (integer)
The part of the source lying inside of the destination is composited onto the destination
imagick::COMPOSITE_SRC (integer)
The source is copied to the destination
imagick::COMPOSITE_SRCIN (integer)
The part of the source lying inside of the destination replaces the destination
imagick::COMPOSITE_SRCOUT (integer)
The part of the source lying outside of the destination replaces the destination
imagick::COMPOSITE_SRCOVER (integer)
The source replaces the destination
imagick::COMPOSITE_SUBTRACT (integer)
Subtract the colors in the source image from the destination image
imagick::COMPOSITE_THRESHOLD (integer)
The source is composited on the target as defined by source threshold
imagick::COMPOSITE_XOR (integer)
The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source
MONTAGEMODE constants
imagick::MONTAGEMODE_FRAME (integer)
imagick::MONTAGEMODE_UNFRAME (integer)
imagick::MONTAGEMODE_CONCATENATE (integer)
STYLE constants
imagick::STYLE_NORMAL (integer)
imagick::STYLE_ITALIC (integer)
imagick::STYLE_OBLIQUE (integer)
imagick::STYLE_ANY (integer)
FILTER constants
imagick::FILTER_UNDEFINED (integer)
imagick::FILTER_POINT (integer)
imagick::FILTER_BOX (integer)
imagick::FILTER_TRIANGLE (integer)
imagick::FILTER_HERMITE (integer)
imagick::FILTER_HANNING (integer)
imagick::FILTER_HAMMING (integer)
imagick::FILTER_BLACKMAN (integer)
imagick::FILTER_GAUSSIAN (integer)
imagick::FILTER_QUADRATIC (integer)
imagick::FILTER_CUBIC (integer)
imagick::FILTER_CATROM (integer)
imagick::FILTER_MITCHELL (integer)
imagick::FILTER_LANCZOS (integer)
imagick::FILTER_BESSEL (integer)
imagick::FILTER_SINC (integer)
IMGTYPE constants
imagick::IMGTYPE_UNDEFINED (integer)
imagick::IMGTYPE_BILEVEL (integer)
imagick::IMGTYPE_GRAYSCALE (integer)
imagick::IMGTYPE_GRAYSCALEMATTE (integer)
imagick::IMGTYPE_PALETTE (integer)
imagick::IMGTYPE_PALETTEMATTE (integer)
imagick::IMGTYPE_TRUECOLOR (integer)
imagick::IMGTYPE_TRUECOLORMATTE (integer)
imagick::IMGTYPE_COLORSEPARATION (integer)
imagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
imagick::IMGTYPE_OPTIMIZE (integer)
RESOLUTION constants
imagick::RESOLUTION_UNDEFINED (integer)
imagick::RESOLUTION_PIXELSPERINCH (integer)
imagick::RESOLUTION_PIXELSPERCENTIMETER (integer)
COMPRESSION constants
imagick::COMPRESSION_UNDEFINED (integer)
imagick::COMPRESSION_NO (integer)
imagick::COMPRESSION_BZIP (integer)
imagick::COMPRESSION_FAX (integer)
imagick::COMPRESSION_GROUP4 (integer)
imagick::COMPRESSION_JPEG (integer)
imagick::COMPRESSION_JPEG2000 (integer)
imagick::COMPRESSION_LOSSLESSJPEG (integer)
imagick::COMPRESSION_LZW (integer)
imagick::COMPRESSION_RLE (integer)
imagick::COMPRESSION_ZIP (integer)
imagick::COMPRESSION_DXT1 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
imagick::COMPRESSION_DXT3 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
imagick::COMPRESSION_DXT5 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
PAINT constants
imagick::PAINT_POINT (integer)
imagick::PAINT_REPLACE (integer)
imagick::PAINT_FLOODFILL (integer)
imagick::PAINT_FILLTOBORDER (integer)
imagick::PAINT_RESET (integer)
GRAVITY constants
imagick::GRAVITY_NORTHWEST (integer)
imagick::GRAVITY_NORTH (integer)
imagick::GRAVITY_NORTHEAST (integer)
imagick::GRAVITY_WEST (integer)
imagick::GRAVITY_CENTER (integer)
imagick::GRAVITY_EAST (integer)
imagick::GRAVITY_SOUTHWEST (integer)
imagick::GRAVITY_SOUTH (integer)
imagick::GRAVITY_SOUTHEAST (integer)
STRETCH constants
imagick::STRETCH_NORMAL (integer)
imagick::STRETCH_ULTRACONDENSED (integer)
imagick::STRETCH_CONDENSED (integer)
imagick::STRETCH_SEMICONDENSED (integer)
imagick::STRETCH_SEMIEXPANDED (integer)
imagick::STRETCH_EXPANDED (integer)
imagick::STRETCH_EXTRAEXPANDED (integer)
imagick::STRETCH_ULTRAEXPANDED (integer)
imagick::STRETCH_ANY (integer)
ALIGN constants
imagick::ALIGN_UNDEFINED (integer)
imagick::ALIGN_LEFT (integer)
imagick::ALIGN_CENTER (integer)
imagick::ALIGN_RIGHT (integer)
DECORATION constants
imagick::DECORATION_NO (integer)
imagick::DECORATION_UNDERLINE (integer)
imagick::DECORATION_OVERLINE (integer)
imagick::DECORATION_LINETROUGH (integer)
NOISE constants
imagick::NOISE_UNIFORM (integer)
imagick::NOISE_GAUSSIAN (integer)
imagick::NOISE_MULTIPLICATIVEGAUSSIAN (integer)
imagick::NOISE_IMPULSE (integer)
imagick::NOISE_LAPLACIAN (integer)
imagick::NOISE_POISSON (integer)
imagick::NOISE_RANDOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
CHANNEL constants
imagick::CHANNEL_UNDEFINED (integer)
imagick::CHANNEL_RED (integer)
imagick::CHANNEL_GRAY (integer)
imagick::CHANNEL_CYAN (integer)
imagick::CHANNEL_GREEN (integer)
imagick::CHANNEL_MAGENTA (integer)
imagick::CHANNEL_BLUE (integer)
imagick::CHANNEL_YELLOW (integer)
imagick::CHANNEL_ALPHA (integer)
imagick::CHANNEL_OPACITY (integer)
imagick::CHANNEL_MATTE (integer)
imagick::CHANNEL_BLACK (integer)
imagick::CHANNEL_INDEX (integer)
imagick::CHANNEL_ALL (integer)
imagick::CHANNEL_DEFAULT (integer)
METRIC constants
imagick::METRIC_UNDEFINED (integer)
imagick::METRIC_MEANABSOLUTEERROR (integer)
imagick::METRIC_MEANSQUAREERROR (integer)
imagick::METRIC_PEAKABSOLUTEERROR (integer)
imagick::METRIC_PEAKSIGNALTONOISERATIO (integer)
imagick::METRIC_ROOTMEANSQUAREDERROR (integer)
PIXEL constants
imagick::PIXEL_CHAR (integer)
imagick::PIXEL_DOUBLE (integer)
imagick::PIXEL_FLOAT (integer)
imagick::PIXEL_INTEGER (integer)
imagick::PIXEL_LONG (integer)
imagick::PIXEL_QUANTUM (integer)
imagick::PIXEL_SHORT (integer)
EVALUATE constants
imagick::EVALUATE_UNDEFINED (integer)
imagick::EVALUATE_ADD (integer)
imagick::EVALUATE_AND (integer)
imagick::EVALUATE_DIVIDE (integer)
imagick::EVALUATE_LEFTSHIFT (integer)
imagick::EVALUATE_MAX (integer)
imagick::EVALUATE_MIN (integer)
imagick::EVALUATE_MULTIPLY (integer)
imagick::EVALUATE_OR (integer)
imagick::EVALUATE_RIGHTSHIFT (integer)
imagick::EVALUATE_SET (integer)
imagick::EVALUATE_SUBTRACT (integer)
imagick::EVALUATE_XOR (integer)
imagick::EVALUATE_POW (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_LOG (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLD (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDBLACK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDWHITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_GAUSSIANNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_IMPULSENOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_LAPLACIANNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_MULTIPLICATIVENOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_POISSONNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_UNIFORMNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_COSINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_SINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_ADDMODULUS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
COLORSPACE constants
imagick::COLORSPACE_UNDEFINED (integer)
imagick::COLORSPACE_RGB (integer)
imagick::COLORSPACE_GRAY (integer)
imagick::COLORSPACE_TRANSPARENT (integer)
imagick::COLORSPACE_OHTA (integer)
imagick::COLORSPACE_LAB (integer)
imagick::COLORSPACE_XYZ (integer)
imagick::COLORSPACE_YCBCR (integer)
imagick::COLORSPACE_YCC (integer)
imagick::COLORSPACE_YIQ (integer)
imagick::COLORSPACE_YPBPR (integer)
imagick::COLORSPACE_YUV (integer)
imagick::COLORSPACE_CMYK (integer)
imagick::COLORSPACE_SRGB (integer)
imagick::COLORSPACE_HSB (integer)
imagick::COLORSPACE_HSL (integer)
imagick::COLORSPACE_HWB (integer)
imagick::COLORSPACE_REC601LUMA (integer)
imagick::COLORSPACE_REC709LUMA (integer)
imagick::COLORSPACE_LOG (integer)
imagick::COLORSPACE_CMY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
VIRTUALPIXELMETHOD constants
imagick::VIRTUALPIXELMETHOD_UNDEFINED (integer)
imagick::VIRTUALPIXELMETHOD_BACKGROUND (integer)
imagick::VIRTUALPIXELMETHOD_CONSTANT (integer)
imagick::VIRTUALPIXELMETHOD_EDGE (integer)
imagick::VIRTUALPIXELMETHOD_MIRROR (integer)
imagick::VIRTUALPIXELMETHOD_TILE (integer)
imagick::VIRTUALPIXELMETHOD_TRANSPARENT (integer)
imagick::VIRTUALPIXELMETHOD_MASK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_BLACK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_GRAY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_WHITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_HORIZONTALTILE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher.
imagick::VIRTUALPIXELMETHOD_VERTICALTILE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher.
PREVIEW constants
imagick::PREVIEW_UNDEFINED (integer)
imagick::PREVIEW_ROTATE (integer)
imagick::PREVIEW_SHEAR (integer)
imagick::PREVIEW_ROLL (integer)
imagick::PREVIEW_HUE (integer)
imagick::PREVIEW_SATURATION (integer)
imagick::PREVIEW_BRIGHTNESS (integer)
imagick::PREVIEW_GAMMA (integer)
imagick::PREVIEW_SPIFF (integer)
imagick::PREVIEW_DULL (integer)
imagick::PREVIEW_GRAYSCALE (integer)
imagick::PREVIEW_QUANTIZE (integer)
imagick::PREVIEW_DESPECKLE (integer)
imagick::PREVIEW_REDUCENOISE (integer)
imagick::PREVIEW_ADDNOISE (integer)
imagick::PREVIEW_SHARPEN (integer)
imagick::PREVIEW_BLUR (integer)
imagick::PREVIEW_THRESHOLD (integer)
imagick::PREVIEW_EDGEDETECT (integer)
imagick::PREVIEW_SPREAD (integer)
imagick::PREVIEW_SOLARIZE (integer)
imagick::PREVIEW_SHADE (integer)
imagick::PREVIEW_RAISE (integer)
imagick::PREVIEW_SEGMENT (integer)
imagick::PREVIEW_SWIRL (integer)
imagick::PREVIEW_IMPLODE (integer)
imagick::PREVIEW_WAVE (integer)
imagick::PREVIEW_OILPAINT (integer)
imagick::PREVIEW_CHARCOALDRAWING (integer)
imagick::PREVIEW_JPEG (integer)
RENDERINGINTENT constants
imagick::RENDERINGINTENT_UNDEFINED (integer)
imagick::RENDERINGINTENT_SATURATION (integer)
imagick::RENDERINGINTENT_PERCEPTUAL (integer)
imagick::RENDERINGINTENT_ABSOLUTE (integer)
imagick::RENDERINGINTENT_RELATIVE (integer)
INTERLACE constants
imagick::INTERLACE_UNDEFINED (integer)
imagick::INTERLACE_NO (integer)
imagick::INTERLACE_LINE (integer)
imagick::INTERLACE_PLANE (integer)
imagick::INTERLACE_PARTITION (integer)
imagick::INTERLACE_GIF (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher.
imagick::INTERLACE_JPEG (integer)
imagick::INTERLACE_PNG (integer)
FILLRULE constants
imagick::FILLRULE_UNDEFINED (integer)
imagick::FILLRULE_EVENODD (integer)
imagick::FILLRULE_NONZERO (integer)
PATHUNITS constants
imagick::PATHUNITS_UNDEFINED (integer)
imagick::PATHUNITS_USERSPACE (integer)
imagick::PATHUNITS_USERSPACEONUSE (integer)
imagick::PATHUNITS_OBJECTBOUNDINGBOX (integer)
LINECAP constants
imagick::LINECAP_UNDEFINED (integer)
imagick::LINECAP_BUTT (integer)
imagick::LINECAP_ROUND (integer)
imagick::LINECAP_SQUARE (integer)
LINEJOIN constants
imagick::LINEJOIN_UNDEFINED (integer)
imagick::LINEJOIN_MITER (integer)
imagick::LINEJOIN_ROUND (integer)
imagick::LINEJOIN_BEVEL (integer)
RESOURCETYPE constants
imagick::RESOURCETYPE_UNDEFINED (integer)
imagick::RESOURCETYPE_AREA (integer)
imagick::RESOURCETYPE_DISK (integer)
imagick::RESOURCETYPE_FILE (integer)
imagick::RESOURCETYPE_MAP (integer)
imagick::RESOURCETYPE_MEMORY (integer)
LAYERMETHOD constants
imagick::LAYERMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COALESCE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREANY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPARECLEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREOVERLAY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_DISPOSE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEPLUS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEIMAGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_OPTIMIZETRANS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEDUPS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEZERO (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_COMPOSITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_MERGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
imagick::LAYERMETHOD_FLATTEN (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
imagick::LAYERMETHOD_MOSAIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
ORIENTATION constants
imagick::ORIENTATION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_TOPLEFT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_TOPRIGHT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMRIGHT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMLEFT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_LEFTTOP (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_RIGHTTOP (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_RIGHTBOTTOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_LEFTBOTTOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
DISTORTION constants
imagick::DISTORTION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_AFFINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_AFFINEPROJECTION (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_ARC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVEPROJECTION (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_SCALEROTATETRANSLATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_POLAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_DEPOLAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_BARREL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_BARRELINVERSE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_SHEPARDS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_SENTINEL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
ALPHACHANNEL constants
imagick::ALPHACHANNEL_ACTIVATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_DEACTIVATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_RESET (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_SET (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_COPY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_EXTRACT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_OPAQUE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_SHAPE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_TRANSPARENT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
SPARSECOLORMETHOD constants
imagick::SPARSECOLORMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BARYCENTRIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_SPEPARDS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_VORONOI (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
FUNCTION constants
imagick::FUNCTION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
imagick::FUNCTION_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
imagick::FUNCTION_SINUSOID (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
INTERPOLATE constants
imagick::INTERPOLATE_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_AVERAGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_BICUBIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_FILTER (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_INTEGER (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_MESH (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_NEARESTNEIGHBOR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_SPLINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher.
DITHERMETHOD constants
imagick::DITHERMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_NO (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_RIEMERSMA (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_FLOYDSTEINBERG (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
Resource Types
Examples
ImageMagick


Removes skew from the image

Imagick::deconstructImages
Imagick::despeckleImage
The Imagick class
PHP Manual

Imagick::deskewImage

(No version information available, might only be in SVN)

Imagick::deskewImage — Removes skew from the image

Description

public void Imagick::deskewImage ( float $threshold )

This method can be used to remove skew from for example scanned images where the paper was not properly placed on the scanning surface. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

Parameters

threshold

Deskew threshold

Return Values

Imagick::deconstructImages
Imagick::despeckleImage
The Imagick class


Examples
ImageMagick
PHP Manual

Examples

Table of Contents

  • Examples
Predefined Constants
Examples
ImageMagick


Examples
The Imagick class
Examples
PHP Manual

Examples

Imagick makes image manipulation in PHP extremely easy through an OO interface. Here is a quick example on how to make a thumbnail:

Example #1 Creating a thumbnail in Imagick

<?php

header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');

// If 0 is provided as a width or height parameter,
// aspect ratio is maintained
$image->thumbnailImage(100, 0);

echo $image;

?>

Using SPL and other OO features supported in Imagick, it can be simple to resize all files in a directory (useful for batch resizing large digital camera images to be web viewable). Here we use resize, as we might want to retain certain meta-data:

Example #2 Make a thumbnail of all JPG files in a directory

<?php

$images = new Imagick(glob('images/*.JPG'));

foreach($images as $image) {

    // Providing 0 forces thumbnailImage to maintain aspect ratio
    $image->thumbnailImage(1024,0);

}

$images->writeImages();

?>

This is an example of creating a reflection of an image. The reflection is created by flipping the image and overlaying a gradient on it. Then both, the original image and the reflection is overlayed on a canvas.

Example #3 Creating a reflection of an image

<?php
/* Read the image */
$im = new Imagick("test.png");

/* Thumbnail the image */
$im->thumbnailImage(200, null);

/* Create a border for the image */
$im->borderImage(new ImagickPixel("white"), 5, 5);

/* Clone the image and flip it */
$reflection = $im->clone();
$reflection->flipImage();

/* Create gradient. It will be overlayd on the reflection */
$gradient = new Imagick();

/* Gradient needs to be large enough for the image and the borders */
$gradient->newPseudoImage($reflection->getImageWidth() + 10, $reflection->getImageHeight() + 10, "gradient:transparent-black");

/* Composite the gradient on the reflection */
$reflection->compositeImage($gradient, imagick::COMPOSITE_OVER, 0, 0);

/* Add some opacity. Requires ImageMagick 6.2.9 or later */
$reflection->setImageOpacity( 0.3 );

/* Create an empty canvas */
$canvas = new Imagick();

/* Canvas needs to be large enough to hold the both images */
$width = $im->getImageWidth() + 40;
$height = ($im->getImageHeight() * 2) + 30;
$canvas->newImage($width, $height, new ImagickPixel("black"));
$canvas->setImageFormat("png");

/* Composite the original image and the reflection on the canvas */
$canvas->compositeImage($im, imagick::COMPOSITE_OVER, 20, 10);
$canvas->compositeImage($reflection, imagick::COMPOSITE_OVER, 20, $im->getImageHeight() + 10);

/* Output the image*/
header("Content-Type: image/png");
echo $canvas;
?>

The above example will output something similar to:

Output of example : Creating a reflection of an image

This example illustrates how to use fill patterns during drawing.

Example #4 Filling text with gradient

<?php

/* Create a new imagick object */
$im = new Imagick();

/* Create new image. This will be used as fill pattern */
$im->newPseudoImage(50, 50, "gradient:red-black");

/* Create imagickdraw object */
$draw = new ImagickDraw();

/* Start a new pattern called "gradient" */
$draw->pushPattern('gradient', 0, 0, 50, 50);

/* Composite the gradient on the pattern */
$draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);

/* Close the pattern */
$draw->popPattern();

/* Use the pattern called "gradient" as the fill */
$draw->setFillPatternURL('#gradient');

/* Set font size to 52 */
$draw->setFontSize(52);

/* Annotate some text */
$draw->annotation(20, 50, "Hello World!");

/* Create a new canvas object and a white image */
$canvas = new Imagick();
$canvas->newImage(350, 70, "white");

/* Draw the ImagickDraw on to the canvas */
$canvas->drawImage($draw);

/* 1px black border around the image */
$canvas->borderImage('black', 1, 1);

/* Set the format to PNG */
$canvas->setImageFormat('png');

/* Output the image */
header("Content-Type: image/png");
echo $canvas;
?>

The above example will output something similar to:

Output of example : Filling text with gradient

Working with animated GIF images

Example #5 Read in GIF image and resize all frames

<?php

/* Create a new imagick object and read in GIF */
$im = new Imagick("example.gif");

/* Resize all frames */
foreach ($im as $frame) {
    /* 50x50 frames */
    $frame->thumbnailImage(50, 50);

    /* Set the virtual canvas to correct size */
    $frame->setImagePage(50, 50, 0, 0);
}

/* Notice writeImages instead of writeImage */
$im->writeImages("example_small.gif", true);
?>

Examples
The Imagick class
Examples
PHP Manual


Exports raw image pixels

Imagick::evaluateImage
Imagick::extentImage
The Imagick class
PHP Manual

Imagick::exportImagePixels

(No version information available, might only be in SVN)

Imagick::exportImagePixels — Exports raw image pixels

Description

public array Imagick::exportImagePixels ( int $x , int $y , int $width , int $height , string $map , int $STORAGE )

Exports image pixels into an array. The map defines the ordering of the exported pixels. The size of the returned array is width * height * strlen(map). This method is available if Imagick has been compiled against ImageMagick version 6.4.7 or newer.

Parameters

x

X-coordinate of the exported area

y

Y-coordinate of the exported area

width

Width of the exported aread

height

Height of the exported area

map

Ordering of the exported pixels. For example "RGB". Valid characters for the map are R, G, B, A, O, C, Y, M, K, I and P.

STORAGE

Refer to this list of pixel type constants

Examples

Example #1 Using Imagick::exportImagePixels()

Export image pixels into an array

<?php

/* Create new object */
$im = new Imagick();

/* Create new image */
$im->newPseudoImage(0, 0, "magick:rose");

/* Export the image pixels */
$pixels = $im->exportImagePixels(10, 10, 2, 2, "RGB", Imagick::PIXEL_CHAR);

/* Output */
var_dump($pixels);
?>

The above example will output:

array(12) {
  [0]=>
  int(72)
  [1]=>
  int(64)
  [2]=>
  int(57)
  [3]=>
  int(69)
  [4]=>
  int(59)
  [5]=>
  int(43)
  [6]=>
  int(124)
  [7]=>
  int(120)
  [8]=>
  int(-96)
  [9]=>
  int(91)
  [10]=>
  int(84)
  [11]=>
  int(111)
}

Return Values

Returns an array containing the pixels values.

Errors/Exceptions

Throws ImagickException on error.

Imagick::evaluateImage
Imagick::extentImage
The Imagick class


Applies a function on the image

Imagick::frameImage
Imagick::fxImage
The Imagick class
PHP Manual

Imagick::functionImage

(No version information available, might only be in SVN)

Imagick::functionImage — Applies a function on the image

Description

public boolean Imagick::functionImage ( integer $function , array $arguments )

Applies an arithmetic, relational, or logical expression to an image. Use these operators to create lighter or darker versions of an image, to increase or decrease contrast in an image, or to negate the image colors. This method is available if Imagick has been compiled against ImageMagick version 6.4.9 or newer.

Parameters

function

Refer to this list of function constants

arguments

Array of arguments to pass to this function.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::frameImage
Imagick::fxImage
The Imagick class


The getImageChannelKurtosis purpose

Imagick::getImageChannelExtrema
Imagick::getImageChannelMean
The Imagick class
PHP Manual

Imagick::getImageChannelKurtosis

(No version information available, might only be in SVN)

Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose

Description

public array Imagick::getImageChannelKurtosis ([ int $channel = Imagick::CHANNEL_DEFAULT ] )

Get the kurtosis and skewness of a specific channel. This method is available if Imagick has been compiled against ImageMagick version 6.4.9 or newer.

Parameters

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns an array with kurtosis and skewness members.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getImageChannelExtrema
Imagick::getImageChannelMean
The Imagick class


Replaces colors in the image

Imagick::getVersion
Imagick::hasNextImage
The Imagick class
PHP Manual

Imagick::haldClutImage

(No version information available, might only be in SVN)

Imagick::haldClutImage — Replaces colors in the image

Description

public boolean Imagick::haldClutImage ( Imagick $clut [, int $channel ] )

Replaces colors in the image using a Hald lookup table. Hald images can be created using HALD color coder.

Parameters

clut

Imagick object containing the Hald lookup image.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::getVersion
Imagick::hasNextImage
The Imagick class


Imports image pixels

Imagick::implodeImage
Imagick::labelImage
The Imagick class
PHP Manual

Imagick::importImagePixels

(No version information available, might only be in SVN)

Imagick::importImagePixels — Imports image pixels

Description

public bool Imagick::importImagePixels ( int $x , int $y , int $width , int $height , string $map , int $storage , array $pixels )

Imports pixels from an array into an image. The map is usually 'RGB'. This method imposes the following constraints for the parameters: amount of pixels in the array must match width x height x length of the map. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

Parameters

x

The image x position

y

The image y position

width

The image width

height

The image height

map

Map of pixel ordering as a string. This can be for example RGB. The value can be any combination or order of R = red, G = green, B = blue, A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan, Y = yellow, M = magenta, K = black, I = intensity (for grayscale), P = pad.

storage

The pixel storage method. Refer to this list of pixel constants.

pixels

The array of pixels

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Imagick::importImagePixels example

<?php

/* Generate array of pixels. 2000 pixels per color stripe */
$count = 2000 * 3;

$pixels =
   array_merge(array_pad(array(), $count, 0),
               array_pad(array(), $count, 255),
               array_pad(array(), $count, 0),
               array_pad(array(), $count, 255),
               array_pad(array(), $count, 0));

/* Width and height. The area is amount of pixels divided
   by three. Three comes from 'RGB', three values per pixel */
$width = $height = pow((count($pixels) / 3), 0.5);

/* Create empty image */
$im = new Imagick();
$im->newImage($width, $height, 'gray');

/* Import the pixels into image.
   width * height * strlen("RGB") must match count($pixels) */
$im->importImagePixels(0, 0, $width, $height, "RGB", Imagick::PIXEL_CHAR, $pixels);

/* output as jpeg image */
$im->setImageFormat('jpg');
header("Content-Type: image/jpg");
echo $im;

?>

The above example will output something similar to:

Output of example : Imagick::importImagePixels()

Imagick::implodeImage
Imagick::labelImage
The Imagick class


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/imagick.

Note: The official name of this extension is imagick.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Remaps image colors

Imagick::reduceNoiseImage
Imagick::removeImage
The Imagick class
PHP Manual

Imagick::remapImage

(No version information available, might only be in SVN)

Imagick::remapImage — Remaps image colors

Description

public void Imagick::remapImage ( Imagick $replacement , int $DITHER )

Replaces colors an image with those defined by replacement . The colors are replaced with the closest possible color. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

Parameters

replacement

An Imagick object containing the replacement colors

DITHER

Refer to this list of dither method constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::reduceNoiseImage
Imagick::removeImage
The Imagick class


Requirements

Installation requirements on Windows

Version information does not differ from that above. There are binaries available from http://www.imagemagick.org/ so that you can load this extension on Windows without need for a compiler.

Installation requirements on other platforms

PHP >= 5.1.3 and ImageMagick >= 6.2.4 is required. The amount of formats supported is by Imagick is entirely dependent upon the amount of formats supported by your ImageMagick installation. For example, Imagemagick requires ghostscript to conduct PDF operations.

Installing/Configuring
Installation
Installing/Configuring


Segments an image

Imagick::scaleImage
Imagick::separateImageChannel
The Imagick class
PHP Manual

Imagick::segmentImage

(No version information available, might only be in SVN)

Imagick::segmentImage — Segments an image

Description

public void Imagick::segmentImage ( int $COLORSPACE , float $cluster_threshold , float $smooth_threshold [, boolean $verbose ] )

Analyses the image and identifies units that are similar. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

Parameters

COLORSPACE

One of the COLORSPACE constants.

cluster_threshold

A percentage describing minimum number of pixels contained in hexedra before it is considered valid.

smooth_threshold

Eliminates noise from the histogram.

verbose

Whether to output detailed information about recognised classes.

Return Values

Imagick::scaleImage
Imagick::separateImageChannel
The Imagick class


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
ImageMagick


Interpolates colors

Imagick::solarizeImage
Imagick::spliceImage
The Imagick class
PHP Manual

Imagick::sparseColorImage

(No version information available, might only be in SVN)

Imagick::sparseColorImage — Interpolates colors

Description

public boolean Imagick::sparseColorImage ( int $SPARSE_METHOD , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Given the arguments array containing numeric values this method interpolates the colors found at those coordinates across the whole image using sparse_method . This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer.

Parameters

SPARSE_METHOD

Refer to this list of sparse method constants

arguments

An array containing the coordinates. The array is in format array(1,1, 2,45)

CHANNEL

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Imagick::solarizeImage
Imagick::spliceImage
The Imagick class


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

NIL (integer)
OP_DEBUG (integer)
OP_READONLY (integer)
Open mailbox read-only
OP_ANONYMOUS (integer)
Don't use or update a .newsrc for news (NNTP only)
OP_SHORTCACHE (integer)
OP_SILENT (integer)
OP_PROTOTYPE (integer)
OP_HALFOPEN (integer)
For IMAP and NNTP names, open a connection but don't open a mailbox.
OP_EXPUNGE (integer)
OP_SECURE (integer)
CL_EXPUNGE (integer)
silently expunge the mailbox before closing when calling imap_close()
FT_UID (integer)
The parameter is a UID
FT_PEEK (integer)
Do not set the \Seen flag if not already set
FT_NOT (integer)
FT_INTERNAL (integer)
The return string is in internal format, will not canonicalize to CRLF.
FT_PREFETCHTEXT (integer)
ST_UID (integer)
The sequence argument contains UIDs instead of sequence numbers
ST_SILENT (integer)
ST_SET (integer)
CP_UID (integer)
the sequence numbers contain UIDS
CP_MOVE (integer)
Delete the messages from the current mailbox after copying with imap_mail_copy()
SE_UID (integer)
Return UIDs instead of sequence numbers
SE_FREE (integer)
SE_NOPREFETCH (integer)
Don't prefetch searched messages
SO_FREE (integer)
SO_NOSERVER (integer)
SA_MESSAGES (integer)
SA_RECENT (integer)
SA_UNSEEN (integer)
SA_UIDNEXT (integer)
SA_UIDVALIDITY (integer)
SA_ALL (integer)
LATT_NOINFERIORS (integer)
This mailbox has no "children" (there are no mailboxes below this one).
LATT_NOSELECT (integer)
This is only a container, not a mailbox - you cannot open it.
LATT_MARKED (integer)
This mailbox is marked. Only used by UW-IMAPD.
LATT_UNMARKED (integer)
This mailbox is not marked. Only used by UW-IMAPD.
SORTDATE (integer)
Sort criteria for imap_sort(): message Date
SORTARRIVAL (integer)
Sort criteria for imap_sort(): arrival date
SORTFROM (integer)
Sort criteria for imap_sort(): mailbox in first From address
SORTSUBJECT (integer)
Sort criteria for imap_sort(): message subject
SORTTO (integer)
Sort criteria for imap_sort(): mailbox in first To address
SORTCC (integer)
Sort criteria for imap_sort(): mailbox in first cc address
SORTSIZE (integer)
Sort criteria for imap_sort(): size of message in octets
TYPETEXT (integer)
TYPEMULTIPART (integer)
TYPEMESSAGE (integer)
TYPEAPPLICATION (integer)
TYPEAUDIO (integer)
TYPEIMAGE (integer)
TYPEVIDEO (integer)
TYPEOTHER (integer)
ENC7BIT (integer)
ENC8BIT (integer)
ENCBINARY (integer)
ENCBASE64 (integer)
ENCQUOTEDPRINTABLE (integer)
ENCOTHER (integer)
IMAP_OPENTIMEOUT (integer)
IMAP_READTIMEOUT (integer)
IMAP_WRITETIMEOUT (integer)
IMAP_CLOSETIMEOUT (integer)
LATT_REFERRAL (integer)
LATT_HASCHILDREN (integer)
LATT_HASNOCHILDREN (integer)
TYPEMODEL (integer)
IMAP_GC_ELT (integer)
Garbage collector, clear message cache elements.
IMAP_GC_ENV (integer)
Garbage collector, clear envelopes and bodies.
IMAP_GC_TEXTS (integer)
Garbage collector, clear texts.
Resource Types
IMAP Functions
IMAP


Installation

To get these functions to work, you have to compile PHP with --with-imap[=DIR], where DIR is the c-client install prefix. From our example above, you would use --with-imap=/usr/local/imap-2000b. This location depends on where you created this directory according to the description above. Windows users may include the php_imap.dll DLL in php.ini.

IMAP is not supported on systems earlier than Windows 2000. This is because it uses encryption functions in order to enable SSL connections to the mail servers.

Note: Depending on how the c-client was configured, you might also need to add --with-imap-ssl=/path/to/openssl/ and/or --with-kerberos=/path/to/kerberos to the PHP configure line.

Warning

The IMAP, recode, YAZ and Cyrus extensions cannot be used in conjuction, because they share the same internal symbols. Note: Yaz 2.0 and above does not suffer from this problem.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

This extension requires the c-client library to be installed. Grab the latest version from » ftp://ftp.cac.washington.edu/imap/ and compile it.

It's important that you do not copy the IMAP source files directly into the system include directory as there may be conflicts. Instead, create a new directory inside the system include directory, such as /usr/local/imap-2000b/ (location and name depend on your setup and IMAP version), and inside this new directory create additional directories named lib/ and include/. From the c-client directory from your IMAP source tree, copy all the *.h files into include/ and all the *.c files into lib/. Additionally when you compiled IMAP, a file named c-client.a was created. Also put this in the lib/ directory but rename it as libc-client.a.

Note: To build the c-client library with SSL or/and Kerberos support read the docs supplied with the package.

Note: In Mandrake Linux, the IMAP library (libc-client.a) is compiled without Kerberos support. A separate version with SSL (client-PHP4.a) is installed. The library must be recompiled in order to add Kerberos support.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
IMAP


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

inclued Configure Options
Name | Default | Changeable | Changelog
inclued.enabled | Off | PHP_INI_* |
inclued.dumpdir | Off | PHP_INI_* |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

inclued.enabled int

Whether or not to enable inclued.

inclued.dumpdir int

Location (path) to the directory that stores inclued files. If set, each PHP request will create a file.

Caution

Because every request creates a file, this directory may fill up fast!

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

This extension has no constants defined.

Resource Types
Examples
inclued


Examples

Table of Contents

  • Example that implements inclued into an application
Predefined Constants
Example that implements inclued into an application
inclued


Example that implements inclued into an application

This example demonstrates the process of implementing inclued into an existing application, and viewing the results.

Example #1 Getting the data from inclued

<?php
// File to store the inclued information
$fp = fopen('/tmp/wp.json', 'w');
if ($fp) {
    $clue = inclued_get_data();
    if ($clue) {
        fwrite($fp, json_encode($clue));
    }
    fclose($fp);
}
?>

Now that some data exists, it's time to make sense of it in the form of a graph. The inclued extension includes a PHP file named gengraph.php that creates a dot file that requires the » graphviz library. However, this form is not required.

Example #2 Example use of gengraph.php

This example creates an image named inclued.png that shows the inclued data.

# First, create the dot file
$ php graphviz.php -i /tmp/wp.json -o wp.dot

# Next, create the image
$ dot -Tpng -o inclued.png wp.dot

Examples
inclued Functions
Examples


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/inclued

Requirements
Runtime Configuration
Installing/Configuring


Requirements

PHP version 5.1.0 or greater.

The included gengraph.php file utilizes the » graphviz library, however, this is not required.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
inclued


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PHP Options/Inf Configuration Options
Name | Default | Changeable | Changelog
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
enable_dl | "1" | PHP_INI_SYSTEM | Removed in PHP 6.0.0.
max_execution_time | "30" | PHP_INI_ALL |
max_input_time | "-1" | PHP_INI_PERDIR | Available since PHP 4.3.0.
max_input_nesting_level | "64" | PHP_INI_PERDIR | Available since PHP 4.4.8. Removed in PHP 5.0.0.
magic_quotes_gpc | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Removed in PHP 6.0.0.
magic_quotes_runtime | "0" | PHP_INI_ALL | Removed in PHP 6.0.0.
zend.enable_gc | "1" | PHP_INI_ALL | Available since PHP 5.3.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

assert.active boolean

Enable assert() evaluation.

assert.bail boolean

Terminate script execution on failed assertions.

assert.warning boolean

Issue a PHP warning for each failed assertion.

assert.callback string

user function to call on failed assertions

assert.quiet_eval boolean

Use the current setting of error_reporting() during assertion expression evaluation. If enabled, no errors are shown (implicit error_reporting(0)) while evaluation. If disabled, errors are shown according to the settings of error_reporting()

enable_dl boolean

This directive is really only useful in the Apache module version of PHP. You can turn dynamic loading of PHP extensions with dl() on and off per virtual server or per directory.

The main reason for turning dynamic loading off is security. With dynamic loading, it's possible to ignore all open_basedir restrictions. The default is to allow dynamic loading, except when using safe mode. In safe mode, it's always impossible to use dl().

max_execution_time integer

This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30. When running PHP from the command line the default setting is 0.

The maximum execution time is not affected by system calls, stream operations etc. Please see the set_time_limit() function for more details.

You can not change this setting with ini_set() when running in safe mode. The only workaround is to turn off safe mode or by changing the time limit in the php.ini.

Your web server can have other timeout configurations that may also interrupt PHP execution. Apache has a Timeout directive and IIS has a CGI timeout function. Both default to 300 seconds. See your web server documentation for specific details.

max_input_time integer

This sets the maximum time in seconds a script is allowed to parse input data, like POST, GET and file uploads.

max_input_nesting_level integer

Sets the max nesting depth of input variables (i.e. $_GET, $_POST..)

magic_quotes_gpc boolean
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically.

Note: In PHP 4, also $_ENV variables are escaped.

Note: If the magic_quotes_sybase directive is also ON it will completely override magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NUL's will remain untouched and unescaped.

See also get_magic_quotes_gpc()

magic_quotes_runtime boolean
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.

Functions affected by magic_quotes_runtime (does not include functions from PECL):

  • get_meta_tags()
  • file_get_contents()
  • file()
  • fgets()
  • fwrite()
  • fread()
  • fputcsv()
  • stream_socket_recvfrom()
  • exec()
  • system()
  • passthru()
  • stream_get_contents()
  • bzread()
  • gzfile()
  • gzgets()
  • gzwrite()
  • gzread()
  • phar_file_get_contents()
  • exif_read_data()
  • dba_insert()
  • dba_replace()
  • dba_fetch()
  • ibase_fetch_row()
  • ibase_fetch_assoc()
  • ibase_fetch_object()
  • mssql_fetch_row()
  • mssql_fetch_object()
  • mssql_fetch_array()
  • mssql_fetch_assoc()
  • mysqli_fetch_row()
  • mysqli_fetch_array()
  • mysqli_fetch_assoc()
  • mysqli_fetch_object()
  • pg_fetch_row()
  • pg_fetch_assoc()
  • pg_fetch_array()
  • pg_fetch_object()
  • pg_fetch_all()
  • pg_select()
  • sybase_fetch_object()
  • sybase_fetch_array()
  • sybase_fetch_assoc()
  • SplFileObject::fgets()
  • SplFileObject::fgetcsv()
  • SplFileObject::fwrite()

zend.enable_gc boolean

Enables or disables the circular reference collector.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are always available as part of the PHP core.

Pre-defined phpcredits() constants
Constant | Value | Description
CREDITS_GROUP | 1 | A list of the core developers
CREDITS_GENERAL | 2 | General credits: Language design and concept, PHP authors and SAPI module.
CREDITS_SAPI | 4 | A list of the server API modules for PHP, and their authors.
CREDITS_MODULES | 8 | A list of the extension modules for PHP, and their authors.
CREDITS_DOCS | 16 | The credits for the documentation team.
CREDITS_FULLPAGE | 32 | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_QA | 64 | The credits for the quality assurance team.
CREDITS_ALL | -1 | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_QA CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags. This is the default value.
phpinfo() constants
Constant | Value | Description
INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS | 2 | PHP Credits. See also phpcredits().
INFO_CONFIGURATION | 4 | Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES | 8 | Loaded modules and their respective settings.
INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV.
INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE | 64 | PHP License information. See also the » license faq.
INFO_ALL | -1 | Shows all of the above. This is the default value.

Assert constants, these values are used to set the assertion options in assert_options().

assert() constants
Constant | INI Setting | Description
ASSERT_ACTIVE | assert.active | Enable assert() evaluation.
ASSERT_CALLBACK | assert.callback | Callback to call on failed assertions.
ASSERT_BAIL | assert.bail | Terminate execution on failed assertions.
ASSERT_WARNING | assert.warning | Issues a PHP warning for each failed assertion
ASSERT_QUITE_EVAL | assert.quiet_eval | Disable error_reporting during assertion expression evaluation.

The following constants are only available if the host operating system is Windows, and can tell different versioning information so its possible to detect various features and make use of them. They are all available as of PHP 5.3.0.

Windows specific constants
Constant | Description
PHP_WINDOWS_VERSION_MAJOR | The major version of Windows, this can be either 4 (NT4/ME/98/95), 5 (XP/2003 R2/2003/2000) or 6 (Vista/2008).
PHP_WINDOWS_VERSION_MINOR | The minor version of Windows, this can be either 0 (Vista/2008/2000/NT4/95), 1 (XP), 2 (2003 R2/2003/XP x64), 10 (98) or 90 (ME).
PHP_WINDOWS_VERSION_BUILD | The Windows build number (for example, Windows Vista with SP1 applied is build 6001)
PHP_WINDOWS_VERSION_PLATFORM | The platform that PHP currently is running on, this value is 2 on Windows Vista/XP/2000/NT4, Server 2008/2003 and on Windows ME/98/95 this value is 1.
PHP_WINDOWS_VERSION_SP_MAJOR | The major version of the service pack installed, this value is 0 if no service pack is installed. For example, Windows XP with service pack 3 installed will make this value 3.
PHP_WINDOWS_VERSION_SP_MINOR | The minor version of the service pack installed, this value is 0 if no service pack is installed.
PHP_WINDOWS_VERSION_SUITEMASK | The suitemask is a bitmask that can tell if various features of Windows is installed, see the table below for possible bitfield values.
PHP_WINDOWS_VERSION_PRODUCTTYPE | This contains the value used to determine the PHP_WINDOWS_NT_* constants. This value may be one of the PHP_WINDOWS_NT_* constants indicating the platform type.
PHP_WINDOWS_NT_DOMAIN_CONTROLLER | This is a domain controller
PHP_WINDOWS_NT_SERVER | This is a server system (eg. Server 2008/2003/2000), note that if this is a domain controller its reported as PHP_WINDOWS_NT_DOMAIN_CONTROLLER.
PHP_WINDOWS_NT_WORKSTATION | This is a workstation system (eg. Vista/XP/2000/NT4)

This table shows a list of features that can be checked for using the PHP_WINDOWS_VERSION_SUITEMASK bitmask.

Windows suitemask bitfields
Bits | Description
0x00000004 | Microsoft BackOffice components are installed.
0x00000400 | Windows Server 2003, Web Edition is installed.
0x00004000 | Windows Server 2003, Compute Cluster Edition is installed.
0x00000080 | Windows Server 2008 Datacenter, Windows Server 2003, Datacenter Edition or Windows 2000 Datacenter Server is installed.
0x00000002 | Windows Server 2008 Enterprise, Windows Server 2003, Enterprise Edition, Windows 2000 Advanced Server, or Windows NT Server 4.0 Enterprise Edition is installed.
0x00000040 | Windows XP Embedded is installed.
0x00000200 | Windows Vista Home Premium, Windows Vista Home Basic, or Windows XP Home Edition is installed.
0x00000100 | Remote Desktop is supported, but only one interactive session is supported. This value is set unless the system is running in application server mode.
0x00000001 | Microsoft Small Business Server was once installed on the system, but may have been upgraded to another version of Windows.
0x00000020 | Microsoft Small Business Server is installed with the restrictive client license in force.
0x00002000 | Windows Storage Server 2003 R2 or Windows Storage Server 2003 is installed.
0x00000010 | Terminal Services is installed. This value is always set. If this value is set but 0x00000100 is not set, then the system is running in application server mode.
0x00008000 | Windows Home Server is installed.
Resource Types
PHP Options/Info Functions
PHP Options/Info


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
PHP Options/Info


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Ingres configuration options
Name | Default | Changeable | Changelog
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.array_index_start | "1" | PHP_INI_ALL | Available since ingres 1.4.0.
ingres.auto | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Available since ingres 1.2.0.
ingres.cursor_mode | "0" | PHP_INI_ALL | Available since ingres 1.1.0.
ingres.default_database | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_password | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_user | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.describe | 1 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.fetch_buffer_size | 100 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.reuse_connection | "1" | PHP_INI_ALL | Available since ingres 2.0.0
ingres.scrollable | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace | "0" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace_connect | "0" | PHP_INI_ALL | Available since ingres 1.2.1.
ingres.utf8 | "1" | PHP_INI_ALL | Available since ingres 2.0.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ingres.allow_persistent boolean

Specifies whether to allow persistent connections to Ingres

ingres.array_index_start integer

Specifies the start value for an integer key for arrays generated by ingres_fetch_row() or ingres_fetch_array(). By default ingres.array_index_start is set to 1. If you wish to make the ingres extension behave like other database extensions set this configuration option to 0.

ingres.auto boolean

Enables or disables autocommit emulation. Ingres cannot have multiple cursors open with autocommit enabled. When enabled, the driver emulates autocommit.

ingres.blob_segment_length integer

Specifies the amount of memory to use when reading BLOB data, in bytes

ingres.cursor_mode integer

Specifies the default mode for cursors opened with ingres_prepare(). Valid values are INGRES_CURSOR_UPDATE or INGRES_CURSOR_READONLY.

ingres.default_database string

Specifies the default database name to use when connecting to the database server if no other name is specified. Does not apply in SQL safe mode.

ingres.default_password string

Specifies the default password to use when connecting to the database server if no other name is specified. Does not apply in SQL safe mode.

ingres.default_user string

Specifies the default user name to use when connecting to the database server if no other name is specified. Does not apply in SQL safe mode.

ingres.describe boolean

Enables the use of DESCRIBE INPUT to determine the expected data types for queries that use parameters. Available with Ingres 9.1.0 and later. When disabled, queries that have parameters passed may need to manually describe the types of those parameters using the types parameter in ingres_query().

Note: Enabling this feature with ingres_query() will cause additional communications traffic between this extension and the server. To minimize this additional traffic, use ingres_prepare() and ingres_execute().

ingres.fetch_buffer_size integer

Specifies the number of pre-fetch rows that ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row() will try and fetch in one fetch operation.

ingres.max_links integer

Specifies the maximum number of Ingres sessions allowed per process or thread. The number of sessions should not exceed the total number of connected sessions configured within Ingres.

ingres.max_persistent integer

Specifies the maximum number of persistent Ingres sessions allowed per process or thread. The number of sessions should not exceed the total number of connected sessions configured within Ingres.

ingres.reuse_connection boolean

Reuses an existing active connection if connecting to the same database with the same user name

ingres.scrollable boolean

Enables support for scrollable cursors. When fetching CLOB or BLOB data, this should be set to FALSE. Available with Ingres 9.2.0 or later.

ingres.trace boolean

Enables simple tracing using E_NOTICE messages

ingres.trace_connect boolean

Prints E_NOTICE messages during ingres_connect() or ingres_pconnect() calls

ingres.utf8 boolean

Assumes that strings being passed to National Character column types (NVARCHAR or NCHAR) are using UTF8 encoding and converts them to UTF16 for the server

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

INGRES_ASSOC (integer)
Columns are returned into the array having the fieldname as the array index. Used with ingres_fetch_array().
INGRES_NUM (integer)
Columns are returned into the array having a numerical index to the fields. By default this index starts at 1, the first field in the result. To change this value, see ingres.array_index_start. Used with ingres_fetch_array().
INGRES_BOTH (integer)
Columns are returned into the array having both a numerical index and the fieldname as the array index. Used with ingres_fetch_array().
INGRES_EXT_VERSION (string)
Specifies the version of the Ingres Extension. Available since version 1.2.0 of the PECL extension.
INGRES_API_VERSION (integer)
Specifies the version of Ingres OpenAPI that the extension was built against. Available since version 1.2.0 of the PECL extension.
INGRES_CURSOR_READONLY (integer)
Specifies that Ingres cursors should be opened in "readonly" mode. Available since version 1.2.0 of the PECL extension. Used with ingres.cursor_mode.
INGRES_CURSOR_UPDATE (integer)
Specifies that Ingres cursors should be opened "for update." Available since version 1.2.0 of the PECL extension. Used with ingres.cursor_mode.
INGRES_DATE_MULTINATIONAL (integer)
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL. Available since version 1.2.0 of the PECL extension. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_DATE_MULTINATIONAL4 (integer)
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL4. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_FINNISH (integer)
Equivalent to the II_DATE_FORMAT setting of FINNISH. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_ISO (integer)
Equivalent to the II_DATE_FORMAT setting of ISO. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_ISO4 (integer)
Equivalent to the II_DATE_FORMAT setting of ISO4. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_GERMAN (integer)
Equivalent to the II_DATE_FORMAT setting of GERMAN. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_MDY (integer)
Equivalent to the II_DATE_FORMAT setting of MDY. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_DMY (integer)
Equivalent to the II_DATE_FORMAT setting of DMY. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_YMD (integer)
Equivalent to the II_DATE_FORMAT setting of YMD. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_MONEY_LEADING (integer)
Specifies the currency character that should be placed at the start of a money value. Equivalent to setting II_MONEY_FORMAT to "L:". Available since version 1.2.0 of the PECL extension. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_MONEY_TRAILING (integer)
Specifies the currency character that should be placed at the end of a money value. Equivalent to setting II_MONEY_FORMAT to "T:". Available since version 1.2.0 of the PECL extension. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_STRUCTURE_BTREE (integer)
Specifies the default table or index structure to BTREE when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CBTREE (integer)
Specifies the default table or index structure to COMPRESSED BTREE when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_HASH (integer)
Specifies the default table or index structure to HASH when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CHASH (integer)
Specifies the default table or index structure to COMPRESSED HASH when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_HEAP (integer)
Specifies the default table structure to HEAP when used in combination with the
options option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CHEAP (integer)
Specifies the default table structure to COMPRESSED HEAP when used in combination with the
options option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_ISAM (integer)
Specifies the default table or index structure to ISAM when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CISAM (integer)
Specifies the default table or index structure to COMPRESSED ISAM when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
Resource Types
Examples
Ingres


Examples

Table of Contents

  • Simple Ingres Example
Predefined Constants
Simple Ingres Example
Ingres


Simple Ingres Example

Examples
Ingres Functions
Examples
PHP Manual

The following simple example shows how to connect to an Ingres database, execute a query, print resulting rows and disconnect from the database.

Example #1 Simple Ingres Example

<?php
// Connecting, selecting database
$link = ingres_connect("database", "user", "password")
    or die("Could not connect: " . ingres_error($link));
echo "Connected successfully";

// Select from a table that exists in all Ingres databases
$query = "SELECT * FROM iitables";
$result = ingres_query($link,$query) or die("Query failed: " .
ingres_error($link));

// Print results in HTML
// relid - table name
// relowner - table owner
echo "<table>\n";
while ($iitables = ingres_fetch_object($result)) {
    echo "\t<tr>\n";
    echo "\t\t<td>" . $iitables->relid . "</td>\n";
    echo "\t\t<td>" . $iitables->relowner . "</td>\n";
    echo "\t</tr>\n";
}
echo "</table>\n";

// Free results
ingres_free_result($result);

// Commit transaction
ingres_commit($link);

// Closing connection
ingres_close($link);
?>

Examples
Ingres Functions
Examples


Installation

This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/ingres.

You can download the DLL for this PECL extension from » http://esd.ingres.com/product/drivers/PHP/.

To have these functions available, you must » download and compile this extension, enabling Ingres support using the --with-ingres[=DIR] option, where DIR is the Ingres base directory. If the II_SYSTEM environment variable is not set correctly you may need to use --with-ingres=DIR to specify your Ingres installation directory.

PHP code written for version 2.x and later is not backward-compatible with earlier versions of this PHP extension. However, it is possible to run two incompatible releases within the same PHP environment using the --enable-ingres2 option. This configuration option renames the extension to ingres2, changing function names, configuration settings, and constants. For example, with this option enabled, ingres_connect() becomes ingres2_connect().

To use this extension the system environment variable II_SYSTEM must be defined. Linux and UNIX users will also need to define the shared library search path, for example, LD_LIBRARY_PATH. When used with the Apache web server these variables must be set explicitly in the startup script for Apache. In addition, the PassEnv directive is required for the Ingres extension to load the correct shared libraries. For example:

Example #1 Example usage of PassEnv for Ingres

<IfModule mod_env.c>
    PassEnv II_SYSTEM
    PassEnv LD_LIBRARY_PATH
</IfModule>

Note: For example configurations for different web servers and operating systems see » http://community.ingres.com/wiki/Ingres_Articles#Ingres_and_Web_Servers.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To use or build the PHP extension for Ingres you must have a working Ingres client environment. You can download the client software for Ingres from » http://esd.ingres.com/.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

ingres_connect() and ingres_pconnect() return an Ingres link identifier.

ingres_query() and ingres_unbuffered_query() return an Ingres result identifier.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Ingres


Security and Safe Mode

Security and Safe Mode Configuration Directives
Name | Default | Changeable | Changelog
safe_mode | "0" | PHP_INI_SYSTEM | Removed in PHP 6.0.0.
safe_mode_gid | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0. Removed in PHP 6.0.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Available since PHP 4.1.0. Removed in PHP 6.0.0.
safe_mode_exec_dir | "" | PHP_INI_SYSTEM | Removed in PHP 6.0.0.
safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | Removed in PHP 6.0.0.
safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | Removed in PHP 6.0.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

safe_mode boolean

Whether to enable PHP's safe mode. If PHP is compiled with --enable-safe-mode then defaults to On, otherwise Off.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

safe_mode_gid boolean

By default, Safe Mode does a UID compare check when opening files. If you want to relax this to a GID compare, then turn on safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) checking upon file access.

safe_mode_include_dir string

UID/GID checks are bypassed when including files from this directory and its subdirectories (directory must also be in include_path or full path must including).

As of PHP 4.2.0, this directive can take a colon (semi-colon on Windows) separated path in a fashion similar to the include_path directive, rather than just a single directory. The restriction specified is actually a prefix, not a directory name. This means that "safe_mode_include_dir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "safe_mode_include_dir = /dir/incl/" If the value of this directive is empty, no files with different UID/GID can be included in PHP 4.2.3 and as of PHP 4.3.3. In earlier versions, all files could be included.
safe_mode_exec_dir string

If PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory. You have to use / as directory separator on all environments including Windows.

safe_mode_allowed_env_vars string

Setting certain environment variables may be a potential security breach. This directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied here. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).

Note: If this directive is empty, PHP will let the user modify ANY environment variable!

safe_mode_protected_env_vars string

This directive contains a comma-delimited list of environment variables that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

See also: open_basedir, disable_functions, disable_classes, register_globals, display_errors, and log_errors.

When safe_mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function or its directory. For example:

-rw-rw-r--    1 rasmus   rasmus       33 Jul  1 19:20 script.php
-rw-r--r--    1 root     root       1116 May 26 18:01 /etc/passwd

Running script.php:

<?php
 readfile('/etc/passwd');
?>

results in this error when safe mode is enabled:

Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not
allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

However, there may be environments where a strict UID check is not appropriate and a relaxed GID check is sufficient. This is supported by means of the safe_mode_gid switch. Setting it to On performs the relaxed GID checking, setting it to Off (the default) performs UID checking.

If instead of safe_mode, you set an open_basedir directory then all file operations will be limited to files under the specified directory. For example (Apache httpd.conf example):

<Directory /docroot>
  php_admin_value open_basedir /docroot
</Directory>

If you run the same script.php with this open_basedir setting then this is the result:

Warning: open_basedir restriction in effect. File is in wrong directory in
/docroot/script.php on line 2

You can also disable individual functions. Note that the disable_functions directive can not be used outside of the php.ini file which means that you cannot disable functions on a per-virtualhost or per-directory basis in your httpd.conf file. If we add this to our php.ini file:

disable_functions = readfile,system

Then we get this output:

Warning: readfile() has been disabled for security reasons in
/docroot/script.php on line 2

Warning

These PHP restrictions are not valid in executed binaries, of course.

Safe Mode
Functions restricted/disabled by safe mode
Safe Mode


Runtime Configuration

This extension has no configuration directives defined in php.ini.

Installing/Configuring
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Inotify constants usable with inotify_add_watch() and/or returned by inotify_read()
IN_ACCESS (integer)
File was accessed (read) (*)
IN_MODIFY (integer)
File was modified (*)
IN_ATTRIB (integer)
Metadata changed (e.g. permissions, mtime, etc.) (*)
IN_CLOSE_WRITE (integer)
File opened for writing was closed (*)
IN_CLOSE_NOWRITE (integer)
File not opened for writing was closed (*)
IN_OPEN (integer)
File was opened (*)
IN_MOVED_TO (integer)
File moved into watched directory (*)
IN_MOVED_FROM (integer)
File moved out of watched directory (*)
IN_CREATE (integer)
File or directory created in watched directory (*)
IN_DELETE (integer)
File or directory deleted in watched directory (*)
IN_DELETE_SELF (integer)
Watched file or directory was deleted
IN_MOVE_SELF (integer)
Watch file or directory was moved
IN_CLOSE (integer)
Equals to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
IN_MOVE (integer)
Equals to IN_MOVED_FROM | IN_MOVED_TO
IN_ALL_EVENTS (integer)
Bitmask of all the above constants
IN_UNMOUNT (integer)
File system containing watched object was unmounted
IN_Q_OVERFLOW (integer)
Event queue overflowed (wd is -1 for this event)
IN_IGNORED (integer)
Watch was removed (explicitly by inotify_rm_watch() or because file was removed or filesystem unmounted
IN_ISDIR (integer)
Subject of this event is a directory
IN_ONLYDIR (integer)
Only watch pathname if it is a directory (Since Linux 2.6.15)
IN_DONT_FOLLOW (integer)
Do not dereference pathname if it is a symlink (Since Linux 2.6.15)
IN_MASK_ADD (integer)
Add events to watch mask for this pathname if it already exists (instead of replacing mask).
IN_ONESHOT (integer)
Monitor pathname for one event, then remove from watch list.

Note: The events marked with an asterisk (*) above can occur for files in watched directories.

Resource Types
Inotify Functions
Inotify


Installing/Configuring
PHP Manual

Installing/Configuring

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/inotify.

Requirements
Runtime Configuration
Installing/Configuring
PHP Manual


Requirements

This extension requires Linux 2.6.13 or newer, and a recent libC.

Installing/Configuring
Installing/Configuring
Installing/Configuring


Resource Types

This extension defines a stream resource returned by inotify_init().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installing/Configuring
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Inotify


Installation and Configuration

  • General Installation Considerations
  • Installation on Unix systems
    • Apache 1.3.x on Unix systems
    • Apache 2.x on Unix systems
    • Lighttpd 1.4 on Unix systems
    • Caudium
    • fhttpd related notes
    • Sun, iPlanet and Netscape servers on Sun Solaris
    • CGI and command line setups
    • HP-UX specific installation notes
    • OpenBSD installation notes
    • Solaris specific installation tips
    • Debian GNU/Linux installation notes
  • Installation on Mac OS X
    • Using Packages
    • Using the bundled PHP
    • Compiling for OS X Server
    • Installing for Apache on MacOS X Client
  • Installation on Windows systems
    • Windows Installer (PHP 5.1.0 and earlier)
    • Windows Installer (PHP 5.2 and later)
    • Manual Installation Steps
    • ActiveScript
    • Microsoft IIS
    • Microsoft IIS 5.1 and IIS 6.0
    • Microsoft IIS 7.0 and later
    • Apache 1.3.x on Microsoft Windows
    • Apache 2.x on Microsoft Windows
    • Sun, iPlanet and Netscape servers on Microsoft Windows
    • OmniHTTPd Server
    • Sambar Server on Microsoft Windows
    • Xitami on Microsoft Windows
    • Building from source
    • Installation of extensions on Windows
    • Command Line PHP on Microsoft Windows
  • Installation of PECL extensions
    • Introduction to PECL Installations
    • Downloading PECL extensions
    • Installing a PHP extension on Windows
    • Compiling shared PECL extensions with the pecl command
    • Compiling shared PECL extensions with phpize
    • Compiling PECL extensions statically into PHP
  • Problems?
    • Read the FAQ
    • Other problems
    • Bug reports
  • Runtime Configuration
    • The configuration file
    • .user.ini files
    • Where a configuration setting may be set
    • How to change configuration settings
What's next?
General Installation Considerations


General Installation Considerations

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

  • Websites and web applications (server-side scripting)
  • Command line scripting
  • Desktop (GUI) applications

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

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

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

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

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

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

Installation and Configuration
Installation on Unix systems
Installation and Configuration


Installation on Mac OS X

Table of Contents

  • Using Packages
  • Using the bundled PHP
  • Compiling for OS X Server
  • Installing for Apache on MacOS X Client

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

Debian GNU/Linux installation notes
Using Packages
Installation and Configuration


Using the bundled PHP

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

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

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

  1. Locate and open the Apache configuration file. By default, the location is as follows: /private/etc/apache2/httpd.conf Using Finder or Spotlight to find this file may prove difficult as by default it's private and owned by the root user.

    Note: One way to open this is by using a Unix based text editor in the Terminal, for example nano, and because the file is owned by root we'll use the sudo command to open it (as root) so for example type the following into the Terminal Application (after, it will prompt for a password): sudo nano /private/etc/apache2/httpd.conf Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents the Ctrl key.

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

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

    # LoadModule php5_module libexec/httpd/libphp5.so

# AddModule mod_php5.c
    Notice the location/path. When building PHP in the future, the above files should be replaced or commented out.

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

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

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

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

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

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

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

    <?php phpinfo(); ?>

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

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

Using Packages
Compiling for OS X Server
Installation on Mac OS X


Installing for Apache on MacOS X Client

The following instructions will help you install a PHP module for the Apache web server included in MacOS X using the MacOS GUI. This version includes MySQL, PostgreSQL, and iODBC database support, cURL, GD, PDFLib, LDAP, and more. These instructions are graciously provided by » Marc Liyanage.

Warning

Be sure you know what you're doing before advancing beyond this point! You can cause irreparable harm to your Apache installation otherwise.

Note: These instructions will only work with the original Apache web server as shipped by Apple. If you re-built or upgraded your Apache, you will have to build your own PHP module.

To install:

  1. For Apache 1.3, download: http://www2.entropy.ch/download/entropy-php-5.2.4-1.tar.gz
  2. For Apache 2, download: wget http://www2.entropy.ch/download/entropy-php-5.2.4-1-apache2.tar.gz
  3. Unpack the compressed .tar.gz file, but DO NOT USE StuffIt Expander. Instead, use Apple's BOMArchiveHelper or the command line.
  4. Double-click the installer package and follow the directions of the installer application.

That's all! PHP should now be up and running. You can test it by dropping a file named test.php into your Sites folder in your home directory. Into that file, write this line: <?php phpinfo() ?>.

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

Compiling for OS X Server
Installation on Windows systems
Installation on Mac OS X


Using Packages

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

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

  • MacPorts: » http://www.macports.org/
  • Entropy: » http://www.entropy.ch/software/macosx/php/
  • Fink: » http://fink.sourceforge.net/

Installation on Mac OS X
Using the bundled PHP
Installation on Mac OS X


Compiling for OS X Server

Mac OS X Server install

  1. Get the latest distributions of Apache and PHP.

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

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

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

    setenv OPTIM=-O2

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

    ./configure --prefix=/usr \
    --sysconfdir=/etc \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --with-xml \
    --with-apache=/src/apache_1.3.12

    If you have any other additions (MySQL, GD, etc.), be sure to add them here. For the --with-apache string, put in the path to your apache source directory, for example /src/apache_1.3.12.

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

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

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

    You may get a message telling you that libmodphp4.a is out of date. If so, go to the src/modules/php4 directory inside your Apache source directory and run this command: ranlib libmodphp4.a. Then go back to the root of the Apache source directory and run the above configure command again. That'll bring the link table up to date. Run make and make install again.

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

Using the bundled PHP
Installing for Apache on MacOS X Client
Installation on Mac OS X


Installation of PECL extensions

Table of Contents

  • Introduction to PECL Installations
  • Downloading PECL extensions
  • Installing a PHP extension on Windows
  • Compiling shared PECL extensions with the pecl command
  • Compiling shared PECL extensions with phpize
  • Compiling PECL extensions statically into PHP
Command Line PHP on Microsoft Windows
Introduction to PECL Installations
Installation and Configuration


Downloading PECL extensions

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

  • The pecl install extname command downloads the extensions code automatically, so in this case there is no need for a separate download.
  • » http://pecl.php.net/ The PECL web site contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: ChangeLog, release notes, requirements and other similar details.
  • pecl download extname PECL extensions that have releases listed on the PECL web site are available for download and installation using the » pecl command. Specific revisions may also be specified.
  • SVN Most PECL extensions also reside in SVN. A web-based view may be seen at » http://svn.php.net/viewvc/pecl/. To download straight from SVN, the following sequence of commands may be used:

    $ svn checkout http://svn.php.net/repository/pecl/extname/trunk extname

  • Windows downloads At this time the PHP project does not compile Windows binaries for PECL extensions. However, to compile PHP under Windows see the chapter titled building PHP for Windows.
Introduction to PECL Installations
Installing a PHP extension on Windows
Installation of PECL extensions


Introduction to PECL Installations

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

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

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

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

Installation of PECL extensions
Downloading PECL extensions
Installation of PECL extensions


Compiling shared PECL extensions with the pecl command

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

$ pecl install extname

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

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

$ pecl install extname-beta

You may also install a specific version using this variant:

$ pecl install extname-0.1

Note: After enabling the extension in php.ini, restarting the web service is required for the changes to be picked up.

Installing a PHP extension on Windows
Compiling shared PECL extensions with phpize
Installation of PECL extensions


Compiling shared PECL extensions with phpize

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

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

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

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

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

Execute phpize --helpto display additional usage information.

Compiling shared PECL extensions with the pecl command
Compiling PECL extensions statically into PHP
Installation of PECL extensions


Compiling PECL extensions statically into PHP

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

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

This will result in the following directory:

/your/phpsrcdir/ext/extname

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

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

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

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

$ ./configure --help | grep extname

Compiling shared PECL extensions with phpize
Problems?
Installation of PECL extensions


Installing a PHP extension on Windows

On Windows, you have two ways to load a PHP extension: either compile it into PHP, or load the DLL. Loading a pre-compiled extension is the easiest and preferred way.

To load an extension, you need to have it available as a ".dll" file on your system. All the extensions are automatically and periodically compiled by the PHP Group (see next section for the download).

To compile an extension into PHP, please refer to building from source documentation.

To compile a standalone extension (aka a DLL file), please refer to building from source documentation. If the DLL file is available neither with your PHP distribution nor in PECL, you may have to compile it before you can start using the extension.

Where to find an extension?

PHP extensions are usually called "php_*.dll" (where the star represents the name of the extension) and they are located under the "PHP\ext" ("PHP\extensions" in PHP4) folder.

PHP ships with the extensions most useful to the majority of developers. They are called "core" extensions.

However, if you need functionality not provided by any core extension, you may still be able to find one in PECL. The PHP Extension Community Library (PECL) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.

If you have developed an extension for your own uses, you might want to think about hosting it on PECL so that others with the same needs can benefit from your time. A nice side effect is that you give them a good chance to give you feedback, (hopefully) thanks, bug reports and even fixes/patches. Before you submit your extension for hosting on PECL, please read http://pecl.php.net/package-new.php.

Which extension to download?

Many times, you will find several versions of each DLL:

  • Different version numbers (at least the first two numbers should match)
  • Different thread safety settings
  • Different processor architecture (x86, x64, ...)
  • Different debugging settings
  • etc.

You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings:

Example #1 phpinfo() call

<?php
phpinfo();
?>

Or from the command line, run:

drive:\\path\to\php\executable\php.exe -i

Loading an extension

The most common way to load a PHP extension is to include it in your php.ini configuration file. Please note that many extensions are already present in your php.ini and that you only need to remove the semicolon to activate them.

;extension=php_extname.dll

extension=php_extname.dll

However, some web servers are confusing because they do not use the php.ini located alongside your PHP executable. To find out where your actual php.ini resides, look for its path in phpinfo():

Configuration File (php.ini) Path  C:\WINDOWS

Loaded Configuration File   C:\Program Files\PHP\5.2\php.ini

After activating an extension, save php.ini, restart the web server and check phpinfo() again. The new extension should now have its own section.

Resolving problems

If the extension does not appear in phpinfo(), you should check your logs to learn where the problem comes from.

If you are using PHP from the command line (CLI), the extension loading error can be read directly on screen.

If you are using PHP with a web server, the location and format of the logs vary depending on your software. Please read your web server documentation to locate the logs, as it does not have anything to do with PHP itself.

Common problems are the location of the DLL, the value of the " extension_dir" setting inside php.ini and compile-time setting mismatches.

If the problem lies in a compile-time setting mismatch, you probably didn't download the right DLL. Try downloading again the extension with the right settings. Again, phpinfo() can be of great help.

Downloading PECL extensions
Compiling shared PECL extensions with the pecl command
Installation of PECL extensions


Problems?

Table of Contents

  • Read the FAQ
  • Other problems
  • Bug reports
Compiling PECL extensions statically into PHP
Read the FAQ
Installation and Configuration


Bug reports

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

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

Other problems
Runtime Configuration
Problems?


Read the FAQ

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

Problems?
Other problems
Problems?


Other problems

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

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

Read the FAQ
Bug reports
Problems?


Installation on Unix systems

Table of Contents

  • Apache 1.3.x on Unix systems
  • Apache 2.x on Unix systems
  • Lighttpd 1.4 on Unix systems
  • Caudium
  • fhttpd related notes
  • Sun, iPlanet and Netscape servers on Sun Solaris
  • CGI and command line setups
  • HP-UX specific installation notes
  • OpenBSD installation notes
  • Solaris specific installation tips
  • Debian GNU/Linux installation notes

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

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

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

Prerequisite knowledge and software for compiling:

  • Basic Unix skills (being able to operate "make" and a C compiler)
  • An ANSI C compiler
  • flex: Version 2.5.4
  • bison: Version 1.28 (preferred), 1.35, or 1.75
  • A web server
  • Any module specific components (such as GD, PDF libs, etc.)

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

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

General Installation Considerations
Apache 1.3.x on Unix systems
Installation and Configuration


Apache 1.3.x on Unix systems

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

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

Example #1 Installation Instructions (Apache Shared Module Version) for PHP

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

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

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

11. make
12. make install

    If you decide to change your configure options after installation,
    you only need to repeat the last three steps. You only need to
    restart apache for the new module to take effect. A recompile of
    Apache is not needed.

    Note that unless told otherwise, 'make install' will also install PEAR,
    various PHP tools such as phpize, install the PHP CLI, and more.

13. Setup your php.ini file:

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

    You may edit your .ini file to set PHP options.  If you prefer your
    php.ini in another location, use --with-config-file-path=/some/path in
    step 10.

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

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

    For PHP 4:

      LoadModule php4_module libexec/libphp4.so

    For PHP 5:

      LoadModule php5_module libexec/libphp5.so

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

    For PHP 4:

      AddModule mod_php4.c

    For PHP 5:

      AddModule mod_php5.c

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

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

    It's also common to setup the .phps extension to show highlighted PHP
    source, this can be done with:

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

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

Alternatively, to install PHP as a static object:

Example #2 Installation Instructions (Static Module Installation for Apache) for PHP

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

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

10. cd ../apache_1.3.x

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

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

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

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

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

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

Example #3 Example commands for restarting Apache

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

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

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

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

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

Different examples of compiling PHP for apache are as follows:

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

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

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

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

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

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

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

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

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

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

User nobody
Group "#-1"

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

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

Installation on Unix systems
Apache 2.x on Unix systems
Installation on Unix systems


Apache 2.x on Unix systems

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

Warning

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

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

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

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

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

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

  2. Likewise, obtain and unpack the PHP source:

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

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

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

  4. Now you have Apache 2.x.NN available under /usr/local/apache2, configured with loadable module support and the standard MPM prefork. To test the installation use your normal procedure for starting the Apache server, e.g.:

    /usr/local/apache2/bin/apachectl start

    and stop the server to go on with the configuration for PHP:

    /usr/local/apache2/bin/apachectl stop

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

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

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

    If you decide to change your configure options after installation, you'll need to re-run the configure, make, and make install steps. You only need to restart apache for the new module to take effect. A recompile of Apache is not needed.

    Note that unless told otherwise, 'make install' will also install PEAR, various PHP tools such as phpize, install the PHP CLI, and more.

  6. Setup your php.ini

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

    You may edit your .ini file to set PHP options. If you prefer having php.ini in another location, use --with-config-file-path=/some/path in step 5.

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

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

    LoadModule php5_module modules/libphp5.so

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

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

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

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

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

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

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

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

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

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

    /usr/local/apache2/bin/apachectl start

    OR

    service httpd restart

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

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

--with-mpm=worker

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

Note: The Apache MultiViews FAQ discusses using multiviews with PHP.

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

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


Caudium

PHP can be built as a Pike module for the » Caudium webserver. Follow the simple instructions below to install PHP for Caudium.

Example #1 Caudium Installation Instructions

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

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

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

Lighttpd 1.4 on Unix systems
fhttpd related notes
Installation on Unix systems


CGI and command line setups

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

Warning

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

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

Testing

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

Using Variables

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

Sun, iPlanet and Netscape servers on Sun Solaris
HP-UX specific installation notes
Installation on Unix systems


Debian GNU/Linux installation notes

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

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

Using APT

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

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

Example #1 Debian Install Example with Apache 2

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

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

Example #2 Stopping and starting Apache once PHP is installed

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

Better control of configuration

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

Example #3 Methods for listing additional PHP 5 packages

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

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

Example #4 Install PHP with MySQL, cURL

# apt-get install php5-mysql php5-curl

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

Common Problems

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


fhttpd related notes

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

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

Caudium
Sun, iPlanet and Netscape servers on Sun Solaris
Installation on Unix systems


HP-UX specific installation notes

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

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

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

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

CGI and command line setups
OpenBSD installation notes
Installation on Unix systems


Lighttpd 1.4 on Unix systems

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

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

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

Letting Lighttpd spawn php processes

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

Example #1 Partial lighttpd.conf

server.modules += ( "mod_fastcgi" )

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

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

Spawning with spawn-fcgi

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

Spawning php-cgi

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

Example #2 Spawning FastCGI Responders

#!/bin/sh

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

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

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

PHP_FCGI_CHILDREN=16
PHP_FCGI_MAX_REQUESTS=10000

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

echo $! > "$PHP_PID"

Connecting to remote FCGI instances

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

Example #3 Connecting to remote php-fastcgi instances

fastcgi.server = ( ".php" =>
   (( "host" => "10.0.0.2", "port" => 1030 ),
    ( "host" => "10.0.0.3", "port" => 1030 ))
)
Apache 2.x on Unix systems
Caudium
Installation on Unix systems


OpenBSD installation notes

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

Using Binary Packages

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

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

Example #1 OpenBSD Package Install Example

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

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

Using Ports

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

Common Problems

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

Older Releases

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

HP-UX specific installation notes
Solaris specific installation tips
Installation on Unix systems


Solaris specific installation tips

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

Required software

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

  • gcc (recommended, other C compilers may work)
  • make
  • flex
  • bison
  • m4
  • autoconf
  • automake
  • perl
  • gzip
  • tar
  • GNU sed

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

Using Packages

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

OpenBSD installation notes
Debian GNU/Linux installation notes
Installation on Unix systems


Sun, iPlanet and Netscape servers on Sun Solaris

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

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

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

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

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

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

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

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

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

  7. Run make followed by make install.

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

Configuration Instructions for Sun/iPlanet/Netscape

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

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

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

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

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so"
Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"]

    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server config directory.

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

    <Object name="default">
.
.
.
.#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines
Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
.
.
</Object>

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

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

    <Object name="x-httpd-php">
ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
Service fn=php4_execute [inikey=value inikey=value ...]
</Object>

    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

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

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

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

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

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

CGI environment and recommended modifications in php.ini

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

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

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

variables_order = "GPCS"
register_globals = On

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

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

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]

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

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

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]

For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].

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

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

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

fhttpd related notes
CGI and command line setups
Installation on Unix systems


Installation on Windows systems

Table of Contents

  • Windows Installer (PHP 5.1.0 and earlier)
  • Windows Installer (PHP 5.2 and later)
  • Manual Installation Steps
  • ActiveScript
  • Microsoft IIS
  • Microsoft IIS 5.1 and IIS 6.0
  • Microsoft IIS 7.0 and later
  • Apache 1.3.x on Microsoft Windows
  • Apache 2.x on Microsoft Windows
  • Sun, iPlanet and Netscape servers on Microsoft Windows
  • OmniHTTPd Server
  • Sambar Server on Microsoft Windows
  • Xitami on Microsoft Windows
  • Building from source
  • Installation of extensions on Windows
  • Command Line PHP on Microsoft Windows

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

Note: Windows 98/ME/NT4 is no longer supported as of PHP 5.3.0.

Note: Windows 95 is no longer supported as of PHP 4.3.0.

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

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

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

Warning

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

Installing for Apache on MacOS X Client
Windows Installer (PHP 5.1.0 and earlier)
Installation and Configuration


ActiveScript

This section contains notes specific to the ActiveScript installation.

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

As of PHP 5.0.1, ActiveScript has been moved to the » PECL repository. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Note: You should read the manual installation steps first!

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

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

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

<job id="test">

 <script language="PHPScript">
  $WScript->Echo("Hello World!");
 </script>

</job>

Save and double-click on the file. If you receive a little window saying "Hello World!" you're done.

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

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

Manual Installation Steps
Microsoft IIS
Installation on Windows systems


Apache 1.3.x on Microsoft Windows

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

Note: Please read the manual installation steps first!

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

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

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

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

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

Installing as an Apache module

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

Example #1 PHP as an Apache 1.3.x module

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

For PHP 4:

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

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

For PHP 5:

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

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

For both:

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

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

Installing as a CGI binary

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

Example #2 PHP and Apache 1.3.x as CGI

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

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

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

# specify the directory where php.ini is
SetEnv PHPRC C:/php

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

Warning

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

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

Microsoft IIS 7.0 and later
Apache 2.x on Microsoft Windows
Installation on Windows systems


Apache 2.x on Microsoft Windows

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

Note: You should read the manual installation steps first!

Note: Apache 2.2 Support
Users of Apache 2.2 should note that the DLL file for Apache 2.2 is named php5apache2_2.dll rather than php5apache2.dll and is available only for PHP 5.2.0 and later. See also » http://snaps.php.net/

You are strongly encouraged to consult the » Apache Documentation to get a basic understanding of the Apache 2.x Server. Also consider reading the » Windows specific notes for Apache 2.x before reading on here.

Apache 2.x is designed to run on the Windows version designated as server platforms, such as Windows NT 4.0, Windows 2000, Windows XP, or Windows 7. While Apache 2.x works tolerably well on Windows 9x, support on these platforms is incomplete, and some things will not work correctly. There is no plan to remedy this situation.

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

There are three ways to set up PHP to work with Apache 2.x on Windows. You can run PHP as a handler, as a CGI, or under FastCGI.

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

Installing as an Apache handler

You need to insert the following lines into your Apache httpd.conf configuration file to load the PHP module for Apache 2.x:

Example #1 PHP and Apache 2.x as handler

#
LoadModule php5_module "c:/php/php5apache2.dll"
AddHandler application/x-httpd-php .php

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

Note: Remember to substitute your actual path to PHP for the C:/php/ in the above examples. Take care to use either php5apache2.dll or php5apache2_2.dll in your LoadModule directive and verify that the referenced file is in fact located at the file path that you point to in this directive.

The above configuration will enable PHP handling of any file that has a .php extension, even if there are other file extensions. For example, a file named example.php.txt will be executed by the PHP handler. To ensure that only files that end in .php are executed, use the following configuration instead:

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

Running PHP as CGI

You should consult the » Apache CGI documentation for a more complete understanding of running CGI on Apache.

To run PHP as CGI, you'll need to place your php-cgi files in a directory designated as a CGI directory using the ScriptAlias directive.

You will then need to insert a #! line in the PHP files, pointing to the location of your PHP binary:

Example #2 PHP and Apache 2.x as CGI

#!C:/php/php.exe
<?php
  phpinfo();
?>

Warning

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

Running PHP under FastCGI

Running PHP under FastCGI has a number of advantages over running it as a CGI. Setting it up this way is fairly straightforward:

Obtain mod_fcgid from » http://httpd.apache.org/mod_fcgid/. Win32 binaries are available for download from that site. Install the module according to the instructions that will come with it.

Configure your web server as shown below, taking care to adjust any paths to reflect your how you have installed things on your particular system:

Example #3 Configure Apache to run PHP as FastCGI

LoadModule fcgid_module modules/mod_fcgid.so

# Where is your php.ini file?
FcgidInitialEnv PHPRC        "c:/php"

AddHandler fcgid-script .php
FcgidWrapper "c:/php/php-cgi.exe" .php

Files with a .php extension will now be executed by the PHP FastCGI wrapper.

Apache 1.3.x on Microsoft Windows
Sun, iPlanet and Netscape servers on Microsoft Windows
Installation on Windows systems


Building from source

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

This documentation will give you a basic understanding of how to compile PHP on Windows. This guide takes advanges of the many improvements made to the build system available in PHP 5.3.0 and greater.

Getting started

Before we can compile PHP we will need a compiler and some of the many libraries that PHP depends on. The only supported compilers on Windows is MSVC (Microsoft Visual C++). Versions 6 and greater is supported, however for better performance Visual C++ 2008 or greater is recommeded. This documentation will use Visual C++ 2008 and PHP 5.3.x as a base.

Visual C++ exists in two editions, a commercial edition (Visual Studio) and in an "Express" edition, which is freely available from Microsoft.

Installing using Visual Studio

When installing Visual Studio, you will be prompted to choose which components you wish to use, in here you must check the "Visual C++" component. If you plan on compiling x64 versions of PHP, you must select the x64 compilers component below "Visual C++".

If you already installed Visual Studio, then plugin your DVD and select "Add/Remove components", and follow the procedure above for installing the compiler.

Installing using Visual C++ Express

Visual C++ Express is available for free from Microsoft at: » http://www.microsoft.com/express/download/.

Before installing, the installation wizard will ask you to install additional components such as SQL Server, Silverlight and so on, none of these are required for compiling PHP.

Installing the Windows Platform SDK

Before PHP can be compiled, we need the Windows Platform SDK. By default Visual C++ comes with the Windows Platform SDK version 6.0A, this can however not be used due to incompatibility with previous versions of the SDK. So the Windows Platform SDK 2008, which is version 6.1 is required. The SDK is freely available from Microsoft at: » http://www.microsoft.com/downloads/details.aspx?FamilyID=e6e1c3df-a74f-4207-8586-711ebe331cdc.

When downloading the SDK, choose the web install, as you will only need selected components. When the download is done and the setup is prompting you to select which components you require, then select the C++ compilers (remember to tick the x64 compilers, if you want to compile the 64bit version of PHP). You don't need any other tools such as CrystalReports, Mobile Development tools or anything, just the C++ libraries, headers and compilers.

Directory structure

Now we need to set a directory structure for where the PHP sources will be located, aswell as the default required libraries for compiling PHP. Below structure is simple and easy usable, its however not required to have it exactly like this, but its easy to overlook.

Example #1 Source and toolchain directory structure

C:.
+---php
|   +---src                       <- Here will the PHP sources be located
|   +---win32build                <- Toolchain and libraries for x86 (32 bit) versions
|   |   +---bin                   <- Toolchain
|   |   +---include               <- Header files
|   |   +---lib                   <- Library files
|   +---win64build                <- Toolchain and libraries for x64 (64 bit) versions (optional)
|       +---bin                   <- Toolchain
|       +---include               <- Header files
|       +---lib                   <- Library files

Getting the PHP source

There are serveral ways to get the PHP sources, either from the source tarballs or directly from the PHP SVN repository. This documentation will simply assume either option is choosen and the sources either have been exracted/checked out to the "C:\php\src\" directory from the above directory structure.

Getting the PHP toolchain

To compile PHP, we need a toolchain of different programs for compiling and linking default extensions. These are all available in a single zip file from the PHP on Windows repository: » http://pecl2.php.net/downloads/php-windows-builds/php-libs/binary-tools.zip.

Extract this zip file so it complies with the directory structure for the "C:\php\win32build\" directory. If you are planning to compile 64bit versions of PHP, you need to do the same with the "C:\php\win64build\" directory. This is alright as the tools are platform independent.

Getting the libraries required for PHP

PHP is a glue language, and depends on many libraries in order to function. By default PHP requires a set of libraries for compiling the core (Engine, CLI SAPI and the standard library).

These are available from PHP.net, organized in compiler versions and machine architectures. A standard PHP build requires the following mandatory libraries:

  • ICU
  • iconv (libiconv)
  • libxml2
  • zlib

If you plan to compile a standard versions of PHP. Meaning compiling all default enabled extension by running configure without any arguments, You will also need the following additional libraries for GD:

  • FreeType
  • libpng
  • libjpeg

All these libraries are packed and published to the following URL: » http://pecl2.php.net/downloads/php-windows-builds/php-libs/.

On the above location, libraries are organized by which compiler that were used to compile them and on which platform architecture. Below explains the different shot name variants for each compiler.

  • VC6 - Visual C++ 6.0
  • VC8 - Visual C++ 2005
  • VC9 - Visual C++ 2008

When you have downloaded the mandatory libraries, and/or any additional libraries you may require, then exact them respectedly to the directory structure set in "C:\php\winXXbuild\", so headers are located in the include directory and library files in the libs directory.

Setting up the environment

Before we can compile PHP, we must alter the PATH environment variable so the configure script can pickup the toolchain in the "C:\php\winXXbuild\bin\" directories. To do this, open the Start menu and right click on "Computer" and select "Properties". Select the "Advanced" tab, and hit the button saying "Environment variables". In the global variables section, find the PATH variable and select "Edit". Append the following to its current value: ;C:\php\win32build\bin and for 64bit support: ;C:\php\win32build\bin;C:\php\win64build\bin.

Now you must create the following directory structure on the drive that you are using to compile on:

Example #2 bison.simple directory structure

C:.
+---usr
|   +---local
|       +---share

Now copy the "C:\php\win32build\bin\bison.simple" file into the "C:\usr\local\share" directory.

Compiling

Now PHP is ready to be compiled, open the Start menu, choose "Programs" and find "Microsoft Visual Studio" (or "Microsoft Visual C++"), select the tools folder and open "Visual Studio 2008 Command Prompt". This will open a console window saying "Setting up environment for XXX", where XXX may be either x86 or x64. If you wish to compile the 64bit version of PHP, you must execute the following:

Example #3 Setting up the x64 build environment

cd bin
vcvarsx86_amd64

Now cd to the "C:\php\src\" directory and execute the buildconf script like so:

Example #4 Running buildconf

buildconf
Now run 'configure --help'

This means that the configure script was generated with success. Now we need to run the generated configure script to generate the Makefiles for the compiler. Simply run configure like so:

Example #5 Running configure

configure
...
...
...

As buildconf advertised, then configure --help can be used to see available commands for configure. If you have multiple cores available then enable multi processing, which optimizes and makes the compilation faster. Multi processing can be enabled using the --enable-one-shot option for configure like so:

Example #6 Enabling multi processing in configure

configure --enable-one-shot
...
...
...

If you wish to do a minimal build, then you need to disable all default enabled extensions using the --disable-all option. When disabling all extensions and SAPIs, you must select atleast one before you can compile a PHP binary. Below example will disable all extensions, enable the CLI SAPI and enable multi processing:

If you need to export debugging symbols and doing a debug build, you also need to enable the following two options: --enable-debug and --enable-debug-pack.

Example #7 Configuring a minimal build of PHP with multi processing

configure --disable-all --enable-cli --enable-one-shot
...
...
...

If you need to compile an NTS (NOT Thread Safe) build of PHP, you need to pass the --disable-zts option to configure. By default PHP is compiled with Thread Safety.

Now we are ready actually perform the compile, this is done by executing nmake, like so:

Example #8 Executing nmake

nmake
...
...
...

Testing the build

When the build process is complete, the PHP binary, along with all the compiled extensions will be located in a sub directory to the sources directory. Depending on the build type, it will be located in one of the following directories:

  • Debug - Debug, NOT Thread Safe
  • Debug_TS - Debug, Thread Safe
  • Release - Release, NOT Thread Safe
  • Release_TS - Release, Thread Safe

If you are compiling the 64bit version of PHP, these directories will be located inside another directory called x64 from the root of the sources.

To test the compiled binary, then cd to its directory and execute the following:

Example #9 Testing the compiled PHP binary

C:\php\src\Release_TS\> php -v
PHP 5.3.X (cli) (built: XXX XX XXXX XX:XX:XX)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

Xitami on Microsoft Windows
Installation of extensions on Windows
Installation on Windows systems


Command Line PHP on Microsoft Windows

This section contains notes and hints specific to getting PHP running from the command line for Windows.

Note: You should read the manual installation steps first!

Getting PHP to run from the command line can be performed without making any changes to Windows.

C:\PHP5\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3

But there are some easy steps that can be followed to make this simpler. Some of these steps should already have been taken, but are repeated here to be able to provide a complete step-by-step sequence.

  • Add the location of the PHP executable (php.exe, php-win.exe or php-cli.exe depending upon your PHP version and display preferences) to the PATH environment variable. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry.

  • Add the .PHP extension to the PATHEXT environment variable. This can be done at the same time as amending the PATH environment variable. Follow the same steps as described in the FAQ but amend the PATHEXT environment variable rather than the PATH environment variable.

    Note: The position in which you place the .PHP will determine which script or program is executed when there are matching filenames. For example, placing .PHP before .BAT will cause your script to run, rather than the batch file, if there is a batch file with the same name.

  • Associate the .PHP extension with a file type. This is done by running the following command:

    assoc .php=phpfile

  • Associate the phpfile file type with the appropriate PHP executable. This is done by running the following command:

    ftype phpfile="C:\PHP5\php.exe" -f "%1" -- %~2

Following these steps will allow PHP scripts to be run from any directory without the need to type the PHP executable or the .PHP extension and all parameters will be supplied to the script for processing.

The example below details some of the registry changes that can be made manually.

Example #1 Registry changes

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php]
@="phpfile"
"Content Type"="application/php"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile]
@="PHP Script"
"EditFlags"=dword:00000000
"BrowserFlags"=dword:00000008
"AlwaysShowExt"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon]
@="C:\\PHP5\\php-win.exe0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell]
@="Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open]
@="&Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command]
@="\"C:\\PHP5\\php.exe\" -f \"%1\" -- %~2"

With these changes the same command can be written as:

"C:\PHP Scripts\script" -arg1 -arg2 -arg3
or, if your "C:\PHP Scripts" path is in the PATH environment variable:
script -arg1 -arg2 -arg3

Note: There is a small problem if you intend to use this technique and use your PHP scripts as a command line filter, like the example below:

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3
or
dir | script -arg1 -arg2 -arg3
You may find that the script simply hangs and nothing is output. To get this operational, you need to make another registry change.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
"InheritConsoleHandles"=dword:00000001
Further information regarding this issue can be found in this » Microsoft Knowledgebase Article : 321788.

Installation of extensions on Windows
Installation of PECL extensions
Installation on Windows systems


Installation of extensions on Windows

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

The DLLs for PHP extensions are prefixed with php_.

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

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

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

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

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

    extension_dir = C:\php\extensions

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

    Example #1 Enable Bzip2 extension for PHP-Windows

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

// ... to
extension=php_bz2.dll

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

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

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

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

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

Building from source
Command Line PHP on Microsoft Windows
Installation on Windows systems


Microsoft IIS

This section contains PHP installation instructions specific to Microsoft Internet Information Services (IIS).

  • Manually installing PHP on Microsoft IIS 5.1 and IIS 6.0
  • Manually installing PHP on Microsoft IIS 7.0 and later
ActiveScript
Microsoft IIS 5.1 and IIS 6.0
Installation on Windows systems


Microsoft IIS 5.1 and IIS 6.0

This section contains instructions for manually setting up Internet Information Services (IIS) 5.1 and IIS 6.0 to work with PHP on Microsoft Windows XP and Windows Server 2003. For instructions on setting up IIS 7.0 and later versions on Windows Vista, Windows Server 2008, Windows 7 and Windows Server 2008 R2 refer to Microsoft IIS 7.0 and later.

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Note: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Example #1 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Download and install the » Microsoft FastCGI Extension for IIS 5.1 and 6.0. The extension is available for 32-bit and 64-bit platforms - select the right download package for your platform.

Configure the FastCGI extension to handle PHP-specific requests by running the command shown below. Replace the value of the "-path" parameter with the absolute file path to the php-cgi.exe file.

Example #2 Configuring FastCGI extension to handle PHP requests

cscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" ^
-extension:php -path:"C:\PHP\php-cgi.exe"

This command will create an IIS script mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI extension. Also, it will configure FastCGI extension to use the executable php-cgi.exe to process the PHP requests.

Note: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each others' files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 5.1 and IIS 6.0, in its default configuration, has anonymous authentication enabled with built-in user account IUSR_<MACHINE_NAME> used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR_<MACHINE_NAME> account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR_<MACHINE_NAME> account should have write permission to those.

To determine which user account is used by IIS anonymous authentication, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Expand the list of web sites under the "Web Sites" node in the tree view, right-click on a web site that is being used and select "Properties";

  3. Click the "Directory Security" tab;

  4. Take note of a "User name:" field in the "Authentication Methods" dialog

Anonymous authenication for IIS 5.1 and IIS 6.0

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Example #3 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Right-click on the "Web Sites" node in the tree view and select "Properties";

  3. Click the "Documents" tab;

  4. Click the "Add..." button and enter "index.php" for the "Default content page:".

Setting index.php as default document for IIS

FastCGI and PHP Recycling configuration

Configure IIS FastCGI extension settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before FastCGI extension shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Example #4 Configuring FastCGI and PHP recycling

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-InstanceMaxRequests:10000

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000

Configuring FastCGI timeout settings

Increase the timeout settings for FastCGI extension if there are applications that have long running PHP scripts. The two settings that control timeouts are ActivityTimeout and RequestTimeout. Refer to » Configuring FastCGI Extension for IIS 6.0 for more information about those settings.

Example #5 Configuring FastCGI timeout settings

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-ActivityTimeout:90

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-RequestTimeout:90

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Example #6 Changing the location of php.ini file

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHPRC:"C:\Some\Directory\"

Microsoft IIS
Microsoft IIS 7.0 and later
Installation on Windows systems


Microsoft IIS 7.0 and later

This section contains instructions for manually setting up Internet Information Services (IIS) 7.0 and later to work with PHP on Microsoft Windows Vista SP1, Windows 7, Windows Server 2008 and Windows Server 2008 R2. For instructions on setting up IIS 5.1 and IIS 6.0 on Windows XP and Windows Server 2003 refer to Microsoft IIS 5.1 and IIS 6.0.

Enabling FastCGI support in IIS

FastCGI module is disabled in default installation of IIS. The steps to enable it differ based on the version of Windows being used.

To enable FastCGI support on Windows Vista SP1 and Windows 7:

  1. In the Windows Start Menu choose "Run:", type "optionalfeatures.exe" and click "Ok";

  2. In the "Windows Features" dialog expand "Internet Information Services", "World Wide Web Services", "Application Development Features" and then enable the "CGI" checkbox;

  3. Click OK and wait until the installation is complete.

Enabling FastCGI support for IIS7 on Windows Vista SP1 and Windows 7

To enable FastCGI support on Windows Server 2008 and Windows Server 2008 R2:

  1. In the Windows Start Menu choose "Run:", type "CompMgmtLauncher" and click "Ok";

  2. If the "Web Server (IIS)" role is not present under the "Roles" node, then add it by clicking "Add Roles";

  3. If the "Web Server (IIS)" role is present, then click "Add Role Services" and then enable the "CGI" checkbox under "Application Development" group;

  4. Click "Next" and then "Install" and wait for the installation to complete.

Enabling FastCGI support on Windows Server 2008 and Windows Server 2008 R2

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Note: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Example #1 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Configure IIS handler mapping for PHP by using either IIS Manager user interface or a command line tool.

Using IIS Manager user interface to create a handler mapping for PHP

Follow these steps to create an IIS handler mapping for PHP in IIS Manager user interface:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. In the IIS Manager user interface select the server node in the "Connections" tree view;

  3. In the "Features View" page open the "Handler Mappings" feature;

    Create IIS handler mapping for PHP : Locate Handler Mappings

  4. In the "Actions" pane click "Add Module Mapping...";

  5. In the "Add Module Mapping" dialog enter the following:

    • Request path: *.php
    • Module: FastCgiModule
    • Executable: C:\[Path to PHP installation]\php-cgi.exe
    • Name: PHP_via_FastCGI

  6. Click "Request Restrictions" button and then configure the mapping to invoke handler only if request is mapped to a file or a folder;

  7. Click OK on all the dialogs to save the configuration.

Create IIS handler mapping for PHP : Add Handler Mapping

Using command line tool to create a handler mapping for PHP

Use the command shown below to create an IIS FastCGI process pool which will use php-cgi.exe executable for processing PHP requests. Replace the value of the fullPath parameter with the absolute file path to the php-cgi.exe file.

Example #2 Creating IIS FastCGI process pool

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI ^
/+[fullPath='c:\PHP\php-cgi.exe']

Configure IIS to handle PHP specific requests by running the command shown below. Replace the value of the scriptProcessor parameter with the absolute file path to the php-cgi.exe file.

Example #3 Creating handler mapping for PHP requests

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers ^
/+[name='PHP_via_FastCGI', path='*.php',verb='*',modules='FastCgiModule',^
scriptProcessor='c:\PHP\php-cgi.exe',resourceType='Either']

This command creates an IIS handler mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI module.

Note: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each other's files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 7, in its default configuration, has anonymous authentication enabled with built-in user account IUSR used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR account should have write permission to those.

To determine what user account is used as an anonymous identity in IIS 7 use the following command. Replace the "Default Web Site" with the name of IIS web site that you use. In the output XML configuration element look for the userName attribute.

Example #4 Determining the account used as IIS anonymous identity

%windir%\system32\inetsrv\appcmd.exe list config "Default Web Site" ^
/section:anonymousAuthentication

<system.webServer>
  <security>
    <authentication>
      <anonymousAuthentication enabled="true" userName="IUSR" />
    </authentication>
   </security>
</system.webServer>

Note: If userName attribute is not present in the anonymousAuthentication element, or is set to an empty string, then it means that the application pool identity is used as an anonymous identity for that web site.

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Example #5 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, use this command:

Example #6 Set index.php as a default document in IIS

%windir%\system32\inetsrv\appcmd.exe set config ^
-section:system.webServer/defaultDocument /+"files.[value='index.php']" ^
/commit:apphost

FastCGI and PHP Recycling configuration

Configure IIS FastCGI settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before IIS shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Example #7 Configuring FastCGI and PHP recycling

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='c:\php\php-cgi.exe'].instanceMaxRequests:10000

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/+"[fullPath='C:\{php_folder}\php-cgi.exe'].environmentVariables.^
[name='PHP_FCGI_MAX_REQUESTS',value='10000']"

Configuring FastCGI timeout settings

Increase the timeout settings for FastCGI if it is expected to have long running PHP scripts. The two settings that control timeouts are activityTimeout and requestTimeout. Use the commands below to change the timeout settings. Make sure to replace the value in the fullPath parameter to contain the absolute path to the php-cgi.exe file.

Example #8 Configuring FastCGI and PHP recycling

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].activityTimeout:"90"  /commit:apphost

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].requestTimeout:"90"  /commit:apphost

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Example #9 Changing the location of php.ini file

appcmd.exe set config  -section:system.webServer/fastCgi ^
/+"[fullPath='C:\php\php.exe',arguments=''].environmentVariables.^
[name='PHPRC',value='C:\Some\Directory\']" /commit:apphost

Microsoft IIS 5.1 and IIS 6.0
Apache 1.3.x on Microsoft Windows
Installation on Windows systems


Windows Installer (PHP 5.1.0 and earlier)

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

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

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

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

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

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

Warning

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

Installation on Windows systems
Windows Installer (PHP 5.2 and later)
Installation on Windows systems


Windows Installer (PHP 5.2 and later)

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

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

Normal Install

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

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

Warning

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

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

Silent Install

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

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

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

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

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

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

The current list of Features to install is as follows:

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

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

Upgrading PHP with the Install

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

Windows Installer (PHP 5.1.0 and earlier)
Manual Installation Steps
Installation on Windows systems


Manual Installation Steps

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

Selecting and downloading the PHP distribution package

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

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

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

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

The PHP package structure and content

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

Example #1 PHP 5 package structure

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

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

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

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

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

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

  • php5apache2_2.dll - Apache 2.2.X module.

  • php5apache2_2_filter.dll - Apache 2.2.X filter.

Changing the php.ini file

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

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

Required directives:

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

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

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

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

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

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

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

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

Optional directives

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

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

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

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

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

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

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

Windows Installer (PHP 5.2 and later)
ActiveScript
Installation on Windows systems


OmniHTTPd Server

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

Note: You should read the manual installation steps first!

Warning

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

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

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

  1. Install OmniHTTPd server.

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

  3. Click on Web Server Global Settings

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

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

  6. Click OK

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

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

Sun, iPlanet and Netscape servers on Microsoft Windows
Sambar Server on Microsoft Windows
Installation on Windows systems


Sambar Server on Microsoft Windows

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

Note: You should read the manual installation steps first!

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

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

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

    Example #1 ISAPI configuration of Sambar

    #for PHP 4
*.php = c:\php\php4isapi.dll

#for PHP 5
*.php = c:\php\php5isapi.dll

    (This line assumes that PHP was installed in c:\php.)

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

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

OmniHTTPd Server
Xitami on Microsoft Windows
Installation on Windows systems


Sun, iPlanet and Netscape servers on Microsoft Windows

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

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

CGI setup on Sun, iPlanet and Netscape servers

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

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

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

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

  • In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).
  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).
  • Do it for each web server instance you want PHP to run

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

NSAPI setup on Sun, iPlanet and Netscape servers

To install PHP with NSAPI, do the following:

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

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

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

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

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

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"]

    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server configuration directory.

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

    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]

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

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

    <Object name="x-httpd-php">
ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
Service fn=php4_execute [inikey=value inikey=value ...]
</Object>

    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

  • Restart your web service and apply changes
  • Do it for each web server instance you want PHP to run

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

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

CGI environment and recommended modifications in php.ini

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

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

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

variables_order = "GPCS"
register_globals = On

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

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

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]

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

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

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]

For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].

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

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

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

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

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

Init fn=php4_init ... server_lib="ns-httpdXX.dll"

where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one.

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

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

Apache 2.x on Microsoft Windows
OmniHTTPd Server
Installation on Windows systems


Xitami on Microsoft Windows

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

Note: You should read the manual installation steps first!

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

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

Warning

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

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

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

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

  • Press the 'Save' icon.

  • Restart the server to reflect changes.

Sambar Server on Microsoft Windows
Building from source
Installation on Windows systems


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Intl Configure Options
Name | Default | Changeable | Changelog
intl.default_locale |  | PHP_INI_ALL |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

intl.default_locale string

Installation
Resource Types
Installing/Configuring


Predefined Constants

INTL_MAX_LOCALE_LEN (integer)
Limit on locale length, set to 80 in PHP code. Locale names longer than this limit will not be accepted.
IDNA_DEFAULT (integer)
Prohibit processing of unassigned codepoints in the input for IDN functions and do not check if the input conforms to domain name ASCII rules.
IDNA_ALLOW_UNASSIGNED (integer)
Allow processing of unassigned codepoints in the input for IDN functions.
IDNA_USE_STD3_RULES (integer)
Check if the input for IDN functions conforms to domain name ASCII rules.

Resource Types
Examples
intl


Examples

Table of Contents

  • Basic usage of this extension
Predefined Constants
Basic usage of this extension
intl


Basic usage of this extension

Each module provides two kind of APIs: a procedural one and an object oriented one. Both are actually identical and described in the corresponding document.

Note: All input strings must be in UTF-8 encoding. All output strings are also in UTF-8.

Example #1 Example of using the procedural API

<?php
$coll  = collator_create('en_US');
$result = collator_compare($coll, "string#1", "string#2");
?>

Example #2 Example of using the object-oriented API

<?php
$coll = new Collator('en_US');
$al   = $coll->getLocale(Locale::ACTUAL_LOCALE);
echo "Actual locale: $al\n";

$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $formatter->format(1234567);
?>
Examples
Collator
Examples


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/intl.

If your ICU is installed to a non-standard directory then you might want to specify its location in LD_LIBRARY_PATH environment variable so that dynamic linker can find it:

$ export LD_LIBRARY_PATH=/opt/icu/lib

Otherwise, if PHP and ICU are installed to their default locations, then the additional options to `configure' are not needed.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To build the extension you need to install the » ICU library of version 3.6+.

The extension can be built with PHP 5.2, 5.2.4+ recommended. It is part of the PHP 5.3+ source tree.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
intl


Create a date formatter

IntlDateFormatter
IntlDateFormatter::format
IntlDateFormatter
PHP Manual

IntlDateFormatter::create

datefmt_create

IntlDateFormatter::__construct

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::create -- datefmt_create -- IntlDateFormatter::__construct — Create a date formatter

Description

Object oriented style

static IntlDateFormatter IntlDateFormatter::create ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )

Object oriented style (constructor)

IntlDateFormatter::__construct ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )

Procedural style

IntlDateFormatter datefmt_create ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )

Create a date formatter

Parameters

locale

Locale to use when formatting or parsing.

datetype

Date type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants.

timetype

Time type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants.

timezone

Time zone ID, default is system default.

calendar

Calendar to use for formatting or parsing; default is Gregorian. This is one of the IntlDateFormatter calendar constants.

pattern

Optional pattern to use when formatting or parsing. Possible patterns are documented at » http://userguide.icu-project.org/formatparse/datetime.

Return Values

Examples

Example #1 datefmt_create() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles', IntlDateFormatter::GREGORIAN  );
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".$fmt->format(0);

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
      'America/Los_Angeles',IntlDateFormatter::GREGORIAN , "MM/dd/yyyy");
echo "Second Formatted output with pattern is ".$fmt->format(0);
?>

The above example will output:

First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
First Formatted output with pattern is 12/31/1969
Second Formatted output with pattern is 12/31/1969

See Also

  • datefmt_format() - Format the date/time value as a string
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

IntlDateFormatter
IntlDateFormatter::format
IntlDateFormatter


Format the date/time value as a string

IntlDateFormatter::create
IntlDateFormatter::getCalendar
IntlDateFormatter
PHP Manual

IntlDateFormatter::format

datefmt_format

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::format -- datefmt_format — Format the date/time value as a string

Description

Object oriented style

string IntlDateFormatter::format ( mixed $value )

Procedural style

string datefmt_format ( IntlDateFormatter $fmt , mixed $value )

Formats the time value as a string.

Parameters

fmt

The date formatter resource.

value

Value to format. Can be integer for an Unix timestamp value (seconds since epoch, UTC) or array for a localtime() array.

Return Values

The formatted string or, if an error occurred, FALSE.

Examples

Example #1 datefmt_format() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".$fmt->format(0);

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN , "MM/dd/yyyy");
echo "Second Formatted output with pattern is ".$fmt->format(0);
?>

The above example will output:

First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
First Formatted output with pattern is 12/31/1969
Second Formatted output with pattern is 12/31/1969

See Also

  • datefmt_create() - Create a date formatter
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

IntlDateFormatter::create
IntlDateFormatter::getCalendar
IntlDateFormatter


Get the calendar used for the IntlDateFormatter

IntlDateFormatter::format
IntlDateFormatter::getDateType
IntlDateFormatter
PHP Manual

IntlDateFormatter::getCalendar

datefmt_get_calendar

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getCalendar -- datefmt_get_calendar — Get the calendar used for the IntlDateFormatter

Description

Object oriented style

int IntlDateFormatter::getCalendar ( void )

Procedural style

int datefmt_get_calendar ( IntlDateFormatter $fmt )

Parameters

fmt

The formatter resource

Return Values

The calendar being used by the formatter.

Examples

Example #1 datefmt_get_calendar() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "calendar of the formatter is : ".datefmt_get_calendar($fmt);
datefmt_set_calendar($fmt,IntlDateFormatter::TRADITIONAL);
echo "Now calendar of the formatter is : ".datefmt_get_calendar($fmt);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "calendar of the formatter is : ".$fmt->getCalendar();
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo "Now calendar of the formatter is : ".$fmt->getCalendar();

?>

The above example will output:

calendar of the formatter is : 1
Now calendar of the formatter is : 0

See Also

  • datefmt_set_calendar() - sets the calendar used to the appropriate calendar, which must be
  • datefmt_create() - Create a date formatter

IntlDateFormatter::format
IntlDateFormatter::getDateType
IntlDateFormatter


Get the datetype used for the IntlDateFormatter

IntlDateFormatter::getCalendar
IntlDateFormatter::getErrorCode
IntlDateFormatter
PHP Manual

IntlDateFormatter::getDateType

datefmt_get_datetype

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getDateType -- datefmt_get_datetype — Get the datetype used for the IntlDateFormatter

Description

Object oriented style

int IntlDateFormatter::getDateType ( void )

Procedural style

int datefmt_get_datetype ( IntlDateFormatter $fmt )

Returns date type used by the formatter.

Parameters

fmt

The formatter resource.

Return Values

The current date type value of the formatter.

Examples

Example #1 datefmt_get_datetype() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "datetype of the formatter is : ".datefmt_get_datetype($fmt);
echo "First Formatted output with datetype is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::SHORT,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Now datetype of the formatter is : ".datefmt_get_datetype($fmt);
echo "Second Formatted output with datetype is ".datefmt_format( $fmt , 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN);
echo "datetype of the formatter is : ".$fmt->getDateType();
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::SHORT,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN);
echo "Now datetype of the formatter is : ".$fmt->getDateType();
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

?>

The above example will output:

datetype of the formatter is : 0
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Now datetype of the formatter is : 2
Second Formatted output is 12/31/69 4:00:00 PM PT

See Also

  • datefmt_get_timetype() - Get the timetype used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getCalendar
IntlDateFormatter::getErrorCode
IntlDateFormatter


Get the error code from last operation

IntlDateFormatter::getDateType
IntlDateFormatter::getErrorMessage
IntlDateFormatter
PHP Manual

IntlDateFormatter::getErrorCode

datefmt_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorCode -- datefmt_get_error_code — Get the error code from last operation

Description

Object oriented style

int IntlDateFormatter::getErrorCode ( void )

Procedural style

int datefmt_get_error_code ( IntlDateFormatter $fmt )

Get the error code from last operation. Returns error code from the last number formatting operation.

Parameters

fmt

The formatter resource.

Return Values

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

Examples

Example #1 datefmt_get_error_code() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$str = datefmt_format($fmt);
if(!$str) {
    echo "ERROR: ".datefmt_get_error_message($fmt) . " (" . datefmt_get_error_code($fmt) . ")\n";
}
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$str = $fmt->format();
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>

The above example will output:

ERROR: U_ZERO_ERROR (0)

See Also

  • datefmt_get_error_message() - Get the error text from the last operation.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

IntlDateFormatter::getDateType
IntlDateFormatter::getErrorMessage
IntlDateFormatter


Get the error text from the last operation.

IntlDateFormatter::getErrorCode
IntlDateFormatter::getLocale
IntlDateFormatter
PHP Manual

IntlDateFormatter::getErrorMessage

datefmt_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorMessage -- datefmt_get_error_message — Get the error text from the last operation.

Description

Object oriented style

string IntlDateFormatter::getErrorMessage ( void )

Procedural style

string datefmt_get_error_message ( IntlDateFormatter $fmt )

Get the error text from the last operation.

Parameters

fmt

The formatter resource.

Return Values

Description of the last error.

Examples

Example #1 datefmt_get_error_message() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$str = datefmt_format($fmt);
if(!$str) {
    echo "ERROR: ".datefmt_get_error_message($fmt) . " (" . datefmt_get_error_code($fmt) . ")\n";
}
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$str = $fmt->format();
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}

?>

The above example will output:

ERROR: U_ZERO_ERROR (0)

See Also

  • datefmt_get_error_code() - Get the error code from last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

IntlDateFormatter::getErrorCode
IntlDateFormatter::getLocale
IntlDateFormatter


Get the locale used by formatter

IntlDateFormatter::getErrorMessage
IntlDateFormatter::getPattern
IntlDateFormatter
PHP Manual

IntlDateFormatter::getLocale

datefmt_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getLocale -- datefmt_get_locale — Get the locale used by formatter

Description

Object oriented style

string IntlDateFormatter::getLocale ([ int $which ] )

Procedural style

string datefmt_get_locale ( IntlDateFormatter $fmt [, int $which ] )

Get locale used by the formatter.

Parameters

fmt

The formatter resource

hich

You can choose between valid and actual locale ( Locale::VALID_LOCALE, Locale::ACTUAL_LOCALE, respectively). The default is the actual locale.

Return Values

the locale of this formatter or 'false' if error

Examples

Example #1 datefmt_get_locale() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "locale of the formatter is : ".datefmt_get_locale($fmt);
echo "First Formatted output is ".datefmt_format( $fmt , 0);
echo "locale of the formatter is : ".datefmt_get_locale($fmt);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "locale of the formatter is : ".$fmt->getLocale();
echo "First Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "locale of the formatter is : ".$fmt->getLocale();
echo "Second Formatted output is ".$fmt->format(0);

?>

The above example will output:

locale of the formatter is : en
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
locale of the formatter is : de
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00

See Also

  • datefmt_create() - Create a date formatter

IntlDateFormatter::getErrorMessage
IntlDateFormatter::getPattern
IntlDateFormatter


Get the pattern used for the IntlDateFormatter

IntlDateFormatter::getLocale
IntlDateFormatter::getTimeType
IntlDateFormatter
PHP Manual

IntlDateFormatter::getPattern

datefmt_get_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getPattern -- datefmt_get_pattern — Get the pattern used for the IntlDateFormatter

Description

Object oriented style

string IntlDateFormatter::getPattern ( void )

Procedural style

string datefmt_get_pattern ( IntlDateFormatter $fmt )

Get pattern used by the formatter.

Parameters

fmt

The formatter resource.

Return Values

The pattern string being used to format/parse.

Examples

Example #1 datefmt_get_pattern() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "pattern of the formatter is : ".datefmt_get_pattern($fmt);
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
datefmt_set_pattern($fmt,'yyyymmdd hh:mm:ss z');
echo "Now pattern of the formatter is : ".datefmt_get_pattern($fmt);
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN,"MM/dd/yyyy"  );
echo "pattern of the formatter is : ".$fmt->getPattern();
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo "Now pattern of the formatter is : ".$fmt->getPattern();
echo "Second Formatted output is ".datefmt_format( $fmt , 0);
?>

The above example will output:

pattern of the formatter is : MM/dd/yyyy
First Formatted output is 12/31/1969
Now pattern of the formatter is : yyyymmdd hh:mm:ss z
Second Formatted output is 19690031 04:00:00 PST

See Also

  • datefmt_set_pattern() - Set the pattern used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getLocale
IntlDateFormatter::getTimeType
IntlDateFormatter


Get the timetype used for the IntlDateFormatter

IntlDateFormatter::getPattern
IntlDateFormatter::getTimeZoneId
IntlDateFormatter
PHP Manual

IntlDateFormatter::getTimeType

datefmt_get_timetype

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeType -- datefmt_get_timetype — Get the timetype used for the IntlDateFormatter

Description

Object oriented style

int IntlDateFormatter::getTimeType ( void )

Procedural style

int datefmt_get_timetype ( IntlDateFormatter $fmt )

Return time type used by the formatter.

Parameters

fmt

The formatter resource.

Return Values

The current date type value of the formatter.

Examples

Example #1 datefmt_get_timetype() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "timetype of the formatter is : ".datefmt_get_timetype($fmt);
echo "First Formatted output with timetype is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::SHORT,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Now timetype of the formatter is : ".datefmt_get_timetype($fmt);
echo "Second Formatted output with timetype is ".datefmt_format( $fmt , 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN);
echo "timetype of the formatter is : ".$fmt->getTimeType();
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::SHORT,'America/Los_Angeles',IntlDateFormatter::GREGORIAN);
echo "Now timetype of the formatter is : ".$fmt->getTimeType();
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

?>

The above example will output:

timetype of the formatter is : 0
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Now timetype of the formatter is : 3
Second Formatted output is Wednesday, December 31, 1969 4:00 PM

See Also

  • datefmt_get_datetype() - Get the datetype used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getPattern
IntlDateFormatter::getTimeZoneId
IntlDateFormatter


Get the timezone-id used for the IntlDateFormatter

IntlDateFormatter::getTimeType
IntlDateFormatter::isLenient
IntlDateFormatter
PHP Manual

IntlDateFormatter::getTimeZoneId

datefmt_get_timezone_id

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeZoneId -- datefmt_get_timezone_id — Get the timezone-id used for the IntlDateFormatter

Description

Object oriented style

string IntlDateFormatter::getTimeZoneId ( void )

Procedural style

string datefmt_get_timezone_id ( IntlDateFormatter $fmt )

Get the timezone-id used for the IntlDateFormatter.

Parameters

fmt

The formatter resource.

Return Values

ID string for the time zone used by this formatter.

Examples

Example #1 datefmt_get_timezone_id() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "timezone_id of the formatter is : ".datefmt_get_timezone_id($fmt);
datefmt_set_timezone_id($fmt,'CN');
echo "Now timezone_id of the formatter is : ".datefmt_get_timezone_id($fmt);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "timezone_id of the formatter is : ".$fmt->getTimezoneId();
$fmt->setTimezoneId('CN');
echo "Now timezone_id of the formatter is : ".$fmt->getTimezoneId();

?>

The above example will output:

timezone_id of the formatter is : America/Los_Angeles
Now timezone_id of the formatter is : CN

See Also

  • datefmt_set_timezone_id() - Sets the time zone to use
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getTimeType
IntlDateFormatter::isLenient
IntlDateFormatter


Get the lenient used for the IntlDateFormatter

IntlDateFormatter::getTimeZoneId
IntlDateFormatter::localtime
IntlDateFormatter
PHP Manual

IntlDateFormatter::isLenient

datefmt_is_lenient

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::isLenient -- datefmt_is_lenient — Get the lenient used for the IntlDateFormatter

Description

Object oriented style

bool IntlDateFormatter::isLenient ( void )

Procedural style

bool datefmt_is_lenient ( IntlDateFormatter $fmt )

Check if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly.

Parameters

fmt

The formatter resource.

Return Values

TRUE if parser is lenient, FALSE if parser is strict. By default the parser is strict.

Examples

Example #1 datefmt_is_lenient() example

<?php
$fmt = datefmt_create( "en_US", IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/Los_Angeles', IntlDateFormatter::GREGORIAN, "dd/mm/yyyy");
echo "lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
datefmt_parse($fmt,"35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .datefmt_parse($fmt,"35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}
datefmt_set_lenient($fmt,false);
echo "Now lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
datefmt_parse($fmt,"35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .datefmt_parse($fmt,"35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter("en_US", IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/Los_Angeles', IntlDateFormatter::GREGORIAN, "dd/mm/yyyy"  );
echo "lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
$fmt->parse("35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

$fmt->setLenient(FALSE);
echo "Now lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
$fmt->parse("35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

?>

The above example will output:

lenient of the formatter is : TRUE
Trying to do parse('35/13/1971').
Result is : -2147483
Now lenient of the formatter is : FALSE
Trying to do parse('35/13/1971').
Result is : Error_msg is : Date parsing failed: U_PARSE_ERROR Error_code is : 9

See Also

  • datefmt_set_lenient() - Set the leniency of the parser
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getTimeZoneId
IntlDateFormatter::localtime
IntlDateFormatter


Parse string to a field-based time value

IntlDateFormatter::isLenient
IntlDateFormatter::parse
IntlDateFormatter
PHP Manual

IntlDateFormatter::localtime

datefmt_localtime

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::localtime -- datefmt_localtime — Parse string to a field-based time value

Description

Object oriented style

array IntlDateFormatter::localtime ( string $value [, int &$position ] )

Procedural style

array datefmt_localtime ( IntlDateFormatter $fmt , string $value [, int &$position ] )

Converts string $value to a field-based time value ( an array of various fields), starting at $parse_pos and consuming as much of the input value as possible.

Parameters

fmt

The formatter resource

value

string to convert to a time

position

Position at which to start the parsing in $value (zero-based). If no error occurs before $value is consumed, $parse_pos will contain -1 otherwise it will contain the position at which parsing ended . If $parse_pos > strlen($value), the parse fails immediately.

Return Values

Localtime compatible array of integers : contains 24 hour clock value in tm_hour field

Examples

Example #1 datefmt_localtime() example

<?php

$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$arr = datefmt_localtime( $fmt, "Wednesday, December 31, 1969 4:00:00 PM PT",0);
echo "First parsed output is ";
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$arr = $fmt->localtime( "Wednesday, December 31, 1969 4:00:00 PM PT",0);
echo "First parsed output is ";
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}

?>

The above example will output:

First parsed output is tm_sec : 0 , tm_min : 0 , tm_hour : 16 , tm_year : 1969 ,
tm_mday : 31 , tm_wday : 4 , tm_yday : 365 , tm_mon : 11 , tm_isdst : 0 ,

See Also

  • datefmt_create() - Create a date formatter
  • datefmt_format() - Format the date/time value as a string
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

IntlDateFormatter::isLenient
IntlDateFormatter::parse
IntlDateFormatter


Parse string to a timestamp value

IntlDateFormatter::localtime
IntlDateFormatter::setCalendar
IntlDateFormatter
PHP Manual

IntlDateFormatter::parse

datefmt_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::parse -- datefmt_parse — Parse string to a timestamp value

Description

Object oriented style

int IntlDateFormatter::parse ( string $value [, int &$position ] )

Procedural style

int datefmt_parse ( IntlDateFormatter $fmt , string $value [, int &$position ] )

Converts string $value to an incremental time value, starting at $parse_pos and consuming as much of the input value as possible.

Parameters

fmt

The formatter resource

value

string to convert to a time

position

Position at which to start the parsing in $value (zero-based). If no error occurs before $value is consumed, $parse_pos will contain -1 otherwise it will contain the position at which parsing ended (and the error occurred). This variable will contain the end position if the parse fails. If $parse_pos > strlen($value), the parse fails immediately.

Return Values

timestamp parsed value

Examples

Example #1 datefmt_parse() example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First parsed output is ".$fmt->parse("Wednesday, December 31, 1969 4:00:00 PM PT");
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second parsed output is ".$fmt->parse("Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00");
?>

Example #2 OO example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First parsed output is ".datefmt_parse( $fmt ,  "Wednesday, December 20, 1989 4:00:00 PM PT");
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second parsed output is ".datefmt_parse( $fmt , "Mittwoch, 20. Dezember 1989 16:00 Uhr GMT-08:00");
?>

The above example will output:

First parsed output is 630201600
Second parsed output is 630201600

See Also

  • datefmt_create() - Create a date formatter
  • datefmt_format() - Format the date/time value as a string
  • datefmt_localtime() - Parse string to a field-based time value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

IntlDateFormatter::localtime
IntlDateFormatter::setCalendar
IntlDateFormatter


sets the calendar used to the appropriate calendar, which must be

IntlDateFormatter::parse
IntlDateFormatter::setLenient
IntlDateFormatter
PHP Manual

IntlDateFormatter::setCalendar

datefmt_set_calendar

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setCalendar -- datefmt_set_calendar — sets the calendar used to the appropriate calendar, which must be

Description

Object oriented style

bool IntlDateFormatter::setCalendar ( int $which )

Procedural style

bool datefmt_set_calendar ( IntlDateFormatter $fmt , int $which )

Sets the calendar used by the formatter.

Parameters

fmt

The formatter resource.

which

The calendar to use. Default is IntlDateFormatter::GREGORIAN.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 datefmt_set_calendar() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "calendar of the formatter is : ".datefmt_get_calendar($fmt);
datefmt_set_calendar($fmt,IntlDateFormatter::TRADITIONAL);
echo "Now calendar of the formatter is : ".datefmt_get_calendar($fmt);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "calendar of the formatter is : ".$fmt->getCalendar();
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo "Now calendar of the formatter is : ".$fmt->getCalendar();
?>

The above example will output:

calendar of the formatter is : 1
Now calendar of the formatter is : 0

See Also

  • datefmt_get_calendar() - Get the calendar used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::parse
IntlDateFormatter::setLenient
IntlDateFormatter


Set the leniency of the parser

IntlDateFormatter::setCalendar
IntlDateFormatter::setPattern
IntlDateFormatter
PHP Manual

IntlDateFormatter::setLenient

datefmt_set_lenient

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setLenient -- datefmt_set_lenient — Set the leniency of the parser

Description

Object oriented style

bool IntlDateFormatter::setLenient ( bool $lenient )

Procedural style

bool datefmt_set_lenient ( IntlDateFormatter $fmt , bool $lenient )

Define if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly. Enabling lenient parsing allows the parser to accept otherwise flawed date or time patterns, parsing as much as possible to obtain a value. Extra space, unrecognized tokens, or invalid values ("February 30th") are not accepted.

Parameters

fmt

The formatter resource

lenient

Sets whether the parser is lenient or not, default is FALSE (strict).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 datefmt_set_lenient() example

<?php
$fmt = datefmt_create("en_US", IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/Los_Angeles', IntlDateFormatter::GREGORIAN, "dd/mm/yyyy");
echo "lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
datefmt_parse($fmt,"35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .datefmt_parse($fmt,"35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}
datefmt_set_lenient($fmt,false);
echo "Now lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
datefmt_parse($fmt,"35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .datefmt_parse($fmt,"35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter("en_US", IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/Los_Angeles', IntlDateFormatter::GREGORIAN, "dd/mm/yyyy");
echo "lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
$fmt->parse("35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

$fmt->setLenient(FALSE);
echo "Now lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
$fmt->parse("35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

?>

The above example will output:

lenient of the formatter is : TRUE
Trying to do parse('35/13/1971').
Result is : -2147483
Now lenient of the formatter is : FALSE
Trying to do parse('35/13/1971').
Result is : Error_msg is : Date parsing failed: U_PARSE_ERROR Error_code is : 9

See Also

  • datefmt_is_lenient() - Get the lenient used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::setCalendar
IntlDateFormatter::setPattern
IntlDateFormatter


Set the pattern used for the IntlDateFormatter

IntlDateFormatter::setLenient
IntlDateFormatter::setTimeZoneId
IntlDateFormatter
PHP Manual

IntlDateFormatter::setPattern

datefmt_set_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setPattern -- datefmt_set_pattern — Set the pattern used for the IntlDateFormatter

Description

Object oriented style

bool IntlDateFormatter::setPattern ( string $pattern )

Procedural style

bool datefmt_set_pattern ( IntlDateFormatter $fmt , string $pattern )

Set the pattern used for the IntlDateFormatter.

Parameters

fmt

The formatter resource.

pattern

New pattern string to use. Possible patterns are documented at » http://userguide.icu-project.org/formatparse/datetime.

Return Values

Returns TRUE on success or FALSE on failure. Bad formatstrings are usually the cause of the failure.

Examples

Example #1 datefmt_set_pattern() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "pattern of the formatter is : ".datefmt_get_pattern($fmt);
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
datefmt_set_pattern($fmt,'yyyymmdd hh:mm:ss z');
echo "Now pattern of the formatter is : ".datefmt_get_pattern($fmt);
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN,"MM/dd/yyyy"  );
echo "pattern of the formatter is : ".$fmt->getPattern();
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo "Now pattern of the formatter is : ".$fmt->getPattern();
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

?>

The above example will output:

pattern of the formatter is : MM/dd/yyyy
First Formatted output with pattern is 12/31/1969
Now pattern of the formatter is : yyyymmdd hh:mm:ss z
Second Formatted output with pattern is 19690031 04:00:00 PST

See Also

  • datefmt_get_pattern() - Get the pattern used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::setLenient
IntlDateFormatter::setTimeZoneId
IntlDateFormatter


Sets the time zone to use

IntlDateFormatter::setPattern
ResourceBundle
IntlDateFormatter
PHP Manual

IntlDateFormatter::setTimeZoneId

datefmt_set_timezone_id

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setTimeZoneId -- datefmt_set_timezone_id — Sets the time zone to use

Description

Object oriented style

bool IntlDateFormatter::setTimeZoneId ( string $zone )

Procedural style

bool datefmt_set_timezone_id ( IntlDateFormatter $fmt , string $zone )

Sets the time zone to use.

Parameters

fmt

The formatter resource.

zone

The time zone ID string of the time zone to use. If NULL or the empty string, the default time zone for the runtime is used.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 datefmt_set_timezone_id() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "timezone_id of the formatter is : ".datefmt_get_timezone_id($fmt);
datefmt_set_timezone_id($fmt,'CN');
echo "Now timezone_id of the formatter is : ".datefmt_get_timezone_id($fmt);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "timezone_id of the formatter is : ".$fmt->getTimezoneId();
$fmt->setTimezoneId('CN');
echo "Now timezone_id of the formatter is : ".$fmt->getTimezoneId();

?>

The above example will output:

timezone_id of the formatter is : America/Los_Angeles
Now timezone_id of the formatter is : CN

See Also

  • datefmt_get_timezone_id() - Get the timezone-id used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::setPattern
ResourceBundle
IntlDateFormatter


What can PHP do?

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

There are three main areas where PHP scripts are used.

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

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

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

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

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

  • Adabas D
  • dBase
  • Empress
  • FilePro (read-only)
  • Hyperwave
  • IBM DB2
  • Informix
  • Ingres
  • InterBase
  • FrontBase
  • mSQL
  • Direct MS-SQL
  • MySQL
  • ODBC
  • Oracle (OCI7 and OCI8)
  • Ovrimos
  • PostgreSQL
  • SQLite
  • Solid
  • Sybase
  • Velocis
  • Unix dbm

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

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

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

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

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

What is PHP?
A simple tutorial
Introduction


What is PHP?

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

Nice, but what does that mean? An example:

Example #1 An introductory example

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

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

    </body>
</html>

Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!"). The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of "PHP mode."

What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.

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

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

Introduction
What can PHP do?
Introduction


Introduction

The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.

APC
Installing/Configuring
APC


Introduction

APD is the Advanced PHP Debugger. It was written to provide profiling and debugging capabilities for PHP code, as well as to provide the ability to print out a full stack backtrace. APD supports interactive debugging, but by default it writes data to trace files. It also offers event based logging so that varying levels of information (including function calls, arguments passed, timings, etc.) can be turned on or off for individual scripts.

Caution

APD is a Zend Extension, modifying the way the internals of PHP handle function calls, and thus may or may not be compatible with other Zend Extensions (for example Zend Optimizer).

APD
Installing/Configuring
APD


Introduction

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

BC Math
Installing/Configuring
BC Math


Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

Bcompiler was written for several reasons:

  • To encode entire script in a proprietary PHP application
  • To encode some classes and/or functions in a proprietary PHP application
  • To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
  • To do the feasibility study for a PHP to C converter

The first of these goals is achieved using the bcompiler_write_header(), bcompiler_write_file() and bcompiler_write_footer() functions. The bytecode files can be written as either uncompressed or plain. To use the generated bytecode, you can simply include it with include or require statements.

The second of these goals is achieved using the bcompiler_write_header(), bcompiler_write_class(), bcompiler_write_footer(), bcompiler_read(), and bcompiler_load() functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load() reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file.

To create EXE type files, bcompiler has to be used with a modified sapi file or a version of PHP which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file.

bcompiler can improve performance by about 30% when used with uncompressed bytecodes only. But keep in mind that uncompressed bytecode can be up to 5 times larger than the original source code. Using bytecode compression can save your space, but decompression requires much more time than parsing a source. bcompiler also does not do any bytecode optimization, this could be added in the future...

In terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retrieve data from a bcompiled bytecode file - so don't put your private passwords or anything in it.

bcompiler
Installing/Configuring
bcompiler


Introduction

The bzip2 functions are used to transparently read and write bzip2 (.bz2) compressed files.

Bzip2
Installing/Configuring
Bzip2


Introduction

Cairo is a native PHP extension to create and modify graphics using the Cairo Graphics Library.

The Cairo Graphics Library is a 2D library written in C with support for multiple output devices. Currently supported output targets include the X Window System, Quartz, Win32, image buffers, PostScript, PDF, and SVG file output. Experimental backends include OpenGL (through glitz), XCB, BeOS, OS/2, and DirectFB. The library also has support for two types of text manipulation and layout. The "toy" API provides demo quality support, and the glyphs API, although full-featured, works best with a helper library such as pango. Font backend support includes FreeType, Quartz, Win32, and User fonts.

There are two types of computer graphics, vector and raster. Raster graphics are the representation of images as an array of pixels. Vector graphics use geometrical primitives such as points, lines, curves or polygons to represent images. The primitives are created using mathematical equations. The Cairo Graphics Library takes a vector approach to graphics, allowing smaller size, infinite zooming, and moving, scaling and rotating without degrading image quality.

Operations in the cairo graphics library including stroking and filling cubic Bézier splines, transforming and compositing translucent images, and antialiased text rendering. All drawing operations can be transformed by any affine transformation (scale, rotation, shear, and others) This is very similiar to drawing operations for PostScript and PDF drawing.

The Cairo PHP Extension aims to provide support for all officially supported font backends and surface backends, as well as expose all available functionality in cairo to PHP users.

Cairo
Installing/Configuring
Cairo


Introduction

The calendar extension presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on Julian Day Count, visit » http://www.hermetic.ch/cal_stud/jdn.htm. For more information on calendar systems visit » http://www.fourmilab.ch/documents/calendar/. Excerpts from this page are included in these instructions, and are in quotes.

Calendar
Installing/Configuring
Calendar


Introduction

These functions allow you to use the CrackLib library to test the 'strength' of a password. The 'strength' of a password is tested by that checks length, use of upper and lower case and checked against the specified CrackLib dictionary. CrackLib will also give helpful diagnostic messages that will help 'strengthen' the password.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.0.0.

Crack
Installing/Configuring
Crack


Introduction

Note: This extension is not available on Windows platforms.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.0.0.

Cyrus
Installing/Configuring
Cyrus


Introduction

These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.

Each component of date (e.g. year) is internally stored as 64-bit number so all imaginable dates (including negative years) are supported.

Note: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g. $date = strtotime('+7 days', $date) and not $date += 7*24*60*60) and leap years into consideration when working with these functions.

Note: The timezones referenced in this section can be found in the List of Supported Timezones.

Date/Time
Installing/Configuring
Date/Time


Introduction

These functions build the foundation for accessing Berkeley DB style databases.

This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as » Sleepycat Software's DB2. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)

DBA
Installing/Configuring
DBA


Introduction

These functions allow you to access records stored in dBase-format (dbf) databases.

dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and delete records are kept until you call dbase_pack().

The types of dBase fields available are:

Available types of fields
Field | dBase Type | Format | Additional information
M | Memo | n/a | This type is not supported by PHP, such field will be ignored
D | Date | YYYYMMDD | The field length is limited to 8
N | Number | A number | You must declare a length and a precision (the number of digits after the decimal point)
C | String | A string | You must declare a length. When retrieving data, the string will be right-padded with spaces to fit the declared length.
L | Boolean | T or Y for TRUE, F or N for FALSE | Stored and returned as an integer (1 or 0)
F | Float | A float number | Support for this type of field was added in PHP 5.2.0

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

Warning

There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent web server processes modifying the same dBase file will very likely ruin your database.

We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; » MySQL or » Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.

dBase
Installing/Configuring
dBase


Introduction

db++, made by the German company » Concept asa, is a relational database system with high performance and low memory and disk usage in mind. While providing SQL as an additional language interface, it is not really a SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra than SQL is.

Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

DB++
Installing/Configuring
DB++


Introduction

The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

dbx
Installing/Configuring
dbx


Introduction

PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO functions should be considered only when direct control of a device is needed. In all other cases, the standard filesystem functions are more than adequate.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

This extension is only available on Windows Platforms as of PHP 5.0.0

Direct IO
Installing/Configuring
Direct IO


Introduction

Enchant is the PHP binding for the » Enchant library. Enchant steps in to provide uniformity and conformity on top of all spelling libraries, and implement certain features that may be lacking in any individual provider library. Everything should "just work" for any and every definition of "just working."

Enchat supports the following backends:

  • Aspell/Pspell (intends to replace Ispell)

  • Ispell (old as sin, could be interpreted as a defacto standard)

  • MySpell/Hunspell (an OOo projects, also used by Mozilla)

  • Uspell (primarily Yiddish, Hebrew, and Eastern European languages - hosted in AbiWord's CVS under the module "uspell")

  • Hspell (Hebrew)

  • AppleSpell (Mac OSX)

Enchant
Installing/Configuring
Enchant


Introduction

These are functions dealing with error handling and logging. They allow you to define your own error handling rules, as well as modify the way the errors can be logged. This allows you to change and enhance error reporting to suit your needs.

With the logging functions, you can send messages directly to other machines, to an email (or email to pager gateway!), to system logs, etc., so you can selectively log and monitor the most important parts of your applications and websites.

The error reporting functions allow you to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors.

Error Handling
Installing/Configuring
Error Handling


Introduction

Those functions provide means to execute commands on the system itself, and means to secure such commands.

Note: All execution functions call the commands through cmd.exe under Windows. Therefore the user calling these functions needs appropriate privilege to run this command. The only exception is proc_open() with bypass_shell option.

Program execution
Installing/Configuring
Program execution


Introduction

With the exif extension you are able to work with image meta data. For example, you may use exif functions to read meta data of pictures taken from digital cameras by working with information stored in the headers of the JPEG and TIFF images.

Exif
Installing/Configuring
Exif


Introduction

This extension allows to interact with processes through PTY. You may consider using the expect:// wrapper with the filesystem functions which provide a simpler and more intuitive interface.

Expect
Installing/Configuring
Expect


Introduction

These functions allow you to access FrontBase database servers. More information about FrontBase can be found at » http://www.frontbase.com/.

Documentation for FrontBase can be found at » http://www.frontbase.com/cgi-bin/WebObjects/FrontBase.woa/wa/productsPage?currentPage=Documentation.

Frontbase support has been added to PHP 4.0.6.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

FrontBase
Installing/Configuring
FrontBase


Introduction

Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at » http://partners.adobe.com/asn/acrobat/forms.jsp for more information on what FDF is and how it is used in general.

The general idea of FDF is similar to HTML forms. The difference is basically the format how data is transmitted to the server when the submit button is pressed (this is actually the Form Data Format) and the format of the form itself (which is the Portable Document Format, PDF). Processing the FDF data is one of the features provided by the fdf functions. But there is more. One may as well take an existing PDF form and populated the input fields with data without modifying the form itself. In such a case one would create a FDF document (fdf_create()) set the values of each input field (fdf_set_value()) and associate it with a PDF form (fdf_set_file()). Finally it has to be sent to the browser with MimeType application/vnd.fdf. The Acrobat reader plugin of your browser recognizes the MimeType, reads the associated PDF form and fills in the data from the FDF document.

If you look at an FDF-document with a text editor you will find a catalogue object with the name FDF. Such an object may contain a number of entries like Fields, F, Status etc.. The most commonly used entries are Fields which points to a list of input fields, and F which contains the filename of the PDF-document this data belongs to. Those entries are referred to in the FDF documentation as /F-Key or /Status-Key. Modifying this entries is done by functions like fdf_set_file() and fdf_set_status(). Fields are modified with fdf_set_value(), fdf_set_opt() etc..

FDF
Installing/Configuring
FDF


Introduction

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

Fileinfo
Installing/Configuring
Fileinfo


Introduction

These functions allow read-only access to data stored in filePro databases.

filePro is a registered trademark of fP Technologies, Inc. You can find more information about filePro at » http://www.fptech.com/.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.2.0.

filePro
Installing/Configuring
filePro


Introduction

No external libraries are needed to build this extension, but if you want PHP to support LFS (large files) on Linux, then you need to have a recent glibc and you need compile PHP with the following compiler flags: -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64.

Filesystem
Installing/Configuring
Filesystem


Introduction

FriBiDi is a free implementation of the » Unicode Bidirectional Algorithm.

FriBiDi
Installing/Configuring
FriBiDi


Introduction

The GeoIP extension allows you to find the location of an IP address. City, State, Country, Longitude, Latitude, and other information as all, such as ISP and connection type can be obtained with the help of GeoIP.

GeoIP
Installing/Configuring
GeoIP


Introduction

The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation for your system for a thorough explanation of these functions or view the docs at » http://www.gnu.org/software/gettext/manual/gettext.html.

Gettext
Installing/Configuring
Gettext


Introduction

Gmagick is a php extension to create, modify and obtain meta information of images using the GraphicsMagick API.

GraphicsMagick prides itself as the swiss army knife of image processing. It works with over 88 major formats including important formats like DPX, GIF, JPEG, JPEG-2000, PNG, PDF, PNM, and TIFF.

Gmagick consists of a main Gmagick class, a GmagickDraw class which is in effect a drawing wand and a GmagickPixel class of which instances represent a single pixel of an image (color, opacity).

Gmagick
Installing/Configuring
Gmagick


Introduction

These functions allow you to work with arbitrary-length integers using the GNU MP library.

These functions have been added in PHP 4.0.4.

Note: Most GMP functions accept GMP number arguments, defined as resource below. However, most of these functions will also accept numeric and string arguments, given that it is possible to convert the latter to a number. Also, if there is a faster function that can operate on integer arguments, it would be used instead of the slower function when the supplied arguments are integers. This is done transparently, so the bottom line is that you can use integers in every function that expects GMP number. See also the gmp_init() function.

Warning

If you want to explicitly specify a large integer, specify it as a string. If you don't do that, PHP will interpret the integer-literal first, possibly resulting in loss of precision, even before GMP comes into play.

Note: This extension is available on Windows platforms since PHP 5.1.0.

GMP
Installing/Configuring
GMP


Introduction

This module allows you to interact with » gnupg.

GnuPG
Installing/Configuring
GnuPG


Introduction

The PECL/haru extension provides bindings to the libHaru library. libHaru is a free, cross platform, and Open Source library for generating PDF files.

The Haru library (libHaru) may be found here: » http://libharu.org.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

haru
Installing/Configuring
haru


Introduction

Message Digest (hash) engine. Allows direct or incremental processing of arbitrary length messages using a variety of hashing algorithms.

Hash
Installing/Configuring
Hash


Introduction

The htscanner extension gives the possibility to use htaccess-like file to configure PHP per directory, just like apache's htaccess. It is especially useful with fastcgi (ISS5/6/7, lighttpd, etc.).

htscanner
Installing/Configuring
htscanner


Introduction

I18n (short for internationalization) are means of adapting an application for different languages and cultures. The scope of i18n support includes support for local date and time, currency, measures, number formatting and strings in different encoding. Native support for i18n and l10n (localization) appeared in PHP6.

Please note that in PHP6, POSIX locales are obsoleted by the set of locales included with the ICU library.

Warning

This extension is still in development and it isn't available to public yet.

i18n
Installing/Configuring
i18n


Introduction

Firebird/InterBase is a relational database offering many ANSI SQL-92 features that runs on Linux, Windows, and a variety of Unix platforms. Firebird/InterBase offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. It has been used in production systems, under a variety of names since 1981.

InterBase is the name of the closed-source variant of this RDBMS that was developed by Borland/Inprise. More information about InterBase is available at » http://www.borland.com/interbase/.

Firebird is a commercially independent project of C and C++ programmers, technical advisors and supporters developing and enhancing a multi-platform relational database management system based on the source code released by Inprise Corp (now known as Borland Software Corp) under the InterBase Public License v.1.0 on 25 July, 2000. More information about Firebird is available at » http://www.firebirdsql.org/.

Note: This extension supports InterBase versions 5 and up and all versions of Firebird. Support for InterBase version 5.x will be dropped in PHP 5.
This database uses a single quote (') character for escaping, a behavior similar to the Sybase database, add to your php.ini the following directive:

magic_quotes_sybase = On

Firebird/InterBase
Installing/Configuring
Firebird/InterBase


Introduction

These functions enable you to access IBM DB2 Universal Database, IBM Cloudscape, and Apache Derby databases using the DB2 Call Level Interface (DB2 CLI).

IBM DB2
Installing/Configuring
IBM DB2


Introduction

This module contains an interface to iconv character set conversion facility. With this module, you can turn a string represented by a local character set into the one represented by another character set, which may be the Unicode character set. Supported character sets depend on the iconv implementation of your system. Note that the iconv function on some systems may not work as you expect. In such case, it'd be a good idea to install the » GNU libiconv library. It will most likely end up with more consistent results.

Since PHP 5.0.0, this extension comes with various utility functions that help you to write multilingual scripts. Let's have a look at the following sections to explore the new features.

iconv
Installing/Configuring
iconv


Introduction

These functions let you read and manipulate ID3 tags. ID3 tags are used in MP3 files to store title of the song, as well as information about the artist, album, genre, year and track number.

Since version 0.2 it is also possible to extract text frames from ID3 v2.2+ tags.

ID3
Installing/Configuring
ID3


Introduction

The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 is implemented in "ifx.ec" and "php_informix.h" in the informix extension directory. IDS 7.x support is fairly complete, with full support for BYTE and TEXT columns. IUS 9.x support is partly finished: the new data types are there, but SLOB and CLOB support is still under construction.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.2.1.

Informix
Installing/Configuring
Informix


Introduction

PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including GIF, PNG, JPEG, WBMP, and XPM. Even more convenient, PHP can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.

With the exif extension, you are able to work with information stored in headers of JPEG and TIFF images. This way you can read meta data generated by digital cameras. The exif functions do not require the GD library.

Note: Read the requirements section about how to expand image capabilities to read, write and modify images. To read meta data of pictures taken by digital cameras you need the above mentioned exif extension.

Note: The getimagesize() function does not require the GD extension.

GD
Installing/Configuring
GD


Introduction

Imagick is a native php extension to create and modify images using the ImageMagick API.

ImageMagick® is a software suite to create, edit, and compose bitmap images.. It can read, convert and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF.

Copyright 1999-2007 ImageMagick Studio LLC, a non-profit organization dedicated to making software imaging solutions freely available.

ImageMagick
Installing/Configuring
ImageMagick


Introduction

These functions enable you to operate with the IMAP protocol, as well as the NNTP, POP3 and local mailbox access methods.

Be warned, however, that some IMAP functions will not work correctly with the POP protocol.

IMAP
Installing/Configuring
IMAP


Introduction

Traces through and dumps the hierarchy of file inclusions and class inheritance at runtime.

The files may have been included using include(), include_once(), require(), or require_once().

Class inheritance dependencies are also reported.

inclued
Installing/Configuring
inclued


Introduction

This functions enable you to get a lot of information about PHP itself, e.g. runtime configuration, loaded extensions, version and much more. You'll also find functions to set options for your running PHP. The probably best known function of PHP - phpinfo() - can be found here.

PHP Options/Info
Installing/Configuring
PHP Options/Info


Introduction

The Ingres driver for PHP enables you to connect to and query the Ingres DBMS, EDBC, and Enterprise Access Gateways.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Ingres
Installing/Configuring
Ingres


Introduction

The inotify extension exposes the inotify functions inotify_init(), inotify_add_watch() and inotify_rm_watch().

As the C inotify_init() function returns a file descriptor, PHP's inotify_init() returns a stream resource, usable with standard stream functions, like stream_select(), stream_set_blocking() and fclose(). inotify_read() replaces the C way of reading inotify events.

Inotify
Installing/Configuring
Inotify


Introduction

Internationalization extension (further is referred as Intl) is a wrapper for » ICU library, enabling PHP programmers to perform UCA-conformant collation and date/time/number/currency formatting in their scripts.

It tends to closely follow ICU APIs, so that people having experience working with ICU in either C/C++ or Java could easily use the PHP API. Also, this way ICU documentation would be useful to understand various ICU functions.

Intl consists of several modules, each of them exposes the corresponding ICU API:

  • Collator: provides string comparison capability with support for appropriate locale-sensitive sort orderings.
  • Number Formatter: allows to display number according to the localized format or given pattern or set of rules, and to parse strings into numbers.
  • Message Formatter: allows to create messages incorporating data (such as numbers or dates) formatted according to given pattern and locale rules, and parse messages extracting data from them.
  • Normalizer: provides a function to transform text into one of the Unicode normalization forms, and provides a routine to test if a given string is already normalized.
  • Locale: provides interaction with locale identifiers in the form of functions to get subtags from locale identifier; parse, compose, match(lookup and filter) locale identifiers.

Links

  • » Miscellaneous ICU docs

  • » ICU User Guide

  • » Unicode Collation Algorithm

intl
Installing/Configuring
intl


Introduction

This extension implements the » JavaScript Object Notation (JSON) data-interchange format. The decoding is handled by a parser based on the JSON_checker by Douglas Crockford.

JSON
Installing/Configuring
JSON


Introduction

These package allows you to access Kerberos V administration servers. You can create, modify, and delete Kerberos V principals and policies.

More information about Kerberos can be found at » http://web.mit.edu/kerberos/www/.

Documentation for Kerberos and KADM5 can be found at » http://web.mit.edu/kerberos/www/krb5-1.2/krb5-1.2.8/doc/admin_toc.html.

KADM5
Installing/Configuring
KADM5


Introduction

KTaglib is an object oriented binding to the taglib library from the KDE project used in projects like Amarok to read and write ID3 and Ogg tags. The library also provides access to audio information. The bindings are designed usually follow the underlying C++ API, but were changed whenever there is a more PHP-like way.

Note: At the moment ktaglib is able to read and write ID3v1 and ID3v2 tags.

KTaglib
Installing/Configuring
KTaglib


Introduction

Libevent is a library that provides a mechanism to execute a callback function when a specific event occurs on a file descriptor or after a timeout has been reached.

More information about Libevent can be found at » http://www.monkey.org/~provos/libevent/.

Libevent
Installing/Configuring
Libevent


Introduction

LZF is a very fast compression algorithm, ideal for saving space with only slight speed cost. It can be optimized for speed or space at the time of compilation. This extension is using » liblzf library by Marc Lehmann for its operations.

LZF
Installing/Configuring
LZF


Introduction

The mail() function allows you to send mail.

Mail
Installing/Configuring
Mail


Introduction

Mailparse is an extension for parsing and working with email messages. It can deal with » RFC 822 and » RFC 2045 (MIME) compliant messages.

Mailparse is stream based, which means that it does not keep in-memory copies of the files it processes - so it is very resource efficient when dealing with large messages.

Note: Mailparse requires the mbstring extension, and mbstring must be loaded before mailparse.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 4.2.0.

Mailparse
Installing/Configuring
Mailparse


Introduction

These math functions will only handle values within the range of the integer and float types on your computer (this corresponds currently to the C types long resp. double). If you need to handle bigger numbers, take a look at the arbitrary precision math functions.

See also the manual page on arithmetic operators.

Math
Installing/Configuring
Math


Introduction

The MaxDB PHP extension allows you to access the functionality provided by MaxDB 7.5.0 and above. More information about the MaxDB Database server can be found at » http://www.sdn.sap.com/irj/sdn/maxdb.

The MaxDB PHP extension is compatible to the MySQL mysqli extension. There are only minor differences in the behaviour of some functions due to the differences of the underlying database servers, MaxDB and MySQL.

The main differences to mysqli are in the following functions:

  • maxdb_character_set_name() - Returns only ascii or unicode.
  • maxdb_get_client_info() - Returns a different version string.
  • maxdb_get_client_version() - Returns a different version string.
  • maxdb_get_host_info() - Returns localhost or hostname.
  • maxdb_get_server_info() - Returns a different version string.
  • maxdb_get_server_version() - Returns a different version string.
  • maxdb_kill() - Only disconnects the session.
  • maxdb_multi_query() - Can not handle multiple SQL statements.
  • maxdb_next_result() - Function returns always false.
  • maxdb_options() - Supports a different set of options.
  • maxdb_report() - Supports a different report mode.
  • maxdb_stat() - Returns a different system status string.
  • maxdb_stmt_store_result() - Is not necessary for MaxDB.
  • maxdb_store_result() - Is not necessary for MaxDB.

Documentation for MaxDB can be found at » http://maxdb.sap.com/documentation/.

MaxDB
Installing/Configuring
MaxDB


Introduction

While there are many languages in which every necessary character can be represented by a one-to-one mapping to an 8-bit value, there are also several languages which require so many characters for written communication that they cannot be contained within the range a mere byte can code (A byte is made up of eight bits. Each bit can contain only two distinct values, one or zero. Because of this, a byte can only represent 256 unique values (two to the power of eight)). Multibyte character encoding schemes were developed to express more than 256 characters in the regular bytewise coding system.

When you manipulate (trim, split, splice, etc.) strings encoded in a multibyte encoding, you need to use special functions since two or more consecutive bytes may represent a single character in such encoding schemes. Otherwise, if you apply a non-multibyte-aware string function to the string, it probably fails to detect the beginning or ending of the multibyte character and ends up with a corrupted garbage string that most likely loses its original meaning.

mbstring provides multibyte specific string functions that help you deal with multibyte encodings in PHP. In addition to that, mbstring handles character encoding conversion between the possible encoding pairs. mbstring is designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience (listed below).

Multibyte String
Installing/Configuring
Multibyte String


Introduction

This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free". CFB/OFB are 8bit by default.

Mcrypt
Installing/Configuring
Mcrypt


Introduction

These functions interface the MCVE (Monetra) API (libmonetra, formerly known as libmcve), allowing you to work directly with MCVE/Monetra from your PHP scripts. MCVE/Monetra is Main Street Softworks' solution to direct credit/debit/gift card processing for Linux/Unix/MacOSX/Windows ( » http://www.mainstreetsoftworks.com/ ). It lets you directly address the credit card clearing houses via your *nix box, modem and/or internet connection (bypassing the need for an additional service such as Authorize.Net or Pay Flow Pro). Using the MCVE/Monetra module for PHP, you can process credit cards directly through MCVE/Monetra via your PHP scripts. The following references will outline the process.

Note: MCVE/Monetra is the replacement for RedHat's CCVS. They contracted with RedHat in late 2001 to migrate all existing clientele to the MCVE platform.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Note: This extension is not available on Windows platforms.

MCVE
Installing/Configuring
MCVE


Introduction

The purpose of this extension is to detect the most memory hungry scripts and functions.

memtrack tracks memory consumption in PHP scripts and produces reports (warnings) when the consumption reaches certain levels set by the user. This is achieved by replacing default executor function by a special function which compares memory usage before and after running the original executor - this way we can tell how much the memory usage has changed during the execution of the current part of the code.

Zend Engine runs its executor for each opcode array (op_array), which usually means function, plain script and such, so memtrack doesn't have any noticeable effect on performance.

memtrack doesn't provide any functions, there are only INI directives which allow you to configure the way it should work.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

Memtrack
Installing/Configuring
Memtrack


Introduction

These functions are intended to work with » mhash. Mhash can be used to create checksums, message digests, message authentication codes, and more.

This is an interface to the mhash library. mhash supports a wide variety of hash algorithms such as MD5, SHA1, GOST, and many others. For a complete list of supported hashes, refer to the documentation of mhash. The general rule is that you can access the hash algorithm from PHP with MHASH_HASHNAME. For example, to access TIGER you use the PHP constant MHASH_TIGER.

Note: This extension is obsoleted by Hash.

Mhash
Installing/Configuring
Mhash


Introduction

Warning

This extension has been deprecated as the PECL extension Fileinfo provides the same functionality (and more) in a much cleaner way.

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

This extension is derived from Apache mod_mime_magic, which is itself based on the file command maintained by Ian F. Darwin. See the source code for further historic and copyright information.

Mimetype
Installing/Configuring
Mimetype


Introduction

First of all: Ming is not an acronym. Ming is an open-source (LGPL) library which allows you to create SWF ("Flash") format movies. Ming supports almost all of Flash 4's features, including: shapes, gradients, bitmaps (pngs and jpegs), morphs ("shape tweens"), text, buttons, actions, sprites ("movie clips"), streaming mp3, and color transforms --the only thing that's missing is sound events.

Note that all values specifying length, distance, size, etc. are in "twips", twenty units per pixel. That's pretty much arbitrary, though, since the player scales the movie to whatever pixel size is specified in the embed/object tag, or the entire frame if not embedded.

Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them. Ming provides some insulation from the mundane details of the SWF file format, wrapping the movie elements in PHP objects. Also, Ming is still being maintained; if there's a feature that you want to see, just let us know at » http://www.libming.org/.

Ming was added in PHP 4.0.5.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

Ming
Installing/Configuring
Ming


Introduction

These functions were placed here because none of the other categories seemed to fit.

Misc.
Installing/Configuring
Misc.


Introduction

These functions allow you to access mSQL database servers. More information about mSQL can be found at » http://www.hughes.com.au/.

mSQL
Installing/Configuring
mSQL


Introduction

These functions allow you to access MS SQL Server database.

SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://www.microsoft.com/sqlserver/2005/en/us/PHP-Driver.aspx. The documentation is available at » http://msdn.microsoft.com/en-us/library/cc296221.aspx

Mssql
Installing/Configuring
Mssql


Introduction

These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.

Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

For an overview of MySQL database connectivity terms and products see Overview.

MySQL
Installing/Configuring
MySQL


Introduction

The mysqli extension allows you to access the functionality provided by MySQL 4.1 and above. More information about the MySQL Database server can be found at » http://www.mysql.com/

An overview of software available for using MySQL from PHP can be found at Overview

Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

Parts of this documentation included from MySQL manual with permissions of Sun Microsystems, Inc.

Examples

All examples in the mysqli documentation use the world database from Sun Microsystems, Inc. The world database can be found at » http://downloads.mysql.com/docs/world.sql.gz

Mysqli
Overview
Mysqli


Introduction

This section of the manual provides an overview of the MySQL Native Driver.

Mysqlnd
Overview
Mysqlnd


Introduction

ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant using PHP from the command line.

The features available, such as colors, depend on the terminal that you are using. Use functions such as ncurses_has_colors(), ncurses_can_change_color(), and ncurses_has_ic() to check for individual capabilities.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

ncurses is available for the following platforms:

  • AIX
  • BeOS
  • BSD variants (FreeBSD, NetBSD, OpenBSD)
  • Cygwin
  • Digital Unix (aka OSF1)
  • GNU/Linux
  • HPUX
  • IRIX64
  • Mac OS X
  • OS/2
  • QNX
  • SCO OpenServer
  • Solaris
  • Tru64

Ncurses
Installing/Configuring
Ncurses


Introduction

This is a PHP language extension for RedHat Newt library, a terminal-based window and widget library for writing applications with user friendly interface. Once this extension is enabled in PHP it will provide the use of Newt widgets, such as windows, buttons, checkboxes, radiobuttons, labels, editboxes, scrolls, textareas, scales, etc. Use of this extension if very similar to the original Newt API of C programming language.

Newt
Installing/Configuring
Newt


Introduction

These functions allow you to access Oracle Database 11g, 10g, 9i and 8i. They support SQL and PL/SQL statements. Basic features include transaction control, binding of PHP variables to Oracle placeholders, and support for large object (LOB) types and collections. Oracle's scalability features such as Database Resident Connection Pooling (DRCP) and result caching are also supported.

OCI8
Installing/Configuring
OCI8


Introduction

The OGG/Vorbis file format, as defined by » http://www.vorbis.com/, is a scheme for compressing audio streams by multiple factors with a minimum of quality loss. This extension adds Ogg Vorbis support to PHP's URL Wrappers. When used in read mode, compressed OGG/Vorbis data is expanded to raw PCM audio in one of six PCM encoding formats listed below.

oggvorbis
Installing/Configuring
oggvorbis


Introduction

Platform independent audio bindings. Requires the » OpenAL library.

OpenAL
Installing/Configuring
OpenAL


Introduction

This module uses the functions of » OpenSSL for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data. OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future.

OpenSSL
Installing/Configuring
OpenSSL


Introduction

The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.

Note: When upgrading from PHP 4.1.x (and 4.2.x) to 4.3.x due to a bug in earlier versions you must ensure that implict_flush is OFF in your php.ini, otherwise any output with ob_start() will not be hidden from output.

Output Control
Installing/Configuring
Output Control


Introduction

The purpose of this extension is to allow overloading of object property access and method calls. Only one function is defined in this extension, overload() which takes the name of the class that should have this functionality enabled. The class named has to define appropriate methods if it wants to have this functionality: __get(), __set() and __call() respectively for getting/setting a property, or calling a method. This way overloading can be selective. Inside these handler functions the overloading is disabled so you can access object properties normally.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

Warning

This extension is not a part of PHP 5. PHP 5 supports __get(), __set() and __call() natively. See the Overloading in PHP 5 page for more information.

Object overloading
Installing/Configuring
Object overloading


Introduction

Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 4.4.5 and PHP 5.1.0.

Note: This extension is not available on Windows platforms.

Ovrimos SQL
Installing/Configuring
Ovrimos SQL


Introduction

This module allows to read and write Paradox databases, primary index files and blob files. Write support has been proven to be quite reliable, though due to lack of documentation the produced files may not in any case be readable by other applications. Encrypted databases can be read without specifying a password if pxlib >= 0.5.0 is used.

Note: This module is also in development and may change, though I don't expect major changes to the API.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

Paradox
Installing/Configuring
Paradox


Introduction

These functions allow runtime analysis of opcodes compiled from PHP scripts.

Parsekit
Installing/Configuring
Parsekit


Introduction

Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

This documentation is intended to explain the general usage of each of the Process Control functions. For detailed information about Unix process control you are encouraged to consult your systems documentation including fork(2), waitpid(2) and signal(2) or a comprehensive reference such as Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).

PCNTL now uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You use the declare() statement to specify the locations in your program where callbacks are allowed to occur. This allows you to minimize the overhead of handling asynchronous events. In the past, compiling PHP with pcntl enabled would always incur this overhead, whether or not your script actually used pcntl.

There is one adjustment that all pcntl scripts prior to PHP 4.3.0 must make for them to work which is to either to use declare() on a section where you wish to allow callbacks or to just enable it across the entire script using the new global syntax of declare().

Note: This extension is not available on Windows platforms.

PCNTL
Installing/Configuring
PCNTL


Introduction

The PDF functions in PHP can create PDF files using the PDFlib library which was initially created by Thomas Merz and is now maintained by » PDFlib GmbH.

The documentation in this section is only meant to be an overview of the available functions in the PDFlib library and should not be considered an exhaustive reference. For the full and detailed explanation of each function, consult the PDFlib Reference Manual which is included in all PDFlib packages distributed by PDFlib GmbH. It provides a very good overview of what PDFlib is capable of doing and contains the most up-to-date documentation of all functions.

For a jump start we urge you to take a look at the programming samples which are contained in all PDFlib distribution packages. These samples demonstrate basic text, vector, and graphics output as well as higher-level functions, such as the PDF import facility (PDI).

All of the functions in PDFlib and the PHP module have identical function names and parameters. Unless configured otherwise, all lengths and coordinates are measured in PostScript points. There are generally 72 PostScript points to an inch, but this depends on the output resolution. Please see the PDFlib Reference Manual included in the PDFlib distribution for a more thorough explanation of the coordinate system used.

With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. The main difference is the following:

In PHP 4, first a PDF resource has to be retrieved with a function call like

$p = PDF_new().

This PDF resource is used as the first parameter in all further function calls, such as in

PDF_begin_document($p, "", "").

In PHP 5 however, a PDFlib object is created with

$p = new PDFlib().

This object offers all PDFlib API functions as methods, e.g. as with

$p->begin_document("", "").

In addition, exceptions have been introduced in PHP 5 which are supported by PDFlib 6 and later as well.

Please see the examples below for more information.

Note: If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.

PDF
Installing/Configuring
PDF


Introduction

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server.

PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. PDO does not provide a database abstraction; it doesn't rewrite SQL or emulate missing features. You should use a full-blown abstraction layer if you need that facility.

PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.

PDO
Installing/Configuring
PDO


Introduction

PostgreSQL database is Open Source product and available without cost. Postgres, developed originally in the UC Berkeley Computer Science Department, pioneered many of the object-relational concepts now becoming available in some commercial databases. It provides SQL92/SQL99 language support, transactions, referential integrity, stored procedures and type extensibility. PostgreSQL is an open source descendant of this original Berkeley code.

PostgreSQL
Installing/Configuring
PostgreSQL


Introduction

The phar extension provides a way to put entire PHP applications into a single file called a "phar" (PHP Archive) for easy distribution and installation. In addition to providing this service, the phar extension also provides a file-format abstraction method for creating and manipulating tar and zip files through the PharData class, much as PDO provides a unified interface for accessing different databases. Unlike PDO, which cannot convert between different databases, Phar also can convert between tar, zip and phar file formats with a single line of code. see Phar::convertToExecutable() for one example.

What is phar? Phar archives are best characterized as a convenient way to group several files into a single file. As such, a phar archive provides a way to distribute a complete PHP application in a single file and run it from that file without the need to extract it to disk. Additionally, phar archives can be executed by PHP as easily as any other file, both on the commandline and from a web server. Phar is kind of like a thumb drive for PHP applications.

Phar implements this functionality through a Stream Wrapper. Normally, to use an external file within a PHP script, you would use include()

Example #1 Using an external file

<?php
 include '/path/to/external/file.php';
 ?>

PHP can be thought of as actually translating /path/to/external/file.php into a stream wrapper as file:///path/to/external/file.php, and under the hood it does in fact use the plain file stream wrapper stream functions to access all local files.

To use a file named file.php contained with a phar archive /path/to/myphar.phar, the syntax is very similar to the file:// syntax above.

Example #2 Using a file within a phar archive

<?php
 include 'phar:///path/to/myphar.phar/file.php';
 ?>

In fact, one can treat a phar archive exactly as if it were an external disk, using any of fopen()-related functions, opendir() and mkdir()-related functions to read, change, or create new files and directories within the phar archive. This allows complete PHP applications to be distributed in a single file and run directly from that file.

The most common usage for a phar archive is to distribute a complete application in a single file. For instance, the PEAR Installer that is bundled with PHP versions is distributed as a phar archive. To use a phar archive distributed in this way, the archive can be executed on the command-line or via a web server.

Phar archives can be distributed as tar archives, zip archives, or as the custom phar file format designed specifically for the phar extension. Each file format has advantages and disadvantages. The tar and zip file formats can be read or extracted by any third-party tool that can read the format, but require the phar extension in order to run with PHP. The phar file format is customized and unique to the phar extension, and can only be created by the phar extension or the PEAR package » PHP_Archive, but has the advantage that applications created in this format will run even if the phar extension is not enabled.

In other words, even with the phar extension disabled, one can execute or include a phar-based archive. Accessing individual files within a phar archive is only possible with the phar extension unless the phar archive was created by PHP_Archive.

The phar extension is also capable of converting a phar archive from tar to zip or to phar file format in a single command:

Example #3 Converting a phar archive from phar to tar file format

<?php
 $phar = new Phar('myphar.phar');
 $pgz = $phar->convertToExecutable(Phar::TAR, Phar::GZ); // makes myphar.phar.tar.gz
 ?>

Phar can compress individual files or an entire archive using gzip compression or bzip2 compression, and can verify archive integrity automatically through the use of md5(), sha1(), sha256(), or sha512() signatures.

Lastly, the Phar extension is security-conscious, and disables write access to executable phar archives by default, and requires system-level disabling of the phar.readonly php.ini setting in order to create or modify phar archives. Normal tar and zip archives without an executable stub can always be created or modified using the PharData class.

If you are creating applications for distribution, you will want to read How to create Phar Archives. If you want more information on the differences between the three file formats that phar supports, you should read Phar, Tar and Zip.

If you are using phar applications, there are helpful tips in How to use Phar Archives

The word phar is a contraction of PHP and Archive and is based loosely on the jar (Java Archive) familiar to Java developers.

The implementation for Phar archives is based on the PEAR package » PHP_Archive, and the implementation details are similar, although the Phar extension is much more powerful. In addition, the Phar extension allows most PHP applications to be run unmodified while PHP_Archive-based phar archives often require extensive modification in order to work.

Phar
Installing/Configuring
Phar


Introduction

This module contains an interface to those functions defined in the IEEE 1003.1 (POSIX.1) standards document which are not accessible through other means.

Warning

Sensitive data can be retrieved with the POSIX functions, e.g. posix_getpwnam() and friends. None of the POSIX function perform any kind of access checking when safe mode is enabled. It's therefore strongly advised to disable the POSIX extension at all (use --disable-posix in your configure line) if you're operating in such an environment.

Note: This extension is not available on Windows platforms.

POSIX
Installing/Configuring
POSIX


Introduction

This module allows to create PostScript documents. It has many similarities with the pdf extension. Actually the API is almost identical and one can in many cases just replace the prefix of each function from pdf_ to ps_. This also works for functions which has no meaning in the PostScript document (like adding hyperlinks) but will have an effect if the document is converted to PDF.

Documents created by this extension are sometimes even superior to documents created with the pdf extension, because pslib's text rendering functions can handle kerning, hyphenation and ligatures which results in much better output of boxed text.

PS
Installing/Configuring
PS


Introduction

These functions allow you to check the spelling of a word and offer suggestions.

Pspell
Installing/Configuring
Pspell


Introduction

This package is based on the libradius (Remote Authentication Dial In User Service) of FreeBSD. It allows clients to perform authentication and accounting by means of network requests to remote servers.

This PECL extension adds full support for Radius Authentication (» RFC 2865) and Radius Accounting (» RFC 2866). This package is available for Unix (tested on FreeBSD and Linux) and for Windows.

Note: An exact description for libradius can be found » here. A detailed description of the configuration file can be found » here.

Radius
Installing/Configuring
Radius


Introduction

Rar is a powerful and effective archiver created by Eugene Roshal. This extension gives you possibility to read Rar archives but doesn't support writing Rar archives, because this is not supported by the UnRar library and is directly prohibited by its license.

More information about Rar and UnRar can be found at » http://www.rarlabs.com/.

Rar
Installing/Configuring
Rar


Introduction

The readline functions implement an interface to the GNU Readline library. These are functions that provide editable command lines. An example being the way Bash allows you to use the arrow keys to insert characters or scroll through command history. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts used from a command line.

Note: This extension is not available on Windows platforms.

Readline
Installing/Configuring
Readline


Introduction

This module contains an interface to the GNU Recode library. The GNU Recode library converts files between various coded character sets and surface encodings. When this cannot be achieved exactly, it may get rid of the offending characters or fall back on approximations. The library recognises or produces nearly 150 different character sets and is able to convert files between almost any pair. Most » RFC 1345 character sets are supported.

Note: This extension is not available on Windows platforms.

Recode
Installing/Configuring
Recode


Introduction

This module allows you to read the meta information stored in the headers of a » RedHat Package Manager (» RPM) file.

RPM Reader
Installing/Configuring
RPM Reader


Introduction

The runkit extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables and embeddable sub-interpreters via sandboxing.

This package is meant as a feature added replacement for the » classkit package. When compiled with the --enable-runkit=classkit option to ./configure, it will export classkit compatible function definitions and constants.

runkit
Predefined Constants
runkit


Introduction

The scream extension gives the possibility to disable the silencing error control operator so all errors are being reported. This feature is controlled by an ini setting.

scream
Installing/Configuring
scream


Introduction

This module provides wrappers for the System V IPC family of functions. It includes semaphores, shared memory and inter-process messaging (IPC).

Semaphores may be used to provide exclusive access to resources on the current machine, or to limit the number of processes that may simultaneously use a resource.

This module provides also shared memory functions using System V shared memory. Shared memory may be used to provide access to global variables. Different httpd-daemons and even other programs (such as Perl, C, ...) are able to access this data to provide a global data-exchange. Remember, that shared memory is NOT safe against simultaneous access. Use semaphores for synchronization.

Limits of Shared Memory by the Unix OS
SHMMAX | max size of shared memory, normally 131072 bytes
SHMMIN | minimum size of shared memory, normally 1 byte
SHMMNI | max amount of shared memory segments on a system, normally 100
SHMSEG | max amount of shared memory segments per process, normally 6

The messaging functions may be used to send and receive messages to/from other processes. They provide a simple and effective means of exchanging data between processes, without the need for setting up an alternative using Unix domain sockets.

Note: This extension is not available on Windows platforms.

Semaphore
Installing/Configuring
Semaphore


Introduction

Shmop is an easy to use set of functions that allows PHP to read, write, create and delete Unix shared memory segments.

Note: Versions of Windows previous to Windows 2000 do not support shared memory.

Note: In PHP 4.0.3, these functions were prefixed by shm rather than shmop.

Shared Memory
Installing/Configuring
Shared Memory


Introduction

SPL is a collection of interfaces and classes that are meant to solve standard problems.

Note: Legacy "doxygen" documentation can be found » here.

SPL
Installing/Configuring
SPL


Introduction

This extension gives you the possibility to use the » SPPLUS Payment System of the Caisse d'Epargne (a French Bank).

Note: This extension is not available on Windows platforms.

Refer to the README files in kit_php's source distribution for configuration details.

SPPLUS
Installing/Configuring
SPPLUS


Introduction

This is an extension for the SQLite Embeddable SQL Database Engine. SQLite is a C library that implements an embeddable SQL database engine. Programs that link with the SQLite library can have SQL database access without running a separate RDBMS process.

SQLite is not a client library used to connect to a big database server. SQLite is the server. The SQLite library reads and writes directly to and from the database files on disk.

Note: For further information see the SQLite Website (» http://sqlite.org/).

SQLite
Installing/Configuring
SQLite


Introduction

Support for SQLite version 3 databases.

SQLite3
Installing/Configuring
SQLite3


Introduction

This is the statistics extension. It contains few dozens of functions useful for statistical computations. It is a wrapper around 2 scientific libraries, namely DCDFLIB (Library of C routines for Cumulative Distributions Functions, Inverses, and Other parameters) by B. Brown & J. Lavato and RANDLIB by Barry Brown, James Lavato & Kathy Russell. Includes CD and PD functions.

Statistics
Installing/Configuring
Statistics


Introduction

PHP offers the ability to create Shockwave Flash files via Paul Haeberli's libswf module.

Note: SWF support was added in PHP 4 RC2.
The libswf does not have support for Windows. The development of that library has been stopped, and the source is not available to port it to another systems.
For up to date SWF support take a look at the MING functions.

Note: This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.0.0.

SWF
Installing/Configuring
SWF


Introduction

Sybase
Installing/Configuring
Sybase


Introduction

tokyo_tyrant extension provides a wrapper for Tokyo Tyrant client libraries. The extension contains the normal key-value API and the table API.

"Tokyo Tyrant is a package of network interface to the DBM called Tokyo Cabinet. Though the DBM has high performance, you might bother in case that multiple processes share the same database, or remote processes access the database. Thus, Tokyo Tyrant is provided for concurrent and remote connections to Tokyo Cabinet. It is composed of the server process managing a database and its access library for client applications." --Tokyo Tyrant documentation

Tokyo Tyrant is written by Mikio Hirabayashi and is licensed under GNU Lesser General Public License.

tokyo_tyrant
Installing/Configuring
tokyo_tyrant


Introduction

Unicode Support.

Warning

This extension is still in development and it isn't available to public yet.

Unicode
Installing/Configuring
Unicode


Introduction

In addition to normal ODBC support, the Unified ODBC functions in PHP allow you to access several databases that have borrowed the semantics of the ODBC API to implement their own API. Instead of maintaining multiple database drivers that were all nearly identical, these drivers have been unified into a single set of ODBC functions.

The following databases are supported by the Unified ODBC functions: » Adabas D, » IBM DB2, » iODBC, » Solid, and » Sybase SQL Anywhere.

Note: With the exception of iODBC, there is no ODBC involved when connecting to the above databases. The functions that you use to speak natively to them just happen to share the same names and syntax as the ODBC functions. However, building PHP with iODBC support enables you to use any ODBC-compliant drivers with your PHP applications. More information on iODBC, is available at » www.iodbc.org with the alternative unixODBC available at » www.unixodbc.org.

ODBC
Installing/Configuring
ODBC


Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

This extension has been moved from PHP as of PHP 4.3.0 and now vpopmail lives in » PECL.

vpopmail
Installing/Configuring
vpopmail


Introduction

Windows Cache Extension for PHP is a PHP accelerator that is used to increase the speed of PHP applications running on Windows and Windows Server. Once the Windows Cache Extension for PHP is enabled and loaded by the PHP engine, PHP applications can take advantage of the functionality without any code modifications.

The Windows Cache Extension includes 3 different types of caches. The following describes the purpose of each cache type and the benefits it provides.

  • PHP Opcode Cache - PHP is a script processing engine, which reads an input stream of data that contains text and/or PHP instructions and produces another stream of data, most commonly in the HTML format. This means that on a web server the PHP engine reads, parses, compiles and executes a PHP script each time that it is requested by a Web client. The reading, parsing and compilation operations put additional load on the web server's CPU and file system and thus affect the overall performance of a PHP web application. The PHP bytecode (opcode) cache is used to store the compiled script bytecode in shared memory so that it can be re-used by PHP engine for subsequent executions of the same script.

  • File Cache - Even with the PHP bytecode cache enabled, the PHP engine has to accesses the script files on a file system. When PHP scripts are stored on a remote UNC file share, the file operations introduce a significant performance overhead. The Windows Cache Extension for PHP includes a file cache that is used to store the content of the PHP script files in shared memory, which reduces the amount of file system operations performed by PHP engine.

  • Resolve File Path Cache - PHP scripts very often include or operate with files by using relative file paths. Every file path has to be normalized to an absolute file path by the PHP engine. When a PHP application uses many PHP files and accesses them by relative paths, the operation of resolving the paths may negatively impact the application's performance. The Windows Cache Extension for PHP provides a Resolve File Path cache, which is used to store the mappings between relative and absolute file paths, thereby reducing the number of path resolutions that the PHP engine has to perform.

WinCache
Installing/Configuring
WinCache


Introduction

The xattr extension allows for the manipulation of extended attributes on a filesystem.

xattr
Installing/Configuring
xattr


Introduction

xdiff extension enables you to create and apply patch files containing differences between different revisions of files.

This extension supports two modes of operation - on strings and on files, as well as two different patch formats - unified and binary. Unified patches are excellent for text files as they are human-readable and easy to review. For binary files like archives or images, binary patches will be adequate choice as they are binary safe and handle non-printable characters well.

Starting from version 1.5.0 there are two different sets of functions for generating binary patches. New functions - xdiff_string_rabdiff() and xdiff_file_rabdiff() generate output compatible with older functions but are typically faster and generate smaller results. For more details about methods of generating binary patches and differences between them, please check » libxdiff website.

This extension uses libxdiff to implement these functions. Please see » http://www.xmailserver.org/xdiff-lib.html for more information.

xdiff
Installing/Configuring
xdiff


Introduction

This extension enables you to transparently read or write ZIP compressed archives and the files inside them.

Zip
Installing/Configuring
Zip


Introduction

This module enables you to transparently read and write gzip (.gz) compressed files, through versions of most of the filesystem functions which work with gzip-compressed files (and uncompressed files, too, but not with sockets).

Note: Version 4.0.4 introduced a fopen-wrapper for .gz-files, so that you can use a special zlib: URL to access compressed files transparently using the normal f*() file access functions if you prefix the filename or path with zlib: when calling fopen(). This feature requires a C runtime library that provides the fopencookie() function. Up to now the GNU libc seems to be the only library that provides this feature.
In PHP 4.3.0, zlib: has been changed to compress.zlib:// to prevent ambiguities with filenames containing ':' characters. The fopencookie() function is no longer required. More information is available in the section about Compression Streams.

Zlib
Installing/Configuring
Zlib


Introduction

Table of Contents

  • What is PHP?
  • What can PHP do?
Getting Started
What is PHP?
Getting Started


Return the current element

Iterator
Iterator::key
Iterator
PHP Manual

Iterator::current

(PHP 5 >= 5.1.0)

Iterator::current — Return the current element

Description

abstract public mixed Iterator::current ( void )

Returns the current element.

Parameters

This function has no parameters.

Return Values

Can return any type.

Iterator
Iterator::key
Iterator


Return the key of the current element

Iterator::current
Iterator::next
Iterator
PHP Manual

Iterator::key

(PHP 5 >= 5.1.0)

Iterator::key — Return the key of the current element

Description

abstract public scalar Iterator::key ( void )

Returns the key of the current element.

Parameters

This function has no parameters.

Return Values

Returns scalar on success, integer 0 on failure.

Errors/Exceptions

Issues E_WARNING on failure.

Iterator::current
Iterator::next
Iterator


Move forward to next element

Iterator::key
Iterator::rewind
Iterator
PHP Manual

Iterator::next

(PHP 5 >= 5.1.0)

Iterator::next — Move forward to next element

Description

abstract public void Iterator::next ( void )

Moves the current position to the next element.

Note: This method is called after each foreach loop.

Parameters

This function has no parameters.

Return Values

Any returned value is ignored.

Iterator::key
Iterator::rewind
Iterator


Rewind the Iterator to the first element

Iterator::next
Iterator::valid
Iterator
PHP Manual

Iterator::rewind

(PHP 5 >= 5.1.0)

Iterator::rewind — Rewind the Iterator to the first element

Description

abstract public void Iterator::rewind ( void )

Rewinds back to the first element of the Iterator.

Note: This is the first method called when starting a foreach loop. It will not be executed after foreach loops.

Parameters

This function has no parameters.

Return Values

Any returned value is ignored.

Iterator::next
Iterator::valid
Iterator


Checks if current position is valid

Iterator::rewind
IteratorAggregate
Iterator
PHP Manual

Iterator::valid

(PHP 5 >= 5.1.0)

Iterator::valid — Checks if current position is valid

Description

abstract public boolean Iterator::valid ( void )

This method is called after Iterator::rewind and Iterator::next to check if the current position is valid.

Parameters

This function has no parameters.

Return Values

The return value will be casted to boolean and then evaluated. Returns TRUE on success or FALSE on failure.

Iterator::rewind
IteratorAggregate
Iterator


Retrieve an external iterator

IteratorAggregate
ArrayAccess
IteratorAggregate
PHP Manual

IteratorAggregate::getIterator

(PHP 5 >= 5.1.0)

IteratorAggregate::getIterator — Retrieve an external iterator

Description

abstract public Traversable IteratorAggregate::getIterator ( void )

Returns an external iterator.

Parameters

This function has no parameters.

Return Values

An instance of an object implementing Iterator or Traversable

Errors/Exceptions

Throws an Exception on failure.

IteratorAggregate
ArrayAccess
IteratorAggregate


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The following constants indicate the type of error returned by json_last_error(). They are all available as of PHP 5.3.0.

JSON_ERROR_NONE (integer)
No error has occurred.
JSON_ERROR_DEPTH (integer)
The maximum stack depth has been exceeded.
JSON_ERROR_CTRL_CHAR (integer)
Control character error, possibly incorrectly encoded.
JSON_ERROR_SYNTAX (integer)
Syntax error.

The following constants can be combined to form options for json_encode(). They are all available as of PHP 5.3.0.

JSON_HEX_TAG (integer)
All < and > are converted to \u003C and \u003E.
JSON_HEX_AMP (integer)
All &s are converted to \u0026.
JSON_HEX_APOS (integer)
All ' are converted to \u0027.
JSON_HEX_QUOT (integer)
All " are converted to \u0022.
JSON_FORCE_OBJECT (integer)
Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty.
Resource Types
JSON Functions
JSON


Requirements

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/json

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
JSON


Predefined Constants

Table of Contents

  • Constants for Attribute Flags
  • Constants for Options

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Resource Types
Constants for Attribute Flags
KADM5


Constants for Attribute Flags

The functions kadm5_create_principal(),
kadm5_modify_principal(), and
kadm5_modify_principal() allow to specify
special attributes using a bitfield. The symbols are defined below:

Attributes for use by the KDC
constant
KRB5_KDB_DISALLOW_POSTDATED
KRB5_KDB_DISALLOW_FORWARDABLE
KRB5_KDB_DISALLOW_TGT_BASED
KRB5_KDB_DISALLOW_RENEWABLE
KRB5_KDB_DISALLOW_PROXIABLE
KRB5_KDB_DISALLOW_DUP_SKEY
KRB5_KDB_DISALLOW_ALL_TIX
KRB5_KDB_REQUIRES_PRE_AUTH
KRB5_KDB_REQUIRES_HW_AUTH
KRB5_KDB_REQUIRES_PWCHANGE
KRB5_KDB_DISALLOW_SVR
KRB5_KDB_PWCHANGE_SERVER
KRB5_KDB_SUPPORT_DESMD5
KRB5_KDB_NEW_PRINC

Predefined Constants
Constants for Options
Predefined Constants


Examples

Table of Contents

  • KADM5 extension overview example
Constants for Options
KADM5 extension overview example
KADM5


KADM5 extension overview example

Examples
KADM5 Functions
Examples
PHP Manual

This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.

Example #1 KADM5 extension overview example

<?php

  $handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

  print "<h1>get_principals</h1>\n";
  $principals = kadm5_get_principals($handle);
  for( $i=0; $i<count($principals); $i++)
      print "$principals[$i]<br>\n";

  print "<h1>get_policies</h1>\n";
  $policies = kadm5_get_policies($handle);
  for( $i=0; $i<count($policies); $i++)
      print "$policies[$i]<br>\n";

  print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

  $options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
  $keys = array_keys($options);
  for( $i=0; $i<count($keys); $i++) {
    $value = $options[$keys[$i]];
    print "$keys[$i]: $value<br>\n";
  }

  $options = array(KADM5_PRINC_EXPIRE_TIME => 0);
  kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

  kadm5_destroy($handle);
?>

Examples
KADM5 Functions
Examples


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/kadm5.

Note: If this option is used without specifying the path to KADM5, PHP will use the built-in KADM5 client libraries. Users who run other applications that use KADM5 (for example, running PHP 4 and PHP 5 as concurrent apache modules, or auth-kadm5) should always specify the path to KADM5: --with-kadm5=/path/to/kadm5. This will force PHP to use the client libraries installed by KADM5, avoiding any conflicts.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Resource Types

This extension defines a KADM5 handle returned by kadm5_init_with_password().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
KADM5


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

KTaglib uses class constants. Most of the constants are mappings to the according Taglib enums and constants.

KTaglib_MPEG_Header::Version1 (integer)
ID3 version is 1.0
KTaglib_MPEG_Header::Version2 (integer)
ID3 version is 2.0
KTaglib_MPEG_Header::Version2_5 (integer)
ID3 version is 2.5
KTaglib_ID3v2_AttachedPictureFrame::Other (integer)
Picture type Other
KTaglib_ID3v2_AttachedPictureFrame::FileIcon (integer)
Picture type FileIcon
KTaglib_ID3v2_AttachedPictureFrame::OtherFileIcon (integer)
Picture type OtherFileIcon
KTaglib_ID3v2_AttachedPictureFrame::FrontCover (integer)
Picture type FrontCover
KTaglib_ID3v2_AttachedPictureFrame::BackCover (integer)
Picture type BackCover
KTaglib_ID3v2_AttachedPictureFrame::LeafletPage (integer)
Picture type LeafletPage
KTaglib_ID3v2_AttachedPictureFrame::Media (integer)
Picture type Media
KTaglib_ID3v2_AttachedPictureFrame::LeadArtist (integer)
Picture type LeadArtist
KTaglib_ID3v2_AttachedPictureFrame::Artist (integer)
Picture type Artist
KTaglib_ID3v2_AttachedPictureFrame::Conductor (integer)
Picture type Condutor
KTaglib_ID3v2_AttachedPictureFrame::Band (integer)
Picture type Band
KTaglib_ID3v2_AttachedPictureFrame::Composer (integer)
Picture type Composer
KTaglib_ID3v2_AttachedPictureFrame::Lyricist (integer)
Picture type Lyricist
KTaglib_ID3v2_AttachedPictureFrame::RecordingLocation (integer)
Picture type RecordingLocation
KTaglib_ID3v2_AttachedPictureFrame::DuringRecording (integer)
Picture type DuringRecording
KTaglib_ID3v2_AttachedPictureFrame::DuringPerformance (integer)
Picture type DuringPerformance
KTaglib_ID3v2_AttachedPictureFrame::MovieScreenCapture (integer)
Picture type MovieScreenCapture
KTaglib_ID3v2_AttachedPictureFrame::ColouredFish (integer)
Picture type ColouredFish
KTaglib_ID3v2_AttachedPictureFrame::Illustration (integer)
Picture type Illustration
KTaglib_ID3v2_AttachedPictureFrame::BandLogo (integer)
Picture type BandLogo
Installation
KTaglib_MPEG_File
KTaglib


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/ktaglib.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Predefined Constants
Installing/Configuring


Requirements

If you want to build ktaglib you need at least taglib 1.5 installed. To obtain the taglib see the » taglib project page. Windows DLL's are build static against taglib, therefore there is no need to have taglib installed.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
Introduction
Requirements
KTaglib


Language Reference

  • Basic syntax
    • Escaping from HTML
    • Instruction separation
    • Comments
  • Types
    • Introduction
    • Booleans
    • Integers
    • Floating point numbers
    • Strings
    • Arrays
    • Objects
    • Resources
    • NULL
    • Pseudo-types and variables used in this documentation
    • Type Juggling
  • Variables
    • Basics
    • Predefined Variables
    • Variable scope
    • Variable variables
    • Variables From External Sources
  • Constants
    • Syntax
    • Magic constants
  • Expressions
  • Operators
    • Operator Precedence
    • Arithmetic Operators
    • Assignment Operators
    • Bitwise Operators
    • Comparison Operators
    • Error Control Operators
    • Execution Operators
    • Incrementing/Decrementing Operators
    • Logical Operators
    • String Operators
    • Array Operators
    • Type Operators
  • Control Structures
    • Introduction
    • if
    • else
    • elseif/else if
    • Alternative syntax for control structures
    • while
    • do-while
    • for
    • foreach
    • break
    • continue
    • switch
    • declare
    • return
    • require
    • include
    • require_once
    • include_once
    • goto
  • Functions
    • User-defined functions
    • Function arguments
    • Returning values
    • Variable functions
    • Internal (built-in) functions
    • Anonymous functions
  • Classes and Objects
    • Introduction
    • The Basics
    • Properties
    • Class Constants
    • Autoloading Classes
    • Constructors and Destructors
    • Visibility
    • Object Inheritance
    • Scope Resolution Operator (::)
    • Static Keyword
    • Class Abstraction
    • Object Interfaces
    • Overloading
    • Object Iteration
    • Patterns
    • Magic Methods
    • Final Keyword
    • Object Cloning
    • Comparing Objects
    • Type Hinting
    • Late Static Bindings
    • Objects and references
    • Object Serialization
  • Namespaces
    • Namespaces overview
    • Defining namespaces
    • Declaring sub-namespaces
    • Defining multiple namespaces in the same file
    • Using namespaces: Basics
    • Namespaces and dynamic language features
    • namespace keyword and __NAMESPACE__ constant
    • Using namespaces: Aliasing/Importing
    • Global space
    • Using namespaces: fallback to global function/constant
    • Name resolution rules
    • FAQ: things you need to know about namespaces
  • Exceptions
    • Extending Exceptions
  • References Explained
    • What References Are
    • What References Do
    • What References Are Not
    • Passing by Reference
    • Returning References
    • Unsetting References
    • Spotting References
  • Predefined Variables
    • Superglobals — Superglobals are built-in variables that are always available in all scopes
    • $GLOBALS — References all variables available in global scope
    • $_SERVER — Server and execution environment information
    • $_GET — HTTP GET variables
    • $_POST — HTTP POST variables
    • $_FILES — HTTP File Upload variables
    • $_REQUEST — HTTP Request variables
    • $_SESSION — Session variables
    • $_ENV — Environment variables
    • $_COOKIE — HTTP Cookies
    • $php_errormsg — The previous error message
    • $HTTP_RAW_POST_DATA — Raw POST data
    • $http_response_header — HTTP response headers
    • $argc — The number of arguments passed to script
    • $argv — Array of arguments passed to script
  • Predefined Exceptions
    • Exception
    • ErrorException
  • Predefined Interfaces
    • Traversable — The Traversable interface
    • Iterator — The Iterator interface
    • IteratorAggregate — The IteratorAggregate interface
    • ArrayAccess — The ArrayAccess interface
    • Serializable — The Serializable interface
  • Context options and parameters
    • Socket context options — Socket context option listing
    • HTTP context options — HTTP context option listing
    • FTP context options — FTP context option listing
    • SSL context options — SSL context option listing
    • CURL context options — CURL context option listing
    • Phar context options — Phar context option listing
    • Context parameters — Context parameter listing
How to change configuration settings
Basic syntax


Basic syntax

Table of Contents

  • Escaping from HTML
  • Instruction separation
  • Comments
Language Reference
Escaping from HTML
Language Reference


Comments

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

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

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

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

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

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

Instruction separation
Types
Basic syntax


Instruction separation

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

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

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

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

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

Escaping from HTML
Comments
Basic syntax


Escaping from HTML

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

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

You can also use more advanced structures:

Example #1 Advanced escaping

<?php
if ($expression) {
    ?>
    <strong>This is true.</strong>
    <?php
} else {
    ?>
    <strong>This is false.</strong>
    <?php
}
?>

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

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

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

Example #2 PHP Opening and Closing Tags

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

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

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

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

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

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

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

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

Basic syntax
Instruction separation
Basic syntax


Constants

Table of Contents

  • Syntax
  • Magic constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Tip

See also the Userland Naming Guide.

Example #1 Valid and invalid constant names

<?php

// Valid constant names
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more");

// Invalid constant names
define("2FOO",    "something");

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");

?>

Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope.

Variables From External Sources
Syntax
Language Reference


Magic constants

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are seven magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows:

A few "magical" PHP constants
Name | Description
__LINE__ | The current line number of the file.
__FILE__ | The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
__DIR__ | The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)
__FUNCTION__ | The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__ | The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__METHOD__ | The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
__NAMESPACE__ | The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).

See also
get_class(),
get_object_vars(),
file_exists() and
function_exists().

Syntax
Expressions
Constants


Syntax

You can define a constant by using the define()-function or by using the const keyword outside a class definition as of PHP 5.3.0. Once a constant is defined, it can never be changed or undefined.

Only scalar data (boolean, integer, float and string) can be contained in constants. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

You can get the value of a constant by simply specifying its name. Unlike with variables, you should not prepend a constant with a $. You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically. Use get_defined_constants() to get a list of all defined constants.

Note: Constants and (global) variables are in a different namespace. This implies that for example TRUE and $TRUE are generally different.

If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs "CONSTANT"). An error of level E_NOTICE will be issued when this happens. See also the manual entry on why $foo[bar] is wrong (unless you first define() bar as a constant). If you simply want to check if a constant is set, use the defined() function.

These are the differences between constants and variables:

  • Constants do not have a dollar sign ($) before them;
  • Constants may only be defined using the define() function, not by simple assignment;
  • Constants may be defined and accessed anywhere without regard to variable scoping rules;
  • Constants may not be redefined or undefined once they have been set; and
  • Constants may only evaluate to scalar values.

Example #1 Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>

Example #2 Defining Constants using the const keyword

<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';

echo CONSTANT;
?>

See also Class Constants.

Constants
Magic constants
Constants


Control Structures

Table of Contents

  • Introduction
  • if
  • else
  • elseif/else if
  • Alternative syntax for control structures
  • while
  • do-while
  • for
  • foreach
  • break
  • continue
  • switch
  • declare
  • return
  • require
  • include
  • require_once
  • include_once
  • goto
Type Operators
Introduction
Language Reference


Exceptions

Table of Contents

  • Extending Exceptions

PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exeptions. Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.

Note: Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.

Tip

The Standard PHP Library (SPL) provides a good number of built-in exceptions.

Example #1 Throwing an Exception

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    else return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

The above example will output:

0.2
Caught exception: Division by zero.
Hello World

Example #2 Nested Exception

<?php

class MyException extends Exception { }

class Test {
    public function testing() {
        try {
            try {
                throw new MyException('foo!');
            } catch (MyException $e) {
                /* rethrow it */
                throw $e;
            }
        } catch (Exception $e) {
            var_dump($e->getMessage());
        }
    }
}

$foo = new Test;
$foo->testing();

?>

The above example will output:

string(4) "foo!"
FAQ: things you need to know about namespaces
Extending Exceptions
Language Reference


Extending Exceptions

A User defined Exception class can be defined by extending the built-in Exception class. The members and properties below, show what is accessible within the child class that derives from the built-in Exception class.

Example #1 The Built in Exception class

<?php
class Exception
{
    protected $message = 'Unknown exception';   // exception message
    private   $string;                          // __toString cache
    protected $code = 0;                        // user defined exception code
    protected $file;                            // source filename of exception
    protected $line;                            // source line of exception
    private   $trace;                           // backtrace
    private   $previous;                        // previous exception if nested exception

    public function __construct($message = null, $code = 0, Exception $previous = null);

    final private function __clone();           // Inhibits cloning of exceptions.

    final public  function getMessage();        // message of exception
    final public  function getCode();           // code of exception
    final public  function getFile();           // source filename
    final public  function getLine();           // source line
    final public  function getTrace();          // an array of the backtrace()
    final public  function getPrevious();       // previous exception
    final public  function getTraceAsString();  // formatted string of trace

    /* Overrideable */
    public function __toString();               // formatted string for display
}
?>

If a class extends the built-in Exception class and re-defines the constructor, it is highly recommended that it also call parent::__construct() to ensure all available data has been properly assigned. The __toString() method can be overridden to provide a custom output when the object is presented as a string.

Note: Exceptions cannot be cloned. Attempting to clone an Exception will result in a E_FATAL error.

Example #2 Extending the Exception class

<?php
/**
 * Define a custom exception class
 */
class MyException extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0, Exception $previous = null) {
        // some code

        // make sure everything is assigned properly
        parent::__construct($message, $code, $previous);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A custom function for this type of exception\n";
    }
}

/**
 * Create a class to test the exception
 */
class TestException
{
    public $var;

    const THROW_NONE    = 0;
    const THROW_CUSTOM  = 1;
    const THROW_DEFAULT = 2;

    function __construct($avalue = self::THROW_NONE) {

        switch ($avalue) {
            case self::THROW_CUSTOM:
                // throw custom exception
                throw new MyException('1 is an invalid parameter', 5);
                break;

            case self::THROW_DEFAULT:
                // throw default one.
                throw new Exception('2 is not allowed as a parameter', 6);
                break;

            default:
                // No exception, object will be created.
                $this->var = $avalue;
                break;
        }
    }
}

// Example 1
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) {      // Will be caught
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Skipped
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";

// Example 2
try {
    $o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) {      // Doesn't match this type
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Will be caught
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";

// Example 3
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) {        // Will be caught
    echo "Default Exception caught\n", $e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";

// Example 4
try {
    $o = new TestException();
} catch (Exception $e) {        // Skipped, no exception
    echo "Default Exception caught\n", $e;
}

// Continue execution
var_dump($o); // TestException
echo "\n\n";
?>
Exceptions
References Explained
Exceptions


Expressions

Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".

The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).

After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions. For instance, consider the following function:

<?php
function foo ()
{
    return 5;
}
?>

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.

Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: integer values, floating point values (float), string values and boolean values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.

PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.

Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP/FI 2, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').

A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.

The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

<?php
$first ? $second : $third
?>

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

The following example should help you understand pre- and post-increment and expressions in general a bit better:

<?php
function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* assign the value five into the variable $a and $b */
$c = $a++;          /* post-increment, assign original value of $a
                       (5) to $c */
$e = $d = ++$b;     /* pre-increment, assign the incremented value of
                       $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++);  /* assign twice the value of $d before
                       the increment, 2*6 = 12 to $f */
$g = double(++$e);  /* assign twice the value of $e after
                       the increment, 2*7 = 14 to $g */
$h = $g += 10;      /* first, $g is incremented by 10 and ends with the
                       value of 24. the value of the assignment (24) is
                       then assigned into $h, and $h ends with the value
                       of 24 as well. */
?>

Some expressions can be considered as statements. In this case, a statement has the form of 'expr ;' that is, an expression followed by a semicolon. In '$b = $a = 5;', '$a = 5' is a valid expression, but it's not a statement by itself. '$b = $a = 5;' however is a valid statement.

One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.

PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.

Magic constants
Operators
Language Reference


Functions

Table of Contents

  • User-defined functions
  • Function arguments
  • Returning values
  • Variable functions
  • Internal (built-in) functions
  • Anonymous functions
goto
User-defined functions
Language Reference


Namespaces

Table of Contents

  • Namespaces overview
  • Defining namespaces
  • Declaring sub-namespaces
  • Defining multiple namespaces in the same file
  • Using namespaces: Basics
  • Namespaces and dynamic language features
  • namespace keyword and __NAMESPACE__ constant
  • Using namespaces: Aliasing/Importing
  • Global space
  • Using namespaces: fallback to global function/constant
  • Name resolution rules
  • FAQ: things you need to know about namespaces
Object Serialization
Namespaces overview
Language Reference


Using namespaces: Basics

Before discussing the use of namespaces, it is important to understand how PHP knows which namespaced element your code is requesting. A simple analogy can be made between PHP namespaces and a filesystem. There are three ways to access a file in a file system:

  1. Relative file name like foo.txt. This resolves to currentdirectory/foo.txt where currentdirectory is the directory currently occupied. So if the current directory is /home/foo, the name resolves to /home/foo/foo.txt.
  2. Relative path name like subdirectory/foo.txt. This resolves to currentdirectory/subdirectory/foo.txt.
  3. Absolute path name like /main/foo.txt. This resolves to /main/foo.txt.

The same principle can be applied to namespaced elements in PHP. For example, a class name can be referred to in three ways:

  1. Unqualified name, or an unprefixed class name like $a = new foo(); or foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\foo. If the code is global, non-namespaced code, this resolves to foo. One caveat: unqualified names for functions and constants will resolve to global functions and constants if the namespaced function or constant is not defined. See Using namespaces: fallback to global function/constant for details.
  2. Qualified name, or a prefixed class name like $a = new subnamespace\foo(); or subnamespace\foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\subnamespace\foo. If the code is global, non-namespaced code, this resolves to subnamespace\foo.
  3. Fully qualified name, or a prefixed name with global prefix operator like $a = new \currentnamespace\foo(); or \currentnamespace\foo::staticmethod();. This always resolves to the literal name specified in the code, currentnamespace\foo.

Here is an example of the three kinds of syntax in actual code:

file1.php

<?php
namespace Foo\Bar\subnamespace;

const FOO = 1;
function foo() {}
class foo
{
    static function staticmethod() {}
}
?>

file2.php

<?php
namespace Foo\Bar;
include 'file1.php';

const FOO = 2;
function foo() {}
class foo
{
    static function staticmethod() {}
}

/* Unqualified name */
foo(); // resolves to function Foo\Bar\foo
foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo FOO; // resolves to constant Foo\Bar\FOO

/* Qualified name */
subnamespace\foo(); // resolves to function Foo\Bar\subnamespace\foo
subnamespace\foo::staticmethod(); // resolves to class Foo\Bar\subnamespace\foo,
                                  // method staticmethod
echo subnamespace\FOO; // resolves to constant Foo\Bar\subnamespace\FOO

/* Fully qualified name */
\Foo\Bar\foo(); // resolves to function Foo\Bar\foo
\Foo\Bar\foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo \Foo\Bar\FOO; // resolves to constant Foo\Bar\FOO
?>

Note that to access any global class, function or constant, a fully qualified name can be used, such as \strlen() or \Exception or \INI_ALL.

Example #1 Accessing global classes, functions and constants from within a namespace

<?php
namespace Foo;

function strlen() {}
const INI_ALL = 3;
class Exception {}

$a = \strlen('hi'); // calls global function strlen
$b = \INI_ALL; // accesses global constant INI_ALL
$c = new \Exception('error'); // instantiates global class Exception
?>

Defining multiple namespaces in the same file
Namespaces and dynamic language features
Namespaces


Defining namespaces

Although any valid PHP code can be contained within a namespace, only three type of code are affected by namespaces: classes, functions and constants.

Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

Example #1 Declaring a single namespace

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

?>

The only code construct allowed before a namespace declaration is the declare statement, for defining encoding of a source file. In addition, no non-PHP code may precede a namespace declaration, including extra whitespace:

Example #2 Declaring a single namespace

<html>
<?php
namespace MyProject; // fatal error - namespace must be the first statement in the script
?>

In addition, unlike any other PHP construct, the same namespace may be defined in multiple files, allowing splitting up of a namespace's contents across the filesystem.

Namespaces overview
Declaring sub-namespaces
Namespaces


Defining multiple namespaces in the same file

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes.

Example #1 Declaring multiple namespaces, simple combination syntax

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

namespace AnotherProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
?>

This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.

Example #2 Declaring multiple namespaces, bracketed syntax

<?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace AnotherProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}
?>

It is strongly discouraged as a coding practice to combine multiple namespaces into the same file. The primary use case is to combine multiple PHP scripts into the same file.

To combine global non-namespaced code with namespaced code, only bracketed syntax is supported. Global code should be encased in a namespace statement with no namespace name as in:

Example #3 Declaring multiple namespaces and unnamespaced code

<?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>

No PHP code may exist outside of the namespace brackets except for an opening declare statement.

Example #4 Declaring multiple namespaces and unnamespaced code

<?php
declare(encoding='UTF-8');
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>

Declaring sub-namespaces
Using namespaces: Basics
Namespaces


Namespaces and dynamic language features

PHP's implementation of namespaces is influenced by its dynamic nature as a programming language. Thus, to convert code like the following example into namespaced code:

Example #1 Dynamically accessing elements

example1.php:

<?php
class classname
{
    function __construct()
    {
        echo __METHOD__,"\n";
    }
}
function funcname()
{
    echo __FUNCTION__,"\n";
}
const constname = "global";

$a = 'classname';
$obj = new $a; // prints classname::__construct
$b = 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"; // prints global
?>

One must use the fully qualified name (class name with namespace prefix). Note that because there is no difference between a qualified and a fully qualified Name inside a dynamic class name, function name, or constant name, the leading backslash is not necessary.

Example #2 Dynamically accessing namespaced elements

<?php
namespace namespacename;
class classname
{
    function __construct()
    {
        echo __METHOD__,"\n";
    }
}
function funcname()
{
    echo __FUNCTION__,"\n";
}
const constname = "namespaced";

include 'example1.php';

$a = 'classname';
$obj = new $a; // prints classname::__construct
$b = 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"; // prints global

/* note that if using double quotes, "\\namespacename\\classname" must be used */
$a = '\namespacename\classname';
$obj = new $a; // prints namespacename\classname::__construct
$a = 'namespacename\classname';
$obj = new $a; // also prints namespacename\classname::__construct
$b = 'namespacename\funcname';
$b(); // prints namespacename\funcname
$b = '\namespacename\funcname';
$b(); // also prints namespacename\funcname
echo constant('\namespacename\constname'), "\n"; // prints namespaced
echo constant('namespacename\constname'), "\n"; // also prints namespaced
?>

Be sure to read the note about escaping namespace names in strings.

Using namespaces: Basics
namespace keyword and __NAMESPACE__ constant
Namespaces


Using namespaces: fallback to global function/constant

Inside a namespace, when PHP encounters a unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. Thus to access internal or non-namespaced user classes, One must refer to them with their fully qualified Name as in:

Example #1 Accessing global classes inside a namespace

<?php
namespace A\B\C;
class Exception extends \Exception {}

$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception

$c = new ArrayObject; // fatal error, class A\B\C\ArrayObject not found
?>

For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.

Example #2 global functions/constants fallback inside a namespace

<?php
namespace A\B\C;

const E_ERROR = 45;
function strlen($str)
{
    return \strlen($str) - 1;
}

echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL

echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
    echo "is array\n";
} else {
    echo "is not array\n";
}
?>

Global space
Name resolution rules
Namespaces


FAQ: things you need to know about namespaces

This FAQ is split into two sections: common questions, and some specifics of implementation that are helpful to understand fully.

First, the common questions.

  1. If I don't use namespaces, should I care about any of this?
  2. How do I use internal or global classes in a namespace?
  3. How do I use namespaces classes functions, or constants in their own namespace?
  4. How does a name like \my\name or \name resolve?
  5. How does a name like my\name resolve?
  6. How does an unqualified class name like name resolve?
  7. How does an unqualified function name or unqualified constant name like name resolve?

There are a few implementation details of the namespace implementations that are helpful to understand.

  1. Import names cannot conflict with classes defined in the same file.
  2. Nested namespaces are not allowed.
  3. Neither functions nor constants can be imported via the use statement.
  4. Dynamic namespace names (quoted identifiers) should escape backslash.
  5. Undefined Constants referenced using any backslash die with fatal error
  6. Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

If I don't use namespaces, should I care about any of this?

No. Namespaces do not affect any existing code in any way, or any as-yet-to-be-written code that does not contain namespaces. You can write this code if you wish:

Example #1 Accessing global classes outside a namespace

<?php
$a = new \stdClass;

This is functionally equivalent to:

Example #2 Accessing global classes outside a namespace

<?php
$a = new stdClass;

How do I use internal or global classes in a namespace?

Example #3 Accessing internal classes in namespaces

<?php
namespace foo;
$a = new \stdClass;

function test(\ArrayObject $typehintexample = null) {}

$a = \DirectoryIterator::CURRENT_AS_FILEINFO;

// extending an internal or global class
class MyException extends \Exception {}
?>

How do I use namespaces classes, functions, or constants in their own namespace?

Example #4 Accessing internal classes, functions or constants in namespaces

<?php
namespace foo;

class MyClass {}

// using a class from the current namespace as a type hint
function test(MyClass $typehintexample = null) {}
// another way to use a class from the current namespace as a type hint
function test(\foo\MyClass $typehintexample = null) {}

// extending a class from the current namespace
class Extended extends MyClass {}

// accessing a global function
$a = \globalfunc();

// accessing a global constant
$b = \INI_ALL;
?>

How does a name like \my\name or \name resolve?

Names that begin with a \ always resolve to what they look like, so \my\name is in fact my\name, and \Exception is Exception.

Example #5 Fully Qualified names

<?php
namespace foo;
$a = new \my\name(); // instantiates "my\name" class
echo \strlen('hi'); // calls function "strlen"
$a = \INI_ALL; // $a is set to the value of constant "INI_ALL"
?>

How does a name like my\name resolve?

Names that contain a backslash but do not begin with a backslash like my\name can be resolved in 2 different ways.

If there is an import statement that aliases another name to my, then the import alias is applied to the my in my\name.

Otherwise, the current namespace name is prepended to my\name.

Example #6 Qualified names

<?php
namespace foo;
use blah\blah as foo;

$a = new my\name(); // instantiates "foo\my\name" class
foo\bar::name(); // calls static method "name" in class "blah\blah\bar"
my\bar(); // calls function "foo\my\bar"
$a = my\BAR; // sets $a to the value of constant "foo\my\BAR"
?>

How does an unqualified class name like name resolve?

Class names that do not contain a backslash like name can be resolved in 2 different ways.

If there is an import statement that aliases another name to name, then the import alias is applied.

Otherwise, the current namespace name is prepended to name.

Example #7 Unqualified class names

<?php
namespace foo;
use blah\blah as foo;

$a = new name(); // instantiates "foo\name" class
foo::name(); // calls static method "name" in class "blah\blah"
?>

How does an unqualified function name or unqualified constant name like name resolve?

Function or constant names that do not contain a backslash like name can be resolved in 2 different ways.

First, the current namespace name is prepended to name.

Finally, if the constant or function name does not exist in the current namespace, a global constant or function name is used if it exists.

Example #8 Unqualified function or constant names

<?php
namespace foo;
use blah\blah as foo;

const FOO = 1;

function my() {}
function foo() {}
function sort(&$a)
{
    sort($a);
    $a = array_flip($a);
    return $a;
}

my(); // calls "foo\my"
$a = strlen('hi'); // calls global function "strlen" because "foo\strlen" does not exist
$arr = array(1,3,2);
$b = sort($arr); // calls function "foo\sort"
$c = foo(); // calls function "foo\foo" - import is not applied

$a = FOO; // sets $a to value of constant "foo\FOO" - import is not applied
$b = INI_ALL; // sets $b to value of global constant "INI_ALL"
?>

Import names cannot conflict with classes defined in the same file.

The following script combinations are legal:

file1.php

<?php
namespace my\stuff;
class MyClass {}
?>

another.php

<?php
namespace another;
class thing {}
?>

file2.php

<?php
namespace my\stuff;
include 'file1.php';
include 'another.php';

use another\thing as MyClass;
$a = new MyClass; // instantiates class "thing" from namespace another
?>

There is no name conflict, even though the class MyClass exists within the my\stuff namespace, because the MyClass definition is in a separate file. However, the next example causes a fatal error on name conflict because MyClass is defined in the same file as the use statement.

<?php
namespace my\stuff;
use another\thing as MyClass;
class MyClass {} // fatal error: MyClass conflicts with import statement
$a = new MyClass;
?>

Nested namespaces are not allowed.

PHP does not allow nesting namespaces

<?php
namespace my\stuff {
    namespace nested {
        class foo {}
    }
}
?>

However, it is easy to simulate nested namespaces like so:

<?php
namespace my\stuff\nested {
    class foo {}
}
?>

Neither functions nor constants can be imported via the use statement.

The only elements that are affected by use statements are namespaces and class names. In order to shorten a long constant or function, import its containing namespace

<?php
namespace mine;
use ultra\long\ns\name;

$a = name\CONSTANT;
name\func();
?>

Dynamic namespace names (quoted identifiers) should escape backslash

It is very important to realize that because the backslash is used as an escape character within strings, it should always be doubled when used inside a string. Otherwise there is a risk of unintended consequences:

Example #9 Dangers of using namespaced names inside a double-quoted string

<?php
$a = new "dangerous\name"; // \n is a newline inside double quoted strings!
$obj = new $a;

$a = new 'not\at\all\dangerous'; // no problems here.
$obj = new $a;
?>

Inside a single-quoted string, the backslash escape sequence is much safer to use, but it is still recommended practice to escape backslashes in all strings as a best practice.

Undefined Constants referenced using any backslash die with fatal error

Any undefined constant that is unqualified like FOO will produce a notice explaining that PHP assumed FOO was the value of the constant. Any constant, qualified or fully qualified, that contains a backslash will produce a fatal error if not found.

Example #10 Undefined constants

<?php
namespace bar;
$a = FOO; // produces notice - undefined constants "FOO" assumed "FOO";
$a = \FOO; // fatal error, undefined namespace constant FOO
$a = Bar\FOO; // fatal error, undefined namespace constant bar\Bar\FOO
$a = \Bar\FOO; // fatal error, undefined namespace constant Bar\FOO
?>

Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

Any attempt to define a namespaced constant that is a special, built-in constant results in a fatal error

Example #11 Undefined constants

<?php
namespace bar;
const NULL = 0; // fatal error;
const true = 'stupid'; // also fatal error;
// etc.
?>

Name resolution rules
Exceptions
Namespaces


Global space

Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

Example #1 Using global space specification

<?php
namespace A\B\C;

/* This function is A\B\C\fopen */
function fopen() {
     /* ... */
     $f = \fopen(...); // call global fopen
     return $f;
}
?>

Using namespaces: Aliasing/Importing
Using namespaces: fallback to global function/constant
Namespaces


Using namespaces: Aliasing/Importing

The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.

PHP namespaces support two kinds of aliasing or importing: aliasing a class name, and aliasing a namespace name. Note that importing a function or constant is not supported.

In PHP, aliasing is accomplished with the use operator. Here is an example showing all 3 kinds of importing:

Example #1 importing/aliasing with the use operator

<?php
namespace foo;
use My\Full\Classname as Another;

// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;

// importing a global class
use \ArrayObject;

$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use \ArrayObject" we would instantiate an object of class foo\ArrayObject
?>

Note that for namespaced names (fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar), the leading backslash is unnecessary and not allowed, as import names must be fully qualified, and are not processed relative to the current namespace.

PHP additionally supports a convenience shortcut to place multiple use statements on the same line

Example #2 importing/aliasing with the use operator, multiple use statements combined

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
?>

Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.

Example #3 Importing and dynamic names

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // instantiates object of class My\Full\Classname
$a = 'Another';
$obj = new $a;      // instantiates object of class Another
?>

In addition, importing only affects unqualified and qualified names. Fully qualified names are absolute, and unaffected by imports.

Example #4 Importing and fully qualified names

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // instantiates object of class My\Full\Classname
$obj = new \Another; // instantiates object of class Another
$obj = new Another\thing; // instantiates object of class My\Full\Classname\thing
$obj = new \Another\thing; // instantiates object of class Another\thing
?>

namespace keyword and __NAMESPACE__ constant
Global space
Namespaces


Declaring sub-namespaces

Much like directories and files, PHP namespaces also contain the ability to specify a hierarchy of namespace names. Thus, a namespace name can be defined with sub-levels:

Example #1 Declaring a single namespace with hierarchy

<?php
namespace MyProject\Sub\Level;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

?>

The above example creates constant MyProject\Sub\Level\CONNECT_OK, class MyProject\Sub\Level\Connection and function MyProject\Sub\Level\connect.

Defining namespaces
Defining multiple namespaces in the same file
Namespaces


namespace keyword and __NAMESPACE__ constant

PHP supports two ways of abstractly accessing elements within the current namespace, the __NAMESPACE__ magic constant, and the namespace keyword.

The value of __NAMESPACE__ is a string that contains the current namespace name. In global, un-namespaced code, it contains an empty string.

Example #1 __NAMESPACE__ example, namespaced code

<?php
namespace MyProject;

echo '"', __NAMESPACE__, '"'; // outputs "MyProject"
?>

Example #2 __NAMESPACE__ example, global code

<?php

echo '"', __NAMESPACE__, '"'; // outputs ""
?>

The __NAMESPACE__ constant is useful for dynamically constructing names, for instance:

Example #3 using __NAMESPACE__ for dynamic name construction

<?php
namespace MyProject;

function get($classname)
{
    $a = __NAMESPACE__ . '\\' . $classname;
    return new $a;
}
?>

The namespace keyword can be used to explicitly request an element from the current namespace or a sub-namespace. It is the namespace equivalent of the self operator for classes.

Example #4 the namespace operator, inside a namespace

<?php
namespace MyProject;

use blah\blah as mine; // see "Using namespaces: importing/aliasing"

blah\mine(); // calls function MyProject\blah\mine()
namespace\blah\mine(); // calls function MyProject\blah\mine()

namespace\func(); // calls function MyProject\func()
namespace\sub\func(); // calls function MyProject\sub\func()
namespace\cname::method(); // calls static method "method" of class MyProject\cname
$a = new namespace\sub\cname(); // instantiates object of class MyProject\sub\cname
$b = namespace\CONSTANT; // assigns value of constant MyProject\CONSTANT to $b
?>

Example #5 the namespace operator, in global code

<?php

namespace\func(); // calls function func()
namespace\sub\func(); // calls function sub\func()
namespace\cname::method(); // calls static method "method" of class cname
$a = new namespace\sub\cname(); // instantiates object of class sub\cname
$b = namespace\CONSTANT; // assigns value of constant CONSTANT to $b
?>

Namespaces and dynamic language features
Using namespaces: Aliasing/Importing
Namespaces


Namespaces overview

What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:

  1. Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

PHP Namespaces provide a way in which to group related classes, functions and constants. Here is an example of namespace syntax in PHP:

Example #1 Namespace syntax example

<?php
namespace my\name; // see "Defining Namespaces" section

class MyClass {}
function myfunction() {}
const MYCONST = 1;

$a = new MyClass;
$c = new \my\name\MyClass; // see "Global Space" section

$a = strlen('hi'); // see "Using namespaces: fallback to global
                   // function/constant" section

$d = namespace\MYCONST; // see "namespace operator and __NAMESPACE__
                        // constant" section
$d = __NAMESPACE__ . '\MYCONST';
echo constant($d); // see "Namespaces and dynamic language features" section
?>

Namespaces are available in PHP as of PHP 5.3.0.

Namespaces
Defining namespaces
Namespaces


Name resolution rules

For the purposes of these resolution rules, here are some important definitions:

Namespace name definitions
Unqualified name

This is an identifier without a namespace separator, such as Foo

Qualified name

This is an identifier with a namespace separator, such as Foo\Bar

Fully qualified name

This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar. namespace\Foo is also a fully qualified name.

Names are resolved following these resolution rules:

  1. Calls to fully qualified functions, classes or constants are resolved at compile-time. For instance new \A\B resolves to class A\B.
  2. All unqualified and qualified names (not fully qualified names) are translated during compilation according to current import rules. For example, if the namespace A\B\C is imported as C, a call to C\D\e() is translated to A\B\C\D\e().
  3. Inside a namespace, all qualified names not translated according to import rules have the current namespace prepended. For example, if a call to C\D\e() is performed within namespace A\B, it is translated to A\B\C\D\e().
  4. Unqualified class names are translated during compilation according to current import rules (full name substituted for short imported name). In example, if the namespace A\B\C is imported as C, new C() is translated to new A\B\C().
  5. Inside namespace (say A\B), calls to unqualified functions are resolved at run-time. Here is how a call to function foo() is resolved:
    1. It looks for a function from the current namespace: A\B\foo().
    2. It tries to find and call the global function foo().
  6. Inside namespace (say A\B), calls to unqualified or qualified class names (not fully qualified class names) are resolved at run-time. Here is how a call to new C() or new D\E() is resolved. For new C():
    1. It looks for a class from the current namespace: A\B\C.
    2. It attempts to autoload A\B\C.
    For new D\E():
    1. It looks for a class by prepending the current namespace: A\B\D\E.
    2. It attempts to autoload A\B\D\E.
    To reference any global class in the global namespace, its fully qualified name new \C() must be used.

Example #1 Name resolutions illustrated

<?php
namespace A;
use B\D, C\E as F;

// function calls

foo();      // first tries to call "foo" defined in namespace "A"
            // then calls global function "foo"

\foo();     // calls function "foo" defined in global scope

my\foo();   // calls function "foo" defined in namespace "A\my"

F();        // first tries to call "F" defined in namespace "A"
            // then calls global function "F"

// class references

new B();    // creates object of class "B" defined in namespace "A"
            // if not found, it tries to autoload class "A\B"

new D();    // using import rules, creates object of class "D" defined in namespace "B"
            // if not found, it tries to autoload class "B\D"

new F();    // using import rules, creates object of class "E" defined in namespace "C"
            // if not found, it tries to autoload class "C\E"

new \B();   // creates object of class "B" defined in global scope
            // if not found, it tries to autoload class "B"

new \D();   // creates object of class "D" defined in global scope
            // if not found, it tries to autoload class "D"

new \F();   // creates object of class "F" defined in global scope
            // if not found, it tries to autoload class "F"

// static methods/namespace functions from another namespace

B\foo();    // calls function "foo" from namespace "A\B"

B::foo();   // calls method "foo" of class "B" defined in namespace "A"
            // if class "A\B" not found, it tries to autoload class "A\B"

D::foo();   // using import rules, calls method "foo" of class "D" defined in namespace "B"
            // if class "B\D" not found, it tries to autoload class "B\D"

\B\foo();   // calls function "foo" from namespace "B"

\B::foo();  // calls method "foo" of class "B" from global scope
            // if class "B" not found, it tries to autoload class "B"

// static methods/namespace functions of current namespace

A\B::foo();   // calls method "foo" of class "B" from namespace "A\A"
              // if class "A\A\B" not found, it tries to autoload class "A\A\B"

\A\B::foo();  // calls method "foo" of class "B" from namespace "A\B"
              // if class "A\B" not found, it tries to autoload class "A\B"
?>
Using namespaces: fallback to global function/constant
FAQ: things you need to know about namespaces
Namespaces


Classes and Objects

Table of Contents

  • Introduction
  • The Basics
  • Properties
  • Class Constants
  • Autoloading Classes
  • Constructors and Destructors
  • Visibility
  • Object Inheritance
  • Scope Resolution Operator (::)
  • Static Keyword
  • Class Abstraction
  • Object Interfaces
  • Overloading
  • Object Iteration
  • Patterns
  • Magic Methods
  • Final Keyword
  • Object Cloning
  • Comparing Objects
  • Type Hinting
  • Late Static Bindings
  • Objects and references
  • Object Serialization
Anonymous functions
Introduction
Language Reference


Class Abstraction

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

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

Example #1 Abstract class example

<?php
abstract class AbstractClass
{
    // Force Extending class to define this method
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // Common method
    public function printOut() {
        print $this->getValue() . "\n";
    }
}

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

class ConcreteClass2 extends AbstractClass
{
    public function getValue() {
        return "ConcreteClass2";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";

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

The above example will output:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.

Static Keyword
Object Interfaces
Classes and Objects


Autoloading Classes

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

Note: Prior to 5.3.0, exceptions thrown in the __autoload function could not be caught in the catch block and would result in a fatal error. From 5.3.0+ exceptions thrown in the __autoload function can be caught in the catch block, with 1 proviso. If throwing a custom exception, then the custom exception class must be available. The __autoload function may be used recursively to autoload the custom exception class.

Note: Autoloading is not available if using PHP in CLI interactive mode.

Note: If the class name is used e.g. in call_user_func() then it can contain some dangerous characters such as ../. It is recommended to not use the user-input in such functions or at least verify the input in __autoload().

Example #1 Autoload example

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

<?php
function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>

Example #2 Autoload other example

This example attempts to load the interface ITest.

<?php

function __autoload($name) {
    var_dump($name);
}

class Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
?>

Example #3 Autoloading with exception handling for 5.3.0+

This example throws an exception and demonstrates the try/catch block.

<?php
function __autoload($name) {
    echo "Want to load $name.\n";
    throw new Exception("Unable to load $name.");
}

try {
    $obj = new NonLoadableClass();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>

The above example will output:

Want to load NonLoadableClass.
Unable to load NonLoadableClass.

Example #4 Autoloading with exception handling for 5.3.0+ - Missing custom exception

This example throws an exception for a non-loadable, custom exception.

<?php
function __autoload($name) {
    echo "Want to load $name.\n";
    throw new MissingException("Unable to load $name.");
}

try {
    $obj = new NonLoadableClass();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>

The above example will output:

Want to load NonLoadableClass.
Want to load MissingException.

Fatal error: Class 'MissingException' not found in testMissingException.php on line 4

See Also

  • unserialize()
  • unserialize_callback_func
  • spl_autoload()
  • spl_autoload_register()

Class Constants
Constructors and Destructors
Classes and Objects


The Basics

class

Every class definition begins with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the class's properties and methods.

The class name can be any valid label which is a not a PHP reserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

A class may contain its own constants, variables (called "properties"), and functions (called "methods").

Example #1 Simple Class definition

<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

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

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Example #2 Some examples of the $this pseudo-variable

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class B
{
    function bar()
    {
        // Note: the next line will issue a warning if E_STRICT is enabled.
        A::foo();
    }
}

$a = new A();
$a->foo();

// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();

// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>

The above example will output:

$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.

new

To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

Example #3 Creating an instance

<?php
$instance = new SimpleClass();

// This can also be done with a variable:
$className = 'Foo';
$instance = new $className(); // Foo()
?>

In the class context, it is possible to create a new object by new self and new parent.

When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Example #4 Object Assignment

<?php

$instance = new SimpleClass();

$assigned   =  $instance;
$reference  =& $instance;

$instance->var = '$assigned will have this value';

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

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

The above example will output:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

extends

A class can inherit the methods and properties of another class by using the keyword extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.

The inherited methods and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method as final, that method may not be overridden. It is possible to access the overridden methods or static properties by referencing them with parent::.

Example #5 Simple Class Inheritance

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

$extended = new ExtendClass();
$extended->displayVar();
?>

The above example will output:

Extending class
a default value
Introduction
Properties
Classes and Objects


Object Cloning

Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.

$copy_of_object = clone $object;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.

Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

Example #1 Cloning an object

<?php
class SubObject
{
    static $instances = 0;
    public $instance;

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

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

class MyCloneable
{
    public $object1;
    public $object2;

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

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;

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

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

?>

The above example will output:

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)
Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)
Final Keyword
Comparing Objects
Classes and Objects


Class Constants

It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them.

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

Its also possible for interfaces to have constants. Look at the interface documentation for examples.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Example #1 Defining and using a constant

<?php
class MyClass
{
    const constant = 'constant value';

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

echo MyClass::constant . "\n";

$classname = "MyClass";
echo $classname::constant . "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::constant."\n"; // As of PHP 5.3.0
?>

Example #2 Static data example

<?php
class foo {
    // As of PHP 5.3.0
    const bar = <<<'EOT'
bar
EOT;
}
?>

Unlike heredocs, nowdocs can be used in any static data context.

Note: Nowdoc support was added in PHP 5.3.0.

Properties
Autoloading Classes
Classes and Objects


Constructors and Destructors

Constructor

void __construct ([ mixed $args [, $... ]] )

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

Example #1 using new unified constructors

<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

Destructor

void __destruct ( void )

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.

Example #2 Destructor Example

<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }

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

$obj = new MyDestructableClass();
?>

Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.

The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.

Note: Destructors called during the script shutdown have HTTP headers already sent. The working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).

Note: Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.

Autoloading Classes
Visibility
Classes and Objects


Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Example #1 Final methods example

<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Example #2 Final class example

<?php
final class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   // Here it doesn't matter if you specify the function as final or not
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>

Note: Properties cannot be declared final, only classes and methods may be declared as final.

Magic Methods
Object Cloning
Classes and Objects


Object Inheritance

Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another.

For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality.

Example #1 Inheritance Example

<?php

class foo
{
    public function printItem($string)
    {
        echo 'Foo: ' . $string . PHP_EOL;
    }

    public function printPHP()
    {
        echo 'PHP is great.' . PHP_EOL;
    }
}

class bar extends foo
{
    public function printItem($string)
    {
        echo 'Bar: ' . $string . PHP_EOL;
    }
}

$foo = new foo();
$bar = new bar();
$foo->printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP();       // Output: 'PHP is great'
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP();       // Output: 'PHP is great'

?>
Visibility
Scope Resolution Operator (::)
Classes and Objects


Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.

implements

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

Note: A class cannot implement two interfaces that share function names, since it would cause ambiguity.

Note: Interfaces can be extended like classes using the extends operator.

Note: The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

Constants

Its possible for interfaces to have constants. Interface constants works exactly like class constants. They cannot be overridden by a class/interface that inherits it.

Examples

Example #1 Interface example

<?php

// Declare the interface 'iTemplate'
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }

    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }

        return $template;
    }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
}
?>

Example #2 Extendable Interfaces

<?php
interface a
{
    public function foo();
}

interface b extends a
{
    public function baz(Baz $baz);
}

// This will work
class c implements b
{
    public function foo()
    {
    }

    public function baz(Baz $baz)
    {
    }
}

// This will not work and result in a fatal error
class d implements b
{
    public function foo()
    {
    }

    public function baz(Foo $foo)
    {
    }
}
?>

Example #3 Multiple interface inheritance

<?php
interface a
{
    public function foo();
}

interface b
{
    public function bar();
}

interface c extends a, b
{
    public function baz();
}

class d implements c
{
    public function foo()
    {
    }

    public function bar()
    {
    }

    public function baz()
    {
    }
}
?>

Example #4 Interfaces with constants

<?php
interface a
{
    const b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

// This will however not work because its not allowed to
// override constants. This is the same concept as with
// class constants
class b implements a
{
    const b = 'Class constant';
}
?>

An interface, together with type-hinting, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type hinting.

Class Abstraction
Overloading
Classes and Objects


Object Iteration

PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.

Example #1 Simple Object Iteration

<?php
class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';

    protected $protected = 'protected var';
    private   $private   = 'private var';

    function iterateVisible() {
       echo "MyClass::iterateVisible:\n";
       foreach($this as $key => $value) {
           print "$key => $value\n";
       }
    }
}

$class = new MyClass();

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

$class->iterateVisible();

?>

The above example will output:

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var

As the output shows, the foreach iterated through all visible variables that can be accessed. To take it a step further you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.

Example #2 Object Iteration implementing Iterator

<?php
class MyIterator implements Iterator
{
    private $var = array();

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

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

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

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

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

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

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

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

The above example will output:

rewinding
current: 1
valid: 1
current: 1
key: 0
0: 1
next: 2
current: 2
valid: 1
current: 2
key: 1
1: 2
next: 3
current: 3
valid: 1
current: 3
key: 2
2: 3
next:
current:
valid:

You can also define your class so that it doesn't have to define all the Iterator functions by simply implementing the PHP 5 IteratorAggregate interface.

Example #3 Object Iteration implementing IteratorAggregate

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

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

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

$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');

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

The above example will output:

rewinding
current: value 1
valid: 1
current: value 1
key: 0
key/value: [0 -> value 1]

next: value 2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1 -> value 2]

next: value 3
current: value 3
valid: 1
current: value 3
key: 2
key/value: [2 -> value 3]

next:
current:
valid:

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

Overloading
Patterns
Classes and Objects


Late Static Bindings

As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.

This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will no longer be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.

Limitations of self::

Static references to the current class like self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined:

Example #1 self:: usage

<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        self::who();
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();
?>

The above example will output:

A

Late Static Bindings' usage

Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. Basically, a keyword that would allow you to reference B from test() in the previous example. It was decided not to introduce a new keyword but rather use static that was already reserved.

Example #2 static:: simple usage

<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        static::who(); // Here comes Late Static Bindings
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();
?>

The above example will output:

B

Note: static:: does not work like $this for static methods! $this-> follows the rules of inheritance while static:: doesn't. This difference is detailed later on this manual page.

Example #3 static:: usage in a non-static context

<?php
class TestChild extends TestParent {
    public function __construct() {
        static::who();
    }

    public function test() {
        $o = new TestParent();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}

class TestParent {
    public function __construct() {
        static::who();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}
$o = new TestChild;
$o->test();

?>

The above example will output:

TestChild
TestParent

Note: Late static bindings' resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords like parent:: or self:: will forward the calling information.

Example #4 Forwarding and non-forwarding calls

<?php
class A {
    public static function foo() {
        static::who();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}

class B extends A {
    public static function test() {
        A::foo();
        parent::foo();
        self::foo();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}
class C extends B {
    public static function who() {
        echo __CLASS__."\n";
    }
}

C::test();
?>

The above example will output:

A
C
C

Edge cases

There are lots of different ways to trigger a method call in PHP, like callbacks or magic methods. As late static bindings base their resolution on runtime information, it might give unexpected results in so-called edge cases.

Example #5 Late static bindings inside magic methods

<?php
class A {

   protected static function who() {
        echo __CLASS__."\n";
   }

   public function __get($var) {
       return static::who();
   }
}

class B extends A {

   protected static function who() {
        echo __CLASS__."\n";
   }
}

$b = new B;
$b->foo;
?>

The above example will output:

B
Type Hinting
Objects and references
Classes and Objects


Magic Methods

The function names __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state and __clone are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

Caution

PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.

__sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

Note: It is not possible for __sleep to return names of private properties in parent classes. Doing this will result in an E_NOTICE level error. Instead you may use the Serializable interface.

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

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

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

Example #1 Sleep and wakeup

<?php
class Connection {
    protected $link;
    private $server, $username, $password, $db;

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

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

    public function __sleep()
    {
        return array('server', 'username', 'password', 'db');
    }

    public function __wakeup()
    {
        $this->connect();
    }
}
?>

__toString

The __toString method allows a class to decide how it will react when it is converted to a string.

Example #2 Simple example

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo) {
        $this->foo = $foo;
    }

    public function __toString() {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

The above example will output:

Hello

It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print(). Since PHP 5.2.0, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts (e.g. with %d modifier). Since PHP 5.2.0, converting objects without __toString method to string would cause E_RECOVERABLE_ERROR.

__invoke

The __invoke method is called when a script tries to call an object as a function.

Note: This feature is available since PHP 5.3.0.

Example #3 Using __invoke

<?php
class CallableClass {
    function __invoke($x) {
        var_dump($x);
    }
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>

The above example will output:

int(5)
bool(true)

__set_state

This static method is called for classes exported by var_export() since PHP 5.1.0.

The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).

Example #4 Using __set_state (since PHP 5.1.0)

<?php

class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array) // As of PHP 5.1.0
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

?>

The above example will output:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}
Patterns
Final Keyword
Classes and Objects


Comparing Objects

In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language).

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

An example will clarify these rules.

Example #1 Example of object comparison in PHP 5

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

function compareObjects(&$o1, &$o2)
{
    echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";
    echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";
    echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";
    echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n";
}

class Flag
{
    public $flag;

    function Flag($flag = true) {
        $this->flag = $flag;
    }
}

class OtherFlag
{
    public $flag;

    function OtherFlag($flag = true) {
        $this->flag = $flag;
    }
}

$o = new Flag();
$p = new Flag();
$q = $o;
$r = new OtherFlag();

echo "Two instances of the same class\n";
compareObjects($o, $p);

echo "\nTwo references to the same instance\n";
compareObjects($o, $q);

echo "\nInstances of two different classes\n";
compareObjects($o, $r);
?>

The above example will output:

Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Instances of two different classes
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Note: Extensions can define own rules for their objects comparison.

Object Cloning
Type Hinting
Classes and Objects


Overloading

Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.

The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and visibility.

All overloading methods must be defined as public.

Note: None of the arguments of these magic methods can be passed by reference.

Note: PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

Changelog

Version | Description
5.3.0 | Added __callStatic(). Added warning to enforce public visibility and non-static declaration.
5.1.0 | Added __isset() and __unset().

Property overloading

void __set ( string $name , mixed $value )
mixed __get ( string $name )
bool __isset ( string $name )
void __unset ( string $name )

__set() is run when writing data to inaccessible properties.

__get() is utilized for reading data from inaccessible properties.

__isset() is triggered by calling isset() or empty() on inaccessible properties.

__unset() is invoked when unset() is used on inaccessible properties.

The $name argument is the name of the property being interacted with. The __set() method's $value argument specifies the value the $name'ed property should be set to.

Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods should not be declared static. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is declared static.

Note: The return value of __set() is ignored because of the way PHP processes the assignment operator. Similarly, __get() is never called when chaining assignemnts together like this:

 $a = $obj->b = 8;

Example #1
     Overloading properties via the __get(),
     __set(), __isset()
     and __unset() methods

<?php
class PropertyTest {
    /**  Location for overloaded data.  */
    private $data = array();

    /**  Overloading not used on declared properties.  */
    public $declared = 1;

    /**  Overloading only used on this when accessed outside the class.  */
    private $hidden = 2;

    public function __set($name, $value) {
        echo "Setting '$name' to '$value'\n";
        $this->data[$name] = $value;
    }

    public function __get($name) {
        echo "Getting '$name'\n";
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }

        $trace = debug_backtrace();
        trigger_error(
            'Undefined property via __get(): ' . $name .
            ' in ' . $trace[0]['file'] .
            ' on line ' . $trace[0]['line'],
            E_USER_NOTICE);
        return null;
    }

    /**  As of PHP 5.1.0  */
    public function __isset($name) {
        echo "Is '$name' set?\n";
        return isset($this->data[$name]);
    }

    /**  As of PHP 5.1.0  */
    public function __unset($name) {
        echo "Unsetting '$name'\n";
        unset($this->data[$name]);
    }

    /**  Not a magic method, just here for example.  */
    public function getHidden() {
        return $this->hidden;
    }
}

echo "<pre>\n";

$obj = new PropertyTest;

$obj->a = 1;
echo $obj->a . "\n\n";

var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";

echo $obj->declared . "\n\n";

echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>

The above example will output:

Setting 'a' to '1'
Getting 'a'
1

Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)

1

Let's experiment with the private property named 'hidden':
Privates are visible inside the class, so __get() not used...
2
Privates not visible outside of class, so __get() is used...
Getting 'hidden'

Notice:  Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29

Method overloading

mixed __call ( string $name , array $arguments )
mixed __callStatic ( string $name , array $arguments )

__call() is triggered when invoking inaccessible methods in an object context.

__callStatic() is triggered when invoking inaccessible methods in a static context.

The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method.

Example #2 Overloading methods via the __call() and __callStatic() methods

<?php
class MethodTest {
    public function __call($name, $arguments) {
        // Note: value of $name is case sensitive.
        echo "Calling object method '$name' "
             . implode(', ', $arguments). "\n";
    }

    /**  As of PHP 5.3.0  */
    public static function __callStatic($name, $arguments) {
        // Note: value of $name is case sensitive.
        echo "Calling static method '$name' "
             . implode(', ', $arguments). "\n";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context');  // As of PHP 5.3.0
?>

The above example will output:

Calling object method 'runTest' in object context
Calling static method 'runTest' in static context
Object Interfaces
Object Iteration
Classes and Objects


Scope Resolution Operator (::)

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!

Example #1 :: from outside the class definition

<?php
class MyClass {
    const CONST_VALUE = 'A constant value';
}

$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0

echo MyClass::CONST_VALUE;
?>

Two special keywords self and parent are used to access properties or methods from inside the class definition.

Example #2 :: from inside the class definition

<?php
class OtherClass extends MyClass
{
    public static $my_static = 'static var';

    public static function doubleColon() {
        echo parent::CONST_VALUE . "\n";
        echo self::$my_static . "\n";
    }
}

$classname = 'OtherClass';
echo $classname::doubleColon(); // As of PHP 5.3.0

OtherClass::doubleColon();
?>

When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.

Example #3 Calling a parent's method

<?php
class MyClass
{
    protected function myFunc() {
        echo "MyClass::myFunc()\n";
    }
}

class OtherClass extends MyClass
{
    // Override parent's definition
    public function myFunc()
    {
        // But still call the parent function
        parent::myFunc();
        echo "OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();
?>
Object Inheritance
Static Keyword
Classes and Objects


Patterns

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.

Factory

The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Example #1 Parameterized Factory Method

<?php
class Example
{
    // The parameterized factory method
    public static function factory($type)
    {
        if (include_once 'Drivers/' . $type . '.php') {
            $classname = 'Driver_' . $type;
            return new $classname;
        } else {
            throw new Exception('Driver not found');
        }
    }
}
?>

Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:

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

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

Singleton

The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.

Example #2 Singleton Function

<?php
class Example
{
    // Hold an instance of the class
    private static $instance;

    // A private constructor; prevents direct creation of object
    private function __construct()
    {
        echo 'I am constructed';
    }

    // The singleton method
    public static function singleton()
    {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }

    // Example method
    public function bark()
    {
        echo 'Woof!';
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

}

?>

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

<?php
// This would fail because the constructor is private
$test = new Example;

// This will always retrieve a single instance of the class
$test = Example::singleton();
$test->bark();

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

?>
Object Iteration
Magic Methods
Classes and Objects


Properties

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

See Visibility for more information on the meanings of public, protected, and private.

Note: In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private. However, var is no longer required. In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning.
If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been declared as public.

Within class methods the properties, constants, and methods may be accessed by using the form $this->property (where property is the name of the property) unless the access is to a static property within the context of a static class method, in which case it is accessed using the form self::$property. See Static Keyword for more information.

The pseudo-variable $this is available inside any class method when that method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Example #1 property declarations

<?php
class SimpleClass
{
   // invalid property declarations:
   public $var1 = 'hello ' . 'world';
   public $var2 = <<<EOD
hello world
EOD;
   public $var3 = 1+2;
   public $var4 = self::myStaticMethod();
   public $var5 = $myVar;

   // valid property declarations:
   public $var6 = myConstant;
   public $var7 = array(true, false);

   // This is allowed only in PHP 5.3.0 and later.
   public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Note: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

Unlike heredocs, nowdocs can be used in any static data context, including property declarations.

Example #2 Example of using a nowdoc to initialize a property

<?php
class foo {
   // As of PHP 5.3.0
   public $bar = <<<'EOT'
bar
EOT;
}
?>

Note: Nowdoc support was added in PHP 5.3.0.

The Basics
Class Constants
Classes and Objects


Objects and references

One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

Example #1 References and Objects

<?php
class A {
    public $foo = 1;
}

$a = new A;
$b = $a;     // $a and $b are copies of the same identifier
             // ($a) = ($b) = <id>
$b->foo = 2;
echo $a->foo."\n";

$c = new A;
$d = &$c;    // $c and $d are references
             // ($c,$d) = <id>

$d->foo = 2;
echo $c->foo."\n";

$e = new A;

function foo($obj) {
    // ($obj) = ($e) = <id>
    $obj->foo = 2;
}

foo($e);
echo $e->foo."\n";

?>

The above example will output:

2
2
2
Late Static Bindings
Object Serialization
Classes and Objects


Object Serialization

Serializing objects - objects in sessions

serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The methods in an object will not be saved, only the name of the class.

In order to be able to unserialize() an object, the class of that object needs to be defined. That is, if you have an object of class A and serialize this, you'll get a string that refers to class A and contains all values of variables contained in it. If you want to be able to unserialize this in another file, an object of class A, the definition of class A must be present in that file first. This can be done for example by storing the class definition of class A in an include file and including this file or making use of the spl_autoload_register() function.

<?php
// classa.inc:

  class A {
      public $one = 1;

      public function show_one() {
          echo $this->one;
      }
  }

// page1.php:

  include("classa.inc");

  $a = new A;
  $s = serialize($a);
  // store $s somewhere where page2.php can find it.
  file_put_contents('store', $s);

// page2.php:

  // this is needed for the unserialize to work properly.
  include("classa.inc");

  $s = file_get_contents('store');
  $a = unserialize($s);

  // now use the function show_one() of the $a object.
  $a->show_one();
?>

If an application is using sessions and uses session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This means that these objects can show up on any of the application's pages once they become part of the session. However, session_register() is deprecated as of PHP 5.3.0, and removed as of PHP 6.0.0. Reliance on this function is not recommended.

It is strongly recommended that if an application serializes objects, for use later in the application, that the application include the class definition for that object throughout the application. Not doing so might result in an object being unserialized without a class definition, which will result in PHP giving the object a class of __PHP_Incomplete_Class_Name, which has no methods and would render the object useless.

So if in the example above $a became part of a session by running session_register("a"), you should include the file classa.inc on all of your pages, not only page1.php and page2.php.

Objects and references
Namespaces
Classes and Objects


Static Keyword

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).

For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public.

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

Static properties cannot be accessed through the object using the arrow operator ->.

Calling non-static methods statically generates an E_STRICT level warning.

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Example #1 Static property example

<?php
class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}

class Bar extends Foo
{
    public function fooStatic() {
        return parent::$my_static;
    }
}

print Foo::$my_static . "\n";

$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n";      // Undefined "Property" my_static

print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0

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

Example #2 Static method example

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>
Scope Resolution Operator (::)
Class Abstraction
Classes and Objects


Type Hinting

PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

Example #1 Type Hinting examples

<?php
// An example class
class MyClass
{
    /**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }

    /**
     * Another test function
     *
     * First parameter must be an array
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }
}

// Another example class
class OtherClass {
    public $var = 'Hello World';
}
?>

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

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

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

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

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

// Works: Prints Hello World
$myclass->test($otherclass);

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

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

Type hinting also works with functions:

<?php
// An example class
class MyClass {
    public $var = 'Hello World';
}

/**
 * A test function
 *
 * First parameter must be an object of type MyClass
 */
function MyFunction (MyClass $foo) {
    echo $foo->var;
}

// Works
$myclass = new MyClass;
MyFunction($myclass);
?>

Type hinting allowing NULL value:

<?php

/* Accepting NULL value */
function test(stdClass $obj = NULL) {

}

test(NULL);
test(new stdClass);

?>

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.

Comparing Objects
Late Static Bindings
Classes and Objects


Visibility

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Property Visibility

Class properties must be defined as public, private, or protected. If declared using var without an explicit visibility keyword, the property will be defined as public.

Example #1 Property declaration

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

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private

/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected method, but not private
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined

?>

Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.

Method Visibility

Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.

Example #2 Method Declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    // Declare a public constructor
    public function __construct() { }

    // Declare a public method
    public function MyPublic() { }

    // Declare a protected method
    protected function MyProtected() { }

    // Declare a private method
    private function MyPrivate() { }

    // This is public
    function Foo()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}

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

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

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

class Bar
{
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    public function testPublic() {
        echo "Bar::testPublic\n";
    }

    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}

class Foo extends Bar
{
    public function testPublic() {
        echo "Foo::testPublic\n";
    }

    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
                // Foo::testPublic
?>

Constructors and Destructors
Object Inheritance
Classes and Objects


Operators

Table of Contents

  • Operator Precedence
  • Arithmetic Operators
  • Assignment Operators
  • Bitwise Operators
  • Comparison Operators
  • Error Control Operators
  • Execution Operators
  • Incrementing/Decrementing Operators
  • Logical Operators
  • String Operators
  • Array Operators
  • Type Operators

An operator is something that you feed with one or more values (or expressions, in programming jargon) which yields another value (so that the construction itself becomes an expression). So you can think of functions or constructions that return a value (like print) as operators and those that return nothing (like echo) as any other thing.

There are three types of operators. Firstly there is the unary operator which operates on only one value, for example ! (the negation operator) or ++ (the increment operator). The second group are termed binary operators; this group contains most of the operators that PHP supports, and a list follows below in the section Operator Precedence.

The third group is the ternary operator: ?:. It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution. Surrounding ternary expressions with parentheses is a very good idea.

Expressions
Operator Precedence
Language Reference


Arithmetic Operators

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

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

The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.

Operands of modulus are converted to integers (by stripping the decimal part) before processing.

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

See also the manual page on Math functions.

Operator Precedence
Assignment Operators
Operators


Array Operators

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

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

<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>

When executed, this script will print the following:

Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(10) "strawberry"
  ["c"]=>
  string(6) "cherry"
}

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

Example #1 Comparing arrays

<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

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

String Operators
Type Operators
Operators


Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the rights (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:

<?php

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

?>

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:

<?php

$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

?>

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop. Assignment by reference is also supported, using the $var = &$othervar; syntax. 'Assignment by reference' means that both variables end up pointing at the same data, and nothing is copied anywhere. To learn more about references, please read References explained. As of PHP 5, objects are assigned by reference unless explicitly told otherwise with the new clone keyword.

Arithmetic Operators
Bitwise Operators
Operators


Bitwise Operators

Bitwise operators allow evaluation and manipulation of specific bits within an integer.

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

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved.

Use parentheses to ensure the desired precedence. For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency.

Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.

PHP's error_reporting ini setting uses bitwise values,
providing a real-world demonstration of turning
bits off. To show all errors, except for notices,
the php.ini file instructions say to use:
E_ALL & ~E_NOTICE

This works by starting with E_ALL:
00000000000000000111011111111111
Then taking the value of E_NOTICE...
00000000000000000000000000001000
... and inverting it via ~:
11111111111111111111111111110111
Finally, it uses AND (&) to find the bits turned
on in both values:
00000000000000000111011111110111

Another way to accomplish that is using XOR (^)
to find bits that are on in only one value or the other:
E_ALL ^ E_NOTICE

error_reporting can also be used to demonstrate turning bits on.
The way to show just errors and recoverable errors is:
E_ERROR | E_RECOVERABLE_ERROR

This process combines E_ERROR
00000000000000000000000000000001
and
00000000000000000001000000000000
using the OR (|) operator
to get the bits turned on in either value:
00000000000000000001000000000001

Example #1 Bitwise AND, OR and XOR operations on integers

<?php
/*
 * Ignore the top section,
 * it is just formatting to make output clearer.
 */

$format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)'
        . ' %3$s (%4$2d = %4$04b)' . "\n";

echo <<<EOH
 ---------     ---------  -- ---------
 result        value      op test
 ---------     ---------  -- ---------
EOH;

/*
 * Here are the examples.
 */

$values = array(0, 1, 2, 4, 8);
$test = 1 + 4;

echo "\n Bitwise AND \n";
foreach ($values as $value) {
    $result = $value & $test;
    printf($format, $result, $value, '&', $test);
}

echo "\n Bitwise Inclusive OR \n";
foreach ($values as $value) {
    $result = $value | $test;
    printf($format, $result, $value, '|', $test);
}

echo "\n Bitwise Exclusive OR (XOR) \n";
foreach ($values as $value) {
    $result = $value ^ $test;
    printf($format, $result, $value, '^', $test);
}
?>

The above example will output:

 ---------     ---------  -- ---------
 result        value      op test
 ---------     ---------  -- ---------
 Bitwise AND
( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101)
( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)
( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101)
( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101)
( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101)

 Bitwise Inclusive OR
( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101)
( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101)
( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) | ( 5 = 0101)

 Bitwise Exclusive OR (XOR)
( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101)
( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101)
( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101)

Example #2 Bitwise XOR operations on strings

<?php
echo 12 ^ 9; // Outputs '5'

echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
                        // 'a' ^ 'e' = #4

echo 2 ^ "3"; // Outputs 1
              // 2 ^ ((int)"3") == 1

echo "2" ^ 3; // Outputs 1
              // ((int)"2") ^ 3 == 1
?>

Example #3 Bit shifting on integers

<?php
/*
 * Here are the examples.
 */

echo "\n--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---\n";

$val = 4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');

$val = 4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places);

$val = 4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');

$val = 4;
$places = 4;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond 0');

echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');

$val = -4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');

$val = -4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond -1');

echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n";

$val = 4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');

$val = 4;
$places = (PHP_INT_SIZE * 8) - 4;
$res = $val << $places;
p($res, $val, '<<', $places);

$val = 4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places, 'sign bits get shifted out');

$val = 4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side');

echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');

$val = -4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places);

$val = -4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side, including sign bit');

/*
 * Ignore this bottom section,
 * it is just formatting to make output clearer.
 */

function p($res, $val, $op, $places, $note = '') {
    $format = '%0' . (PHP_INT_SIZE * 8) . "b\n";

    printf("Expression: %d = %d %s %d\n", $res, $val, $op, $places);

    echo " Decimal:\n";
    printf("  val=%d\n", $val);
    printf("  res=%d\n", $res);

    echo " Binary:\n";
    printf('  val=' . $format, $val);
    printf('  res=' . $format, $res);

    if ($note) {
        echo " NOTE: $note\n";
    }

    echo "\n";
}
?>

Output of the above example on 32 bit machines:

--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
 Decimal:
  val=4
  res=2
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000010
 NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
 Decimal:
  val=4
  res=1
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000001

Expression: 0 = 4 >> 3
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: bits shift out right side

Expression: 0 = 4 >> 4
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: same result as above; can not shift beyond 0

--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
 Decimal:
  val=-4
  res=-2
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111110
 NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
 Decimal:
  val=-4
  res=-1
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTE: bits shift out right side

Expression: -1 = -4 >> 3
 Decimal:
  val=-4
  res=-1
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTE: same result as above; can not shift beyond -1

--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
 Decimal:
  val=4
  res=8
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000001000
 NOTE: zeros fill in right side

Expression: 1073741824 = 4 << 28
 Decimal:
  val=4
  res=1073741824
 Binary:
  val=00000000000000000000000000000100
  res=01000000000000000000000000000000

Expression: -2147483648 = 4 << 29
 Decimal:
  val=4
  res=-2147483648
 Binary:
  val=00000000000000000000000000000100
  res=10000000000000000000000000000000
 NOTE: sign bits get shifted out

Expression: 0 = 4 << 30
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: bits shift out left side

--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
 Decimal:
  val=-4
  res=-8
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111000
 NOTE: zeros fill in right side

Expression: -2147483648 = -4 << 29
 Decimal:
  val=-4
  res=-2147483648
 Binary:
  val=11111111111111111111111111111100
  res=10000000000000000000000000000000

Expression: 0 = -4 << 30
 Decimal:
  val=-4
  res=0
 Binary:
  val=11111111111111111111111111111100
  res=00000000000000000000000000000000
 NOTE: bits shift out left side, including sign bit

Output of the above example on 64 bit machines:

--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
 Decimal:
  val=4
  res=2
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000010
 NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
 Decimal:
  val=4
  res=1
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000001

Expression: 0 = 4 >> 3
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out right side

Expression: 0 = 4 >> 4
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: same result as above; can not shift beyond 0

--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
 Decimal:
  val=-4
  res=-2
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111110
 NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
 Decimal:
  val=-4
  res=-1
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTE: bits shift out right side

Expression: -1 = -4 >> 3
 Decimal:
  val=-4
  res=-1
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTE: same result as above; can not shift beyond -1

--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
 Decimal:
  val=4
  res=8
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000001000
 NOTE: zeros fill in right side

Expression: 4611686018427387904 = 4 << 60
 Decimal:
  val=4
  res=4611686018427387904
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0100000000000000000000000000000000000000000000000000000000000000

Expression: -9223372036854775808 = 4 << 61
 Decimal:
  val=4
  res=-9223372036854775808
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=1000000000000000000000000000000000000000000000000000000000000000
 NOTE: sign bits get shifted out

Expression: 0 = 4 << 62
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out left side

--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
 Decimal:
  val=-4
  res=-8
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111000
 NOTE: zeros fill in right side

Expression: -9223372036854775808 = -4 << 61
 Decimal:
  val=-4
  res=-9223372036854775808
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1000000000000000000000000000000000000000000000000000000000000000

Expression: 0 = -4 << 62
 Decimal:
  val=-4
  res=0
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out left side, including sign bit

Warning

Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits. Use functions from the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX.

See also
pack(),
unpack(),
gmp_and(),
gmp_or(),
gmp_xor(),
gmp_testbit(),
gmp_clrbit()

Assignment Operators
Comparison Operators
Operators


Comparison Operators

Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

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

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true

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

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

Comparison with Various Types
Type of Operand 1 | Type of Operand 2 | Result
null or string | string | Convert NULL to "", numerical or lexical comparison
bool or null | anything | Convert to bool, FALSE < TRUE
object | object | Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation
string, resource or number | string, resource or number | Translate strings and resources to numbers, usual math
array | array | Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example)
array | anything | array is always greater
object | anything | object is always greater

Example #1 Transcription of standard array comparison

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

See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.

Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Example #2 Assigning a default value

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

?>

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

Note: It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

Example #3 Non-obvious Ternary Behaviour

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

Bitwise Operators
Error Control Operators
Operators


Error Control Operators

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

See also error_reporting() and the manual section for Error Handling and Logging functions.

Warning

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

Comparison Operators
Execution Operators
Operators


Execution Operators

PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().

<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>

Note: The backtick operator is disabled when safe mode is enabled or shell_exec() is disabled.

See also the manual section on Program Execution functions, popen() proc_open(), and Using PHP from the commandline.

Error Control Operators
Incrementing/Decrementing Operators
Operators


Incrementing/Decrementing Operators

PHP supports C-style pre- and post-increment and decrement operators.

Note: The increment/decrement operators do not affect boolean values. Decrementing NULL values has no effect too, but incrementing them results in 1.

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

Here's a simple example script:

<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";

echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.

Example #1 Arithmetic Operations on Character Variables

<?php
$i = 'W';
for ($n=0; $n<6; $n++) {
    echo ++$i . "\n";
}
?>

The above example will output:

X
Y
Z
AA
AB
AC

Incrementing or decrementing booleans has no effect.

Execution Operators
Logical Operators
Operators


Logical Operators

Logical Operators
Example | Name | Result
$a and $b | And | TRUE if both $a and $b are TRUE.
$a or $b | Or | TRUE if either $a or $b is TRUE.
$a xor $b | Xor | TRUE if either $a or $b is TRUE, but not both.
! $a | Not | TRUE if $a is not TRUE.
$a && $b | And | TRUE if both $a and $b are TRUE.
$a || $b | Or | TRUE if either $a or $b is TRUE.

The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)

Example #1 Logical operators illustrated

<?php

// --------------------
// foo() will never get called as those operators are short-circuit

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

// --------------------
// "||" has a greater precedence than "or"

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($e = false) or true)
$f = false or true;

var_dump($e, $f);

// --------------------
// "&&" has a greater precedence than "and"

// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;

// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;

var_dump($g, $h);
?>

The above example will output something similar to:

bool(true)
bool(false)
bool(false)
bool(true)
Incrementing/Decrementing Operators
String Operators
Operators


Operator Precedence

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. If operator precedence is equal, left to right associativity is used.

The following table lists the precedence of operators with the highest-precedence operators listed at the top of the table. Operators on the same line have equal precedence, in which case their associativity decides which order to evaluate them in.

Operator Precedence
Associativity | Operators | Additional Information
non-associative | clone new | clone and new
left | [ | array()
non-associative | ++ -- | increment/decrement
right | ~ - (int) (float) (string) (array) (object) (bool) @ | types
non-associative | instanceof | types
right | ! | logical
left | * / % | arithmetic
left | + - . | arithmetic and string
left | << >> | bitwise
non-associative | < <= > >= <> | comparison
non-associative | == != === !== | comparison
left | & | bitwise and references
left | ^ | bitwise
left | | | bitwise
left | && | logical
left | || | logical
left | ? : | ternary
right | = += -= *= /= .= %= &= |= ^= <<= >>= | assignment
left | and | logical
left | xor | logical
left | or | logical
left | , | many uses

Left associativity means that the expression is evaluated from left to right, right associativity means the opposite.

Example #1 Associativity

<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>

Use parentheses to increase readability of the code.

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

Operators
Arithmetic Operators
Operators


String Operators

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";     // now $a contains "Hello World!"
?>

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

Logical Operators
Array Operators
Operators


Type Operators

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:

Example #1 Using instanceof with classes

<?php
class MyClass
{
}

class NotMyClass
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>

The above example will output:

bool(true)
bool(false)

instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:

Example #2 Using instanceof with inherited classes

<?php
class ParentClass
{
}

class MyClass extends ParentClass
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>

The above example will output:

bool(true)
bool(true)

To check if an object is not an instanceof a class, the logical not operator can be used.

Example #3 Using instanceof to check if object is not an instanceof a class

<?php
class MyClass
{
}

$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>

The above example will output:

bool(true)

Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface:

Example #4 Using instanceof for class

<?php
interface MyInterface
{
}

class MyClass implements MyInterface
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>

The above example will output:

bool(true)
bool(true)

Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable:

Example #5 Using instanceof with other variables

<?php
interface MyInterface
{
}

class MyClass implements MyInterface
{
}

$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';

var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
?>

The above example will output:

bool(true)
bool(true)
bool(false)

There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This can be worked around by using a dynamic class reference, or a string variable containing the class name:

Example #6 Avoiding classname lookups and fatal errors with instanceof in PHP 5.0

<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>

The above example will output:

bool(false)

The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof. Note that as of PHP 5.3.0, is_a() is no longer deprecated.

See also get_class() and is_a().

Array Operators
Control Structures
Operators


Pseudo-types and variables used in this documentation

mixed

mixed indicates that a parameter may accept multiple (but not necessarily all) types.

gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.

number

number indicates that a parameter can be either integer or float.

callback

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.

A PHP function is passed by its name as a string. Any built-in
or user-defined function can be used, except language constructs such as:
array(), echo(),
empty(), eval(),
exit(), isset(),
list(), print() or
unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0.

Apart from common user-defined function, create_function() can also be used to create an anonymous callback function. As of PHP 5.3.0 it is possible to also pass a closure to a callback parameter.

Example #1 Callback function examples

<?php

// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// An example callback method
class MyClass {
    static function myCallbackMethod() {
        echo 'Hello World!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function');

// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod'));

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
    public static function who() {
        echo "A\n";
    }
}

class B extends A {
    public static function who() {
        echo "B\n";
    }
}

call_user_func(array('B', 'parent::who')); // A
?>

Example #2 Callback example using a Closure

<?php
// Our closure
$double = function($a) {
    return $a * 2;
};

// This is our range of numbers
$numbers = range(1, 5);

// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map($double, $numbers);

print implode(' ', $new_numbers);
?>

The above example will output:

2 4 6 8 10

Note: In PHP4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.

Note: Callbacks registered with functions such as call_user_func() and call_user_func_array() will not be called if there is an uncaught exception thrown in a previous callback.

void

void as a return type means that the return value is useless. void in a parameter list means that the function doesn't accept any parameters.

...

$... in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments.

NULL
Type Juggling
Types


References Explained

Table of Contents

  • What References Are
  • What References Do
  • What References Are Not
  • Passing by Reference
  • Returning References
  • Unsetting References
  • Spotting References
Extending Exceptions
What References Are
Language Reference


What References Are Not

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

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

What happens is that $var in foo will be bound with $bar in the caller, but then re-bound with $GLOBALS["baz"]. There's no way to bind $bar in the calling scope to something else using the reference mechanism, since $bar is not available in the function foo (it is represented by $var, but $var has only variable contents and not name-to-value binding in the calling symbol table). You can use returning references to reference variables selected by the function.

What References Do
Passing by Reference
References Explained


Passing by Reference

You can pass a variable by reference to a function so the function can modify the variable. The syntax is as follows:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
// $a is 6 here
?>

Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

The following things can be passed by reference:

  • Variables, i.e. foo($a)
  • New statements, i.e. foo(new foobar())

  • References returned from functions, i.e.:

    <?php
    function foo(&$var)
    {
            $var++;
    }
    function &    bar()
    {
            $a = 5;
        return     $a;
    }
    foo(bar());
    ?>

    See more about returning by reference.

No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

<?php
function foo(&$var)
{
    $var++;
}
function bar() // Note the missing &
{
    $a = 5;
    return $a;
}
foo(bar()); // Produces fatal error since PHP 5.0.5

foo($a = 5); // Expression, not variable
foo(5); // Produces fatal error
?>

These requirements are for PHP 4.0.4 and later.

What References Are Not
Returning References
References Explained


Returning References

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so. To return references, use this syntax:

<?php
class foo {
    public $value = 42;

    public function &getValue() {
        return $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue;                // prints the new value of $obj->value, i.e. 2.
?>

In this example, the property of the object returned by the getValue function would be set, not the copy, as it would be without using reference syntax.

Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue.

Note: If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else. Since PHP 4.4.0 in the PHP4 branch, and PHP 5.1.0 in the PHP5 branch, an E_NOTICE error is issued if the code tries to return a dynamic expression or a result of the new operator.

Passing by Reference
Unsetting References
References Explained


Spotting References

Many syntax constructs in PHP are implemented via referencing mechanisms, so everything mentioned herein about reference binding also applies to these constructs. Some constructs, like passing and returning by reference, are mentioned above. Other constructs that use references are:

global References

When you declare a variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:

<?php
$var =& $GLOBALS["var"];
?>

This also means that unsetting $var won't unset the global variable.

$this

In an object method, $this is always a reference to the caller object.

Unsetting References
Predefined Variables
References Explained


Unsetting References

When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:

<?php
$a = 1;
$b =& $a;
unset($a);
?>

won't unset $b, just $a.

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

Returning References
Spotting References
References Explained


What References Are

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on. See What References Are Not for more information. Instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.

References Explained
What References Do
References Explained


What References Do

There are three basic operations performed using references: assigning by reference, passing by reference, and returning by reference. This section will give an introduction to these operations, with links to further reading.

Assign By Reference

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

<?php
$a =& $b;
?>

it means that $a and $b point to the same content.

Note: $a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place.

Note: If arrays with references are copied, their values are not dereferenced. This is valid also for arrays passed by value to functions.

Note: If you assign, pass, or return an undefined variable by reference, it will get created.

Example #1 Using references with undefined variables

<?php
function foo(&$var) { }

foo($a); // $a is "created" and assigned to null

$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)

$c = new StdClass;
foo($c->d);
var_dump(property_exists($c, 'd')); // bool(true)
?>

The same syntax can be used with functions that return references, and with the new operator (since PHP 4.0.4 and before PHP 5.0.0):

<?php
$foo =& find_var($bar);
?>

Since PHP 5, new returns a reference automatically, so using =& in this context is deprecated and produces an E_STRICT message.

Warning

If you assign a reference to a variable declared global inside a function, the reference will be visible only inside the function. You can avoid this by using the $GLOBALS array.

Example #2 Referencing global variables inside functions

<?php
$var1 = "Example variable";
$var2 = "";

function global_references($use_globals)
{
    global $var1, $var2;
    if (!$use_globals) {
        $var2 =& $var1; // visible only inside the function
    } else {
        $GLOBALS["var2"] =& $var1; // visible also in global context
    }
}

global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable'
?>

Think about global $var; as a shortcut to $var =& $GLOBALS['var'];. Thus assigning another reference to $var only changes the local variable's reference.

Note: If you assign a value to a variable with references in a foreach statement, the references are modified too.

Example #3 References and foreach statement

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

Pass By Reference

The second thing references do is to pass variables by reference. This is done by making a local variable in a function and a variable in the calling scope referencing the same content. Example:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
?>

will make $a to be 6. This happens because in the function foo the variable $var refers to the same content as $a. For more information on this, read the passing by reference section.

Return By Reference

The third thing references can do is return by reference.

What References Are
What References Are Not
References Explained


Types

Table of Contents

  • Introduction
  • Booleans
  • Integers
  • Floating point numbers
  • Strings
  • Arrays
  • Objects
  • Resources
  • NULL
  • Pseudo-types and variables used in this documentation
  • Type Juggling
Comments
Introduction
Language Reference


Arrays

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.

Syntax

Specifying with array()

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

array(  key =>  value
     , ...
     )
// key may only be an integer or string
// value may be any value of any type
<?php
$arr = array("foo" => "bar", 12 => true);

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

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

A value can be any PHP type.

Note: Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.

<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

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

If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.

<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);

// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
Warning

Before PHP 4.3.0, appending to an array in which the current maximum key was negative would create a new key as described above. Since PHP 4.3.0, the new key will be 0.

Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string. Using the empty string as a key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

Creating/modifying with square bracket syntax

An existing array can be modified by explicitly setting values in it.

This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.

<?php
$arr = array(5 => 1, 12 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

$arr["x"] = 42; // This adds a new element to
                // the array with key "x"

unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array
?>

Note: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero).
Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
    unset($array[$i]);
}
print_r($array);

// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
print_r($array);

// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>

The above example will output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Note: The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

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

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

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.

Array do's and don'ts

Why is $foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:

<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

Note: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
    echo "\nChecking $i: \n";
    echo "Bad: " . $array['$i'] . "\n";
    echo "Good: " . $array[$i] . "\n";
    echo "Bad: {$array['$i']}\n";
    echo "Good: {$array[$i]}\n";
}
?>

The above example will output:

Checking 0:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad:
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad:
Good: 1

Checking 1:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad:
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad:
Good: 2

More examples to demonstrate this behaviour:

<?php
// Show all errors
error_reporting(E_ALL);

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// This defines a constant to demonstrate what's going on.  The value 'veggie'
// is assigned to a constant named fruit.
define('fruit', 'veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]";      // Hello apple

// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>

When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices.

As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works:

<?php
echo $arr[somefunc($bar)];
?>

This is an example of using a function return value as the array index. PHP also knows about constants:

<?php
$error_descriptions[E_ERROR]   = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

<?php
$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

because E_ERROR equals 1, etc.

So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords.

Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.

Converting to array

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

<?php

class A {
    private $A; // This will become '\0A\0A'
}

class B extends A {
    private $A; // This will become '\0B\0A'
    public $AA; // This will become 'AA'
}

var_dump((array) new B());
?>

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

Converting NULL to an array results in an empty array.

Comparing

It is possible to compare arrays with the array_diff() function and with array operators.

Examples

The array type in PHP is very versatile. Here are some examples:

<?php
// This:
$a = array( 'color' => 'red',
            'taste' => 'sweet',
            'shape' => 'round',
            'name'  => 'apple',
            4        // key will be 0
          );

$b = array('a', 'b', 'c');

// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), and $b will be the array
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>

Example #1 Using array()

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

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

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

// empty array
$empty = array();
?>

Example #2 Collection

<?php
$colors = array('red', 'blue', 'green', 'yellow');

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

?>

The above example will output:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Changing the values of the array directly is possible since PHP 5 by passing them by reference. Before that, a workaround is necessary:

Example #3 Collection

<?php
// PHP 5
foreach ($colors as &$color) {
    $color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions
foreach ($colors as $key => $color) {
    $colors[$key] = strtoupper($color);
}

print_r($colors);
?>

The above example will output:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

This example creates a one-based array.

Example #4 One-based index

<?php
$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

The above example will output:

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

Example #5 Filling an array

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

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array.

Example #6 Sorting an array

<?php
sort($files);
print_r($files);
?>

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

Example #7 Recursive and multi-dimensional arrays

<?php
$fruits = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                                     ),
                  "numbers" => array ( 1,
                                       2,
                                       3,
                                       4,
                                       5,
                                       6
                                     ),
                  "holes"   => array (      "first",
                                       5 => "second",
                                            "third"
                                     )
                );

// Some examples to address values in the array above
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

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

$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>
Strings
Objects
Types


Booleans

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

Note: The boolean type was introduced in PHP 4.

Syntax

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

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

Typically, some kind of operator which returns a boolean value, and the value is passed on to a control structure.

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

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

// ...because instead, this can be used:
if ($show_separators) {
    echo "<hr>\n";
}
?>

Converting to boolean

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

See also Type Juggling.

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

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

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

Warning

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

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


Floating point numbers

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

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

Formally:

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

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

Warning

Floating point precision

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

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

So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Converting to float

For information on converting strings to float, see String conversion to numbers. For values of other types, the conversion is performed by converting the value to integer first and then to float. See Converting to integer for more information. As of PHP 5, a notice is thrown if an object is converted to float.

Integers
Strings
Types


Integers

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

See also:

  • Arbitrary length integer / GMP
  • Floating point numbers
  • Arbitrary precision / BCMath

Syntax

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

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x.

Example #1 Integer literals

<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
?>

Formally, the structure for integer literals is:

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

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

octal       : 0[0-7]+

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

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bits platforms usually have the maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

Warning

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

Example #2 Octal weirdness

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

Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

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

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

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

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

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

Unfortunately, there was a bug in PHP which caused this to not always work correctly when negative numbers were involved. For example, the result of -50000 * $million is -429496728. However, when both operands were positive, there was no problem.

This was fixed in PHP 4.1.0.

There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.

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

Converting to integer

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

See also: type-juggling.

From booleans

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

From floating point numbers

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

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

Warning

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

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

See also the warning about float precision.

From strings

See String conversion to numbers

From other types

Caution

The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice.

Booleans
Floating point numbers
Types


Introduction

PHP supports eight primitive types.

Four scalar types:

  • boolean
  • integer
  • float (floating-point number, aka double)
  • string

Two compound types:

  • array
  • object

And finally two special types:

  • resource
  • NULL

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

  • mixed
  • number
  • callback

And the pseudo-variable $... .

Some references to the type "double" may remain in the manual. Consider double the same as float; the two names exist only for historic reasons.

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

Note: To check the type and value of an expression, use the var_dump() function. To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use gettype(), but rather the is_type functions. Some examples:

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

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

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

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

To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it.

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

Types
Booleans
Types


NULL

The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.

Note: The null type was introduced in PHP 4.

A variable is considered to be null if:

  • it has been assigned the constant NULL.

  • it has not been set to any value yet.

  • it has been unset().

Syntax

There is only one value of type null, and that is the case-insensitive keyword NULL.

<?php
$var = NULL;
?>

See also the functions is_null() and unset().

Casting to NULL

Casting a variable to null will remove the variable and unset its value.

Resources
Pseudo-types and variables used in this documentation
Types


Objects

Object Initialization

To create a new object, use the new statement to instantiate a class:

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo.";
    }
}

$bar = new foo;
$bar->do_foo();
?>

For a full discussion, see the Classes and Objects chapter.

Converting to object

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.

<?php
$obj = (object) 'ciao';
echo $obj->scalar;  // outputs 'ciao'
?>
Arrays
Resources
Types


Resources

A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.

Note: The resource type was introduced in PHP 4

See also the get_resource_type() function.

Converting to resource

As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.

Freeing resources

Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

Note: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information.

Objects
NULL
Types


Strings

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

Note: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running.

Syntax

A string literal can be specified in four different ways:

  • single quoted
  • double quoted
  • heredoc syntax
  • nowdoc syntax (since PHP 5.3.0)

Single quoted

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

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash before a single quote, or at the end of the string, double it (\\). Note that attempting to escape any other character will print the backslash too.

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

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

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

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

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

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

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

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

Double quoted

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

Escaped characters
Sequence | Meaning
\n | linefeed (LF or 0x0A (10) in ASCII)
\r | carriage return (CR or 0x0D (13) in ASCII)
\t | horizontal tab (HT or 0x09 (9) in ASCII)
\v | vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\f | form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ | backslash
\$ | dollar sign
\" | double-quote
\[0-7]{1,3} | the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} | the sequence of characters matching the regular expression is a character in hexadecimal notation

As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed.

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

Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

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

Warning

It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.

If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

Example #1 Invalid example

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

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

Example #2 Heredoc string quoting example

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

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

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

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

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

The above example will output:

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

It is also possible to use the Heredoc syntax to pass data to function arguments:

Example #3 Heredoc in arguments example

<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>

As of PHP 5.3.0, its possible to initialize static variables and class properties/constants using the Heredoc syntax:

Example #4 Using Heredoc to initialize static values

<?php
// Static variables
function foo()
{
    static $bar = <<<LABEL
Nothing in here...
LABEL;
}

// Class properties/constants
class foo
{
    const BAR = <<<FOOBAR
Constant example
FOOBAR;

    public $baz = <<<FOOBAR
Property example
FOOBAR;
}
?>

PHP 5.3.0 also introduces the possibility for Heredoc's to use double quotes in declarings:

Example #5 Using double quotes in Heredoc

<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>

Note: Heredoc support was added in PHP 4.

Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

Example #6 Nowdoc string quoting example

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

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

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

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

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

The above example will output:

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

Note: Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class properties or constants:

Example #7 Static data example

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

Note: Nowdoc support was added in PHP 5.3.0.

Variable parsing

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

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

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

Simple syntax

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

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

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

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

// Show all errors
error_reporting(E_ALL);

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

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

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

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

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

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

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

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

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

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

In fact, any value in the namespace can be included in a string with this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

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

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

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

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

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

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

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

echo "This works too: {$obj->values[3]->name}";

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

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>

It is also possible to access class properties using variables within strings using this syntax.

<?php
class foo {
    var $bar = 'I am bar.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}\n";
echo "{$foo->$baz[1]}\n";
?>

The above example will output:

I am bar.
I am bar.

Note: Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

<?php
// Show all errors.
error_reporting(E_ALL);

class beers {
    const softdrink = 'rootbeer';
    public static $ale = 'ipa';
}

$rootbeer = 'A & W';
$ipa = 'Alexander Keith\'s';

// This works; outputs: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";

// This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>

String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose.

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 5.3.0. Use square brackets instead, such as $str[42].

Warning

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NUL byte.

Example #8 Some string examples

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

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

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

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

?>

Note: Accessing variables of other types using [] or {} silently returns NULL.

Useful functions and operators

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

There are a number of useful functions for string manipulation.

See the string functions section for general functions, and the regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality.

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

Finally, see also the character type functions.

Converting to string

A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo() or print() functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function.

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).

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

Arrays are always converted to the string "Array"; because of this, echo() and print() can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. See below for tips on viewing the entire contents.

Objects in PHP 4 are always converted to the string "Object". To print the values of object properties for debugging reasons, read the paragraphs below. To get an object's class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.

Resources are always converted to strings with the structure "Resource id #1", where 1 is the unique number assigned to the resource by PHP at runtime. Do not rely upon this structure; it is subject to change. To get a resource's type, use the get_resource_type() function.

NULL is always converted to an empty string.

As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types.

Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.

String conversion to numbers

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

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

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

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

To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on:

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

Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.

Floating point numbers
Arrays
Types


Type Juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

<?php
$foo = "0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo = $foo + 1.3;  // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)
?>

If the last two examples above seem odd, see String conversion to numbers.

To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function.

To test any of the examples in this section, use the var_dump() function.

Note: The behaviour of an automatic conversion to array is currently undefined.
Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

<?php
$a    = 'car'; // $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

See the section titled String access by character for more information.

Type Casting

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

<?php
$foo = 10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (binary) - cast to binary string (PHP 6)
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

(binary) casting and b prefix forward support was added in PHP 5.2.1

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

<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>

Casting literal strings and variables to binary strings:

<?php
$binary = (binary) $string;
$binary = b"binary string";
?>

Note: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.

<?php
$foo = 10;            // $foo is an integer
$str = "$foo";        // $str is a string
$fst = (string) $foo; // $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
    echo "they are the same";
}
?>

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

  • Converting to boolean
  • Converting to integer
  • Converting to float
  • Converting to string
  • Converting to array
  • Converting to object
  • Converting to resource
  • Converting to NULL
  • The type comparison tables
Pseudo-types and variables used in this documentation
Variables
Types


Variables

Table of Contents

  • Basics
  • Predefined Variables
  • Variable scope
  • Variable variables
  • Variables From External Sources
Type Juggling
Basics
Language Reference


Basics

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Note: For our purposes here, a letter is a-z, A-Z, and the bytes from 127 through 255 (0x7f-0xff).

Note: $this is a special variable that can't be assigned.

Tip

See also the Userland Naming Guide.

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

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var";      // outputs "Bob, Joe"

$4site = 'not yet';     // invalid; starts with a number
$_4site = 'not yet';    // valid; starts with an underscore
$täyte = 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.
?>

By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

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

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

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

function test()
{
   return 25;
}

$bar = &test();    // Invalid.
?>

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo()) are set as an empty string and arrays become to an empty array.

Example #1 Default values of uninitialized variables

<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump($unset_var);

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true\n" : "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);

// Integer usage; outputs 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);

// Array usage; outputs array(1) {  [3]=>  string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

Variables
Predefined Variables
Variables


Variables From External Sources

HTML Forms (GET and POST)

When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example:

Example #1 A simple HTML form

<form action="foo.php" method="post">
    Name:  <input type="text" name="username" /><br />
    Email: <input type="text" name="email" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:

Example #2 Accessing data from a simple POST HTML form

<?php
// Available since PHP 4.1.0

   echo $_POST['username'];
   echo $_REQUEST['username'];

   import_request_variables('p', 'p_');
   echo $p_username;

// Unavailable since PHP 6. As of PHP 5.0.0, these long predefined
// variables can be disabled with the register_long_arrays directive.

   echo $HTTP_POST_VARS['username'];

// Available if the PHP directive register_globals = on. As of
// PHP 4.2.0 the default value of register_globals = off.
// Using/relying on this method is not preferred.

   echo $username;
?>

Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST and import_request_variables().

Note: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0

Note: Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].

As shown, before PHP 4.2.0 the default value for register_globals was on. The PHP community is encouraging all to not rely on this directive as it's preferred to assume it's off and code accordingly.

Note: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.

PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:

Example #3 More complex form variables

<?php
if ($_POST) {
    echo '<pre>';
    echo htmlspecialchars(print_r($_POST, true));
    echo '</pre>';
}
?>
<form action="" method="post">
    Name:  <input type="text" name="personal[name]" /><br />
    Email: <input type="text" name="personal[email]" /><br />
    Beer: <br />
    <select multiple name="beer[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
    </select><br />
    <input type="submit" value="submit me!" />
</form>

IMAGE SUBMIT variable names

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

<input type="image" src="image.gif" name="sub" />

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.

HTTP Cookies

PHP transparently supports HTTP cookies as defined by » Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header() function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie() manual page for more details and examples.

If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

<?php
  setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
  setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.

Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

Example #4 A setcookie() example

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

Dots in incoming variable names

Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:

<?php
$varname.ext;  /* invalid variable name */
?>

Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.

For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.

Determining variable types

Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.

Variable variables
Constants
Variables


Predefined Variables

PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.

Warning

In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. This is a major change in PHP. Having register_globals off affects the set of predefined variables available in the global scope. For example, to get DOCUMENT_ROOT you'll use $_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from the URL http://www.example.com/test.php?id=3 instead of $id, or $_ENV['HOME'] instead of $HOME.

For related information on this change, read the configuration entry for register_globals, the security chapter on Using Register Globals , as well as the PHP » 4.1.0 and » 4.2.0 Release Announcements.

Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred.

From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global--i.e., automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals.) The superglobals are listed below; however, for a listing of their contents and further discussion on PHP predefined variables and their natures, please see the section Reserved Predefined Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.

Note: Variable variables
Superglobals cannot be used as variable variables inside functions or class methods.

Note: Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not identical, so modifying one will not change the other.

If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.

Basics
Variable scope
Variables


Variable scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:

<?php
$a = 1;
include 'b.inc';
?>

Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

<?php
$a = 1; /* global scope */

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

test();
?>

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

The global keyword

First, an example use of global:

Example #1 Using global

<?php
$a = 1;
$b = 2;

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

    $b = $a + $b;
}

Sum();
echo $b;
?>

The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

Example #2 Using $GLOBALS instead of global

<?php
$a = 1;
$b = 2;

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

Sum();
echo $b;
?>

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:

Example #3 Example demonstrating superglobals and scope

<?php
function test_global()
{
    // Most predefined variables aren't "super" and require
    // 'global' to be available to the functions local scope.
    global $HTTP_POST_VARS;

    echo $HTTP_POST_VARS['name'];

    // Superglobals are available in any scope and do
    // not require 'global'. Superglobals are available
    // as of PHP 4.1.0, and HTTP_POST_VARS is now
    // deemed deprecated.
    echo $_POST['name'];
}
?>

Using static variables

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

Example #4 Example demonstrating need for static variables

<?php
function test()
{
    $a = 0;
    echo $a;
    $a++;
}
?>

This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

Example #5 Example use of static variables

<?php
function test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.

Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:

Example #6 Static variables with recursive functions

<?php
function test()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        test();
    }
    $count--;
}
?>

Note: Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.

Example #7 Declaring static variables

<?php
function foo(){
    static $int = 0;          // correct
    static $int = 1+2;        // wrong  (as it is an expression)
    static $int = sqrt(121);  // wrong  (as it is an expression too)

    $int++;
    echo $int;
}
?>

Note: Static declarations are resolved in compile-time.

References with global and static variables

The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:

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

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

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

The above example will output:

NULL
object(stdClass)(0) {
}

A similar behaviour applies to the static statement. References are not stored statically:

<?php
function &get_instance_ref() {
    static $obj;

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

function &get_instance_noref() {
    static $obj;

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

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

The above example will output:

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}

This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.

Predefined Variables
Variable variables
Variables


Superglobals are built-in variables that are always available in all scopes

Predefined Variables
$GLOBALS
Predefined Variables
PHP Manual

Superglobals

Superglobals — Superglobals are built-in variables that are always available in all scopes

Description

Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods.

These superglobal variables are:

  • $GLOBALS
  • $_SERVER
  • $_GET
  • $_POST
  • $_FILES
  • $_COOKIE
  • $_SESSION
  • $_REQUEST
  • $_ENV

Changelog

Version | Description
4.1.0 | Superglobals were introduced to PHP.

Notes

Note: Variable availability
By default, all of the superglobals are available but there are directives that affect this availability. For further information, refer to the documentation for variables_order.

Note: Dealing with register_globals
If the deprecated register_globals directive is set to on then the variables within will also be made available in the global scope of the script. For example, $_POST['foo'] would also exist as $foo.
For related information, see the FAQ titled "How does register_globals affect me?"

Note: Variable variables
Superglobals cannot be used as variable variables inside functions or class methods.

See Also

  • variable scope
  • The variables_order directive
  • The filter extension

Predefined Variables
$GLOBALS
Predefined Variables


Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

<?php
$a = 'hello';
?>

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

<?php
$$a = 'world';
?>

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

<?php
echo "$a ${$a}";
?>

produces the exact same output as:

<?php
echo "$a $hello";
?>

i.e. they both produce: hello world.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

Example #1 Variable function example

<?php
class foo {
    var $bar = 'I am bar.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo $foo->$bar . "\n";
echo $foo->$baz[1] . "\n";
?>

The above example will output:

I am bar.
I am bar.

Warning

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

Variable scope
Variables From External Sources
Variables


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

EV_TIMEOUT (integer)
EV_READ (integer)
EV_WRITE (integer)
EV_SIGNAL (integer)
EV_PERSIST (integer)
EVLOOP_NONBLOCK (integer)
EVLOOP_ONCE (integer)
Resource Types
Examples
Libevent


Examples

Example #1 polling STDIN using basic API

<?php

function print_line($fd, $events, $arg)
{
    static $max_requests = 0;

    $max_requests++;

    if ($max_requests == 10) {
        // exit loop after 10 writes
        event_base_loopexit($arg[1]);
    }

    // print the line
    echo  fgets($fd);
}

// create base and event
$base = event_base_new();
$event = event_new();

$fd = STDIN;

// set event flags
event_set($event, $fd, EV_READ | EV_PERSIST, "print_line", array($event, $base));
// set event base
event_base_set($event, $base);

// enable event
event_add($event);
// start event loop
event_base_loop($base);

?>

Example #2 polling STDIN using buffered event API

<?php

function print_line($buf, $arg)
{
    static $max_requests;

    $max_requests++;

    if ($max_requests == 10) {
        event_base_loopexit($arg);
    }

    // print the line
    echo event_buffer_read($buf, 4096);
}

function error_func($buf, $what, $arg)
{
    // handle errors
}

$base = event_base_new();
$eb = event_buffer_new(STDIN, "print_line", NULL, "error_func", $base);

event_buffer_base_set($eb, $base);
event_buffer_enable($eb, EV_READ);

event_base_loop($base);

?>

Predefined Constants
Libevent Functions
Libevent


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/libevent.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

This extension requires » libevent library. Minimal required version is 1.4.0.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

There are several resource types used in the extension. These resources are event, event base and buffered event.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Libevent


Tries to find out best available locale based on HTTP "Accept-Language" header

Locale
Locale::composeLocale
Locale
PHP Manual

Locale::acceptFromHttp

locale_accept_from_http

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::acceptFromHttp -- locale_accept_from_http — Tries to find out best available locale based on HTTP "Accept-Language" header

Description

Object oriented style

static string Locale::acceptFromHttp ( string $header )

Procedural style

string locale_accept_from_http ( string $header )

Tries to find locale that can satisfy the language list that is requested by the HTTP "Accept-Language" header.

Parameters

header

The string containing the "Accept-Language" header according to format in RFC 2616.

Return Values

The corresponding locale identifier.

Examples

Example #1 locale_accept_from_http() example

<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>

Example #2 OO example

<?php
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>

The above example will output:

en_US

See Also

  • locale_lookup() - Searches the language tag list for the best match to the language

Locale
Locale::composeLocale
Locale


Returns a correctly ordered and delimited locale ID

Locale::acceptFromHttp
Locale::filterMatches
Locale
PHP Manual

Locale::composeLocale

locale_compose

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::composeLocale -- locale_compose — Returns a correctly ordered and delimited locale ID

Description

Object oriented style

static string Locale::composeLocale ( array $subtags )

Procedural style

string locale_compose ( array $subtags )

Returns a correctly ordered and delimited locale ID the keys identify the particular locale ID subtags, and the values are the associated subtag values.

Parameters

subtags

an array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values.

Note: The 'variant' and 'private' subtags can take maximum 15 values whereas 'extlang' can take maximum 3 values.e.g. Variants are allowed with the suffix ranging from 0-14. Hence the keys for the input array can be variant0, variant1, ...,variant14. In the returned locale id, the subtag is ordered by suffix resulting in variant0 followed by variant1 followed by variant2 and so on.
The 'variant', 'private' and 'extlang' multiple values can be specified both as array under specific key (e.g. 'variant') and as multiple numbered keys (e.g. 'variant0', 'variant1', etc.).

Return Values

The corresponding locale identifier.

Examples

Example #1 locale_compose() example

<?php
$arr = array(
    'language'=>'en' ,
    'script'  =>'Hans' ,
    'region'  =>'CN',
    'variant2'=>'rozaj' ,
    'variant1'=>'nedis' ,
    'private1'=>'prv1' ,
    'private2'=>'prv2'
);
echo locale_compose( $arr );
?>

Example #2 OO example

<?php
$arr = array(
    'language'=>'en' ,
    'script'  =>'Hans' ,
    'region'  =>'CN',
    'variant2'=>'rozaj' ,
    'variant1'=>'nedis' ,
    'private1'=>'prv1' ,
    'private2'=>'prv2'
);
echo Locale::composeLocale( $arr );
?>

The above example will output:

Locale: en_Hans_CN_nedis_rozaj_x_prv1_prv2

See Also

  • locale_parse() - Returns a key-value array of locale ID subtag elements.

Locale::acceptFromHttp
Locale::filterMatches
Locale


Checks if a language tag filter matches with locale

Locale::composeLocale
Locale::getAllVariants
Locale
PHP Manual

Locale::filterMatches

locale_filter_matches

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::filterMatches -- locale_filter_matches — Checks if a language tag filter matches with locale

Description

Object oriented style

static bool Locale::filterMatches ( string $langtag , string $locale [, bool $canonicalize = false ] )

Procedural style

bool locale_filter_matches ( string $langtag , string $locale [, bool $canonicalize = false ] )

Checks if a $langtag filter matches with $locale according to RFC 4647's basic filtering algorithm

Parameters

langtag

The language tag to check

locale

The language range to check against

canonicalize

If true, the arguments will be converted to canonical form before matching.

Return Values

TRUE if $locale matches $langtag FALSE otherwise.

Examples

Example #1 locale_filter_matches() example

<?php
echo (locale_filter_matches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match";
echo '; ';
echo (locale_filter_matches('de-DE_1996','de-DE', false)) ? "Matches" : "Does not match";
?>

Example #2 OO example

<?php
echo (Locale::filterMatches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match";
echo '; ';
echo (Locale::filterMatches('de-DE-1996','de-DE', false)) ? "Matches" : "Does not match";
?>

The above example will output:

Does not match; Matches

See Also

  • locale_lookup() - Searches the language tag list for the best match to the language

Locale::composeLocale
Locale::getAllVariants
Locale


Gets the variants for the input locale

Locale::filterMatches
Locale::getDefault
Locale
PHP Manual

Locale::getAllVariants

locale_get_all_variants

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getAllVariants -- locale_get_all_variants — Gets the variants for the input locale

Description

Object oriented style

static array Locale::getAllVariants ( string $locale )

Procedural style

array locale_get_all_variants ( string $locale )

Gets the variants for the input locale

Parameters

locale

The locale to extract the variants from

Return Values

The array containing the list of all variants subtag for the locale or NULL if not present

Examples

Example #1 locale_get_all_variants() example

<?php
$arr = locale_get_all_variants('sl_IT_NEDIS_ROJAZ_1901');
var_export( $arr );
?>

Example #2 OO example

<?php
 $arr = Locale::getAllVariants('sl_IT_NEDIS_ROJAZ_1901');
 var_export( $arr );
?>

The above example will output:

array (
    0 => 'NEDIS',
    1 => 'ROJAZ',
    2 => '1901',
)

See Also

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_script() - Gets the script for the input locale
  • locale_get_region() - Gets the region for the input locale

Locale::filterMatches
Locale::getDefault
Locale


Gets the default locale value from the INTL global 'default_locale'

Locale::getAllVariants
Locale::getDisplayLanguage
Locale
PHP Manual

Locale::getDefault

locale_get_default

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDefault -- locale_get_default — Gets the default locale value from the INTL global 'default_locale'

Description

Object oriented style

static string Locale::getDefault ( void )

Procedural style

string locale_get_default ( void )

Gets the default locale value. At the PHP initialization this value is set to 'intl.default_locale' value from php.ini if that value exists or from ICU's function uloc_getDefault().

Parameters

Return Values

The current runtime locale

Examples

Example #1 locale_get_default() example

<?php
ini_set('intl.default_locale', 'de-DE');
echo locale_get_default();
echo '; ';
locale_set_default('fr');
echo locale_get_default();
?>

Example #2 OO example

<?php
ini_set('intl.default_locale', 'de-DE');
echo Locale::getDefault();
echo '; ';
Locale::setDefault('fr');
echo Locale::getDefault();
?>

The above example will output:

de-DE; fr

See Also

  • locale_set_default() - sets the default runtime locale

Locale::getAllVariants
Locale::getDisplayLanguage
Locale


Returns an appropriately localized display name for language of the inputlocale

Locale::getDefault
Locale::getDisplayName
Locale
PHP Manual

Locale::getDisplayLanguage

locale_get_display_language

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayLanguage -- locale_get_display_language — Returns an appropriately localized display name for language of the inputlocale

Description

Object oriented style

static string Locale::getDisplayLanguage ( string $locale [, string $in_locale ] )

Procedural style

string locale_get_display_language ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for language of the input locale. If is NULL then the default locale is used.

Parameters

locale

The locale to return a display language for

in_locale

Optional format locale to use to display the language name

Return Values

display name of the language for the $locale in the format appropriate for $in_locale.

Examples

Example #1 locale_get_display_language() example

<?php
echo locale_get_display_language('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'de');
?>

The above example will output:

Slovenian;
slov\xc3\xa8ne;
Slowenisch

See Also

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

Locale::getDefault
Locale::getDisplayName
Locale


Returns an appropriately localized display name for the input locale

Locale::getDisplayLanguage
Locale::getDisplayRegion
Locale
PHP Manual

Locale::getDisplayName

locale_get_display_name

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayName -- locale_get_display_name — Returns an appropriately localized display name for the input locale

Description

Object oriented style

static string Locale::getDisplayName ( string $locale [, string $in_locale ] )

Procedural style

string locale_get_display_name ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for the input locale. If is NULL then the default locale is used.

Parameters

locale

The locale to return a display name for.

in_locale

optional format locale

Return Values

Display name of the locale in the format appropriate for $in_locale.

Examples

Example #1 locale_get_display_name() example

<?php
echo locale_get_display_name('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_name('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_name('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'de');
?>

The above example will output:

Slovenian (Latin, Italy, Natisone dialect);
slov\xc3\xa8ne (latin, Italie, dialecte de Natisone;
Slowenisch (Lateinisch, Italien, NEDIS)

See Also

  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayLanguage
Locale::getDisplayRegion
Locale


Returns an appropriately localized display name for region of the input locale

Locale::getDisplayName
Locale::getDisplayScript
Locale
PHP Manual

Locale::getDisplayRegion

locale_get_display_region

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayRegion -- locale_get_display_region — Returns an appropriately localized display name for region of the input locale

Description

Object oriented style

static string Locale::getDisplayRegion ( string $locale [, string $in_locale ] )

Procedural style

string locale_get_display_region ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for region of the input locale. If is NULL then the default locale is used.

Parameters

locale

The locale to return a display region for.

in_locale

Optional format locale to use to display the region name

Return Values

display name of the region for the $locale in the format appropriate for $in_locale.

Examples

Example #1 locale_get_display_region() example

<?php
echo locale_get_display_region('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_region('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_region('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'de');
?>

The above example will output:

Italy;
Italie;
Italien

See Also

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayName
Locale::getDisplayScript
Locale


Returns an appropriately localized display name for script of the input locale

Locale::getDisplayRegion
Locale::getDisplayVariant
Locale
PHP Manual

Locale::getDisplayScript

locale_get_display_script

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayScript -- locale_get_display_script — Returns an appropriately localized display name for script of the input locale

Description

Object oriented style

static string Locale::getDisplayScript ( string $locale [, string $in_locale ] )

Procedural style

string locale_get_display_script ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for script of the input locale. If is NULL then the default locale is used.

Parameters

locale

The locale to return a display script for

in_locale

Optional format locale to use to display the script name

Return Values

Display name of the script for the $locale in the format appropriate for $in_locale.

Examples

Example #1 locale_get_display_script() example

<?php
echo locale_get_display_script('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_script('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_script('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'de');
?>

The above example will output:

Latin;
latin;
Lateinisch

See Also

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayRegion
Locale::getDisplayVariant
Locale


Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayScript
Locale::getKeywords
Locale
PHP Manual

Locale::getDisplayVariant

locale_get_display_variant

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayVariant -- locale_get_display_variant — Returns an appropriately localized display name for variants of the input locale

Description

Object oriented style

static string Locale::getDisplayVariant ( string $locale [, string $in_locale ] )

Procedural style

string locale_get_display_variant ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for variants of the input locale. If is NULL then the default locale is used.

Parameters

locale

The locale to return a display variant for

in_locale

Optional format locale to use to display the variant name

Return Values

Display name of the variant for the $locale in the format appropriate for $in_locale.

Examples

Example #1 locale_get_display_variant() example

<?php
echo locale_get_display_variant('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_variant('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_variant('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'de');
?>

The above example will output:

Natisone dialect;
dialecte de Natisone;
NEDIS

See Also

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale

Locale::getDisplayScript
Locale::getKeywords
Locale


Gets the keywords for the input locale

Locale::getDisplayVariant
Locale::getPrimaryLanguage
Locale
PHP Manual

Locale::getKeywords

locale_get_keywords

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getKeywords -- locale_get_keywords — Gets the keywords for the input locale

Description

Object oriented style

static array Locale::getKeywords ( string $locale )

Procedural style

array locale_get_keywords ( string $locale )

Gets the keywords for the input locale.

Parameters

locale

The locale to extract the keywords from

Return Values

Associative array containing the keyword-value pairs for this locale

Examples

Example #1 locale_get_keywords() example

<?php
$keywords_arr = locale_get_keywords( 'de_DE@currency=EUR;collation=PHONEBOOK' );
if ($keywords_arr) {
    foreach ($keywords_arr as $key => $value) {
        echo "$key = $value\n";
    }
}
?>

Example #2 OO example

<?php
$keywords_arr = Locale::getKeywords( 'de_DE@currency=EUR;collation=PHONEBOOK' );
if ($keywords_arr) {
    foreach( $keywords_arr as $key => $value){
        echo "$key = $value\n";
    }
}
?>

The above example will output:

collation = PHONEBOOK
currency = EUR

See Also

  • locale_get_all_variants() - Gets the variants for the input locale

Locale::getDisplayVariant
Locale::getPrimaryLanguage
Locale


Gets the primary language for the input locale

Locale::getKeywords
Locale::getRegion
Locale
PHP Manual

Locale::getPrimaryLanguage

locale_get_primary_language

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getPrimaryLanguage -- locale_get_primary_language — Gets the primary language for the input locale

Description

Object oriented style

static string Locale::getPrimaryLanguage ( string $locale )

Procedural style

string locale_get_primary_language ( string $locale )

Gets the primary language for the input locale

Parameters

locale

The locale to extract the primary language code from

Return Values

The language code associated with the language or NULL in case of error.

Examples

Example #1 locale_get_primary_language() example

<?php
echo locale_get_primary_language('zh-Hant');
?>

Example #2 OO example

<?php
echo Locale::getPrimaryLanguage('zh-Hant');
?>

The above example will output:

zh

See Also

  • locale_get_script() - Gets the script for the input locale
  • locale_get_region() - Gets the region for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

Locale::getKeywords
Locale::getRegion
Locale


Gets the region for the input locale

Locale::getPrimaryLanguage
Locale::getScript
Locale
PHP Manual

Locale::getRegion

locale_get_region

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getRegion -- locale_get_region — Gets the region for the input locale

Description

Object oriented style

static string Locale::getRegion ( string $locale )

Procedural style

string locale_get_region ( string $locale )

Gets the region for the input locale.

Parameters

locale

The locale to extract the region code from

Return Values

The region subtag for the locale or NULL if not present

Examples

Example #1 locale_get_region() example

<?php
echo locale_get_region('de-CH-1901');
?>

Example #2 OO example

<?php
echo Locale::getRegion('de-CH-1901');
?>

The above example will output:

CH

See Also

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_script() - Gets the script for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

Locale::getPrimaryLanguage
Locale::getScript
Locale


Gets the script for the input locale

Locale::getRegion
Locale::lookup
Locale
PHP Manual

Locale::getScript

locale_get_script

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getScript -- locale_get_script — Gets the script for the input locale

Description

Object oriented style

static string Locale::getScript ( string $locale )

Procedural style

string locale_get_script ( string $locale )

Gets the script for the input locale.

Parameters

locale

The locale to extract the script code from

Return Values

The script subtag for the locale or NULL if not present

Examples

Example #1 locale_get_script() example

<?php
echo locale_get_script('sr-Cyrl');
?>

Example #2 OO example

<?php
echo Locale::getScript('sr-Cyrl');
?>

The above example will output:

Cyrl

See Also

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_region() - Gets the region for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

Locale::getRegion
Locale::lookup
Locale


Searches the language tag list for the best match to the language

Locale::getScript
Locale::parseLocale
Locale
PHP Manual

Locale::lookup

locale_lookup

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::lookup -- locale_lookup — Searches the language tag list for the best match to the language

Description

Object oriented style

static string Locale::lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )

Procedural style

string locale_lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )

Searches the items in langtag for the best match to the language range specified in locale according to RFC 4647's lookup algorithm.

Parameters

langtag

An array containing a list of language tags to compare to locale . Maximum 100 items allowed.

locale

The locale to use as the language range when matching.

canonicalize

If true, the arguments will be converted to canonical form before matching.

default

The locale to use if no match is found.

Return Values

The closest matching language tag or default value.

Examples

Example #1 locale_lookup() example

<?php
$arr = array(
    'de-DEVA',
    'de-DE-1996',
    'de',
    'de-De'
);
echo locale_lookup($arr, 'de-DE-1996-x-prv1-prv2', 'en_US');
?>

Example #2 OO example

<?php
$arr = array(
    'de-DEVA',
    'de-DE-1996',
    'de',
    'de-De'
);
echo Locale::lookup($arr, 'de-DE-1996-x-prv1-prv2', 'en_US');
?>

The above example will output:

de_de_1996

See Also

  • locale_filter_matches() - Checks if a language tag filter matches with locale

Locale::getScript
Locale::parseLocale
Locale


Returns a key-value array of locale ID subtag elements.

Locale::lookup
Locale::setDefault
Locale
PHP Manual

Locale::parseLocale

locale_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::parseLocale -- locale_parse — Returns a key-value array of locale ID subtag elements.

Description

Object oriented style

static array Locale::parseLocale ( string $locale )

Procedural style

array locale_parse ( string $locale )

Returns a key-value array of locale ID subtag elements.

Parameters

locale

The locale to extract the subtag array from. Note: The 'variant' and 'private' subtags can take maximum 15 values whereas 'extlang' can take maximum 3 values.

Return Values

Returns an array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values. The array will be ordered as the locale id subtags e.g. in the locale id if variants are '-varX-varY-varZ' then the returned array will have variant0=>varX , variant1=>varY , variant2=>varZ

Examples

Example #1 locale_parse() example

<?php
$arr = locale_parse('sl-Latn-IT-nedis');
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}
?>

Example #2 OO example

<?php
$arr = Locale::parseLocale('sl-Latn-IT-nedis');
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}
?>

The above example will output:

language : sl , script : Latn , region : IT , variant0 : NEDIS ,

See Also

  • locale_compose() - Returns a correctly ordered and delimited locale ID

Locale::lookup
Locale::setDefault
Locale


sets the default runtime locale

Locale::parseLocale
Normalizer
Locale
PHP Manual

Locale::setDefault

locale_set_default

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::setDefault -- locale_set_default — sets the default runtime locale

Description

Object oriented style

static bool Locale::setDefault ( string $locale )

Procedural style

bool locale_set_default ( string $locale )

Sets the default runtime locale to $locale. This changes the value of INTL global 'default_locale' locale identifier. UAX #35 extensions are accepted.

Parameters

locale

Is a BCP 47 compliant language tag containing the

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 locale_set_default() example

<?php
locale_set_default('de-DE');
echo locale_get_default();
?>

Example #2 OO example

<?php
Locale::setDefault('de-DE');
echo Locale::getDefault();
?>

The above example will output:

de-DE

See Also

  • locale_get_default() - Gets the default locale value from the INTL global 'default_locale'

Locale::parseLocale
Normalizer
Locale


Predefined Constants

This extension has no constants defined.

Resource Types
LZF Functions
LZF


Installation

This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/lzf.

In order to use these functions you must compile PHP with lzf support by using the --with-lzf[=DIR] configure option. You may also pass --enable-lzf-better-compression to optimize LZF for space rather then speed.

Windows users will enable php_lzf.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
LZF


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mail configuration options
Name | Default | Changeable | Changelog
mail.add_x_header | "0" | PHP_INI_SYSTEM|PHP_INI_PERDIR | Available since PHP 5.3.0.
mail.log | NULL | PHP_INI_SYSTEM|PHP_INI_PERDIR | Available since PHP 5.3.0.
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL | Available since PHP 4.3.0.
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | PHP_INI_SYSTEM |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mail.add_x_header bool

Add X-PHP-Originating-Script that will include UID of the script followed by the filename.

mail.log string

Log all mail() calls including the full path of the script, line number, To address and headers.

SMTP string

Used under Windows only: host name or IP address of the SMTP server PHP should use for mail sent with the mail() function.

smtp_port int

Used under Windows only: Number of the port to connect to the server specified with the SMTP setting when sending mail with mail(); defaults to 25. Only available since PHP 4.3.0.

sendmail_from string

Which "From:" mail address should be used in mail sent from PHP under Windows. This directive also sets the "Return-Path:" header.

sendmail_path string

Where the sendmail program can be found, usually /usr/sbin/sendmail or /usr/lib/sendmail. configure does an honest attempt of locating this one for you and set a default, but if it fails, you can set it here.

Systems not using sendmail should set this directive to the sendmail wrapper/replacement their mail system offers, if any. For example, » Qmail users can normally set it to /var/qmail/bin/sendmail or /var/qmail/bin/qmail-inject.

qmail-inject does not require any option to process mail correctly.

This directive works also under Windows. If set, smtp, smtp_port and sendmail_from are ignored and the specified command is executed.

Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

Resource Types
Mail Functions
Mail


Requirements

For the Mail functions to be available, PHP must have access to the sendmail binary on your system during compile time. If you use another mail program, such as qmail or postfix, be sure to use the appropriate sendmail wrappers that come with them. PHP will first look for sendmail in your PATH, and then in the following: /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib. It's highly recommended to have sendmail available from your PATH. Also, the user that compiled PHP must have permission to access the sendmail binary.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Mail


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mailparse configuration options
Name | Default | Changeable | Changelog
mailparse.def_charset | "us-ascii" | PHP_INI_ALL | Available since PHP 4.1.0. Removed in PHP 4.2.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

MAILPARSE_EXTRACT_OUTPUT (integer)
MAILPARSE_EXTRACT_STREAM (integer)
MAILPARSE_EXTRACT_RETURN (integer)
Resource Types
Mailparse Functions
Mailparse


Installation

This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/mailparse.

In order to use these functions you must compile PHP with mailparse support by using the --enable-mailparse configure option.

Windows users will enable php_mailparse.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Mailparse


PHP Manual
PHP Manual

PHP Manual

  • Preface
Copyright
Preface
PHP Manual
PHP Manual


Predefined Constants

The constants below are always available as part of the PHP core.

Math constants
Constant | Value | Description | Availability
M_PI | 3.14159265358979323846 | Pi |
M_E | 2.7182818284590452354 | e |
M_LOG2E | 1.4426950408889634074 | log_2 e |
M_LOG10E | 0.43429448190325182765 | log_10 e |
M_LN2 | 0.69314718055994530942 | log_e 2 |
M_LN10 | 2.30258509299404568402 | log_e 10 |
M_PI_2 | 1.57079632679489661923 | pi/2 |
M_PI_4 | 0.78539816339744830962 | pi/4 |
M_1_PI | 0.31830988618379067154 | 1/pi |
M_2_PI | 0.63661977236758134308 | 2/pi |
M_SQRTPI | 1.77245385090551602729 | sqrt(pi) | PHP 5.2.0
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi) |
M_SQRT2 | 1.41421356237309504880 | sqrt(2) |
M_SQRT3 | 1.73205080756887729352 | sqrt(3) | PHP 5.2.0
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) |
M_LNPI | 1.14472988584940017414 | log_e(pi) | PHP 5.2.0
M_EULER | 0.57721566490153286061 | Euler constant | PHP 5.2.0
PHP_ROUND_HALF_UP | 1 | Round halves up | PHP 5.3.0
PHP_ROUND_HALF_DOWN | 2 | Round halves down | PHP 5.3.0
PHP_ROUND_HALF_EVEN | 3 | Round halves to even numbers | PHP 5.3.0
PHP_ROUND_HALF_ODD | 4 | Round halves to odd numbers | PHP 5.3.0
NAN | NAN (as a float) | Not A Number |
INF | INF (as a float) | The infinite |

All constants without a labeled PHP version above are available starting with PHP 4.0.0.

Resource Types
Math Functions
Math


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Math


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MaxDB Configuration Options
Name | Default | Changeable | Changelog
maxdb.default_host | NULL | PHP_INI_ALL |
maxdb.default_db | NULL | PHP_INI_ALL |
maxdb.default_user | NULL | PHP_INI_ALL |
maxdb.default_pw | NULL | PHP_INI_ALL |
maxdb.long_readlen | "200" | PHP_INI_ALL |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

maxdb.default_host string

The default server host to use when connecting to the database server if no other host is specified.

maxdb.default_db string

The default server database to use when connecting if no other database is specified.

maxdb.default_user string

The default user name to use when connecting to the database server if no other name is specified.

maxdb.default_pw string

The default password to use when connecting to the database server if no other password is specified.

maxdb.long_readlen integer

The default maximum length of bytes that is transferred to the client if long data is retrieved from the MaxDB database server.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The following constants to use with maxdb_options() are defined. For further description of these constants see » http://maxdb.sap.com/documentation/.

MaxDB PHP client constants
Constant | Description
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment.
MAXDB_APPLICATION | The application to be connected to the database.
MAXDB_APPVERSION | The version of the application.
MAXDB_SQLMODE | The SQL mode.
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not.
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system.
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released.
MAXDB_PACKETCOUNT | The number of different request packets used for the connection.
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use.
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named.

The function maxdb_fetch_array() uses a constant for the different types of result arrays. The following constants are defined:

MaxDB fetch constants
Constant | Description
MAXDB_ASSOC | Columns are returned into the array having the fieldname as the array index.
MAXDB_ASSOC_UPPER | Columns are returned into the array having the upper case fieldname as the array index.
MAXDB_ASSOC_LOWER | Columns are returned into the array having the lower case fieldname as the array index.
MAXDB_BOTH | Columns are returned into the array having both a numerical index and the fieldname as the array index.
MAXDB_NUM | Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

Resource Types
Examples
MaxDB


Examples

Table of Contents

  • MaxDB extension overview example
Predefined Constants
MaxDB extension overview example
MaxDB


MaxDB extension overview example

Examples
MaxDB Functions
Examples
PHP Manual

All examples in the MaxDB PHP documentation use the HOTELDB demo database from MaxDB. More about this database can be found at » http://maxdb.sap.com/doc/7_7/44/d8c25164bb38d0e10000000a1553f7/content.htm.

To use the examples in the MaxDB PHP documentation, you have to load the tutorial data into your database. Then you have to set maxdb.default_db in php.ini to the database that contains the tutorial data.

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MaxDB database.

Example #1 MaxDB extension overview example

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$query = "SELECT * FROM hotel.city";
$result = maxdb_query($link, $query) or die("Query failed : " . maxdb_error());

/* Printing results in HTML */
echo "<table>\n";
while ($line = maxdb_fetch_array($result, MAXDB_ASSOC)) {
    echo "  <tr>\n";
    foreach ($line as $col_value) {
        echo "    <td>$col_value</td>\n";
    }
    echo "  </tr>\n";
}
echo "</table>\n";

/* Free resultset */
maxdb_free_result($result);

/* Closing connection */
maxdb_close($link);
?>

The following example shows how to bind variables to a SELECT INTO statement.

Example #2 Example for use of SELECT INTO statements

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "SELECT percentage INTO ? FROM hotel.countrylanguage where language = ?");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

$name = "Mbundu";

maxdb_stmt_bind_param($stmt, 'ds', $percentage, $name);
maxdb_stmt_execute($stmt);

printf ("%f\n", $percentage);

maxdb_stmt_close ($stmt);
?>

The following example shows how to use MaxDB database procedures.

Example #3 Example fore using database procedures

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP DBPROC test_proc");
maxdb_report (MAXDB_REPORT_ERROR);

$query = "create dbproc test_proc (INOUT e_text char(72)) AS select * from SYSDBA.DUAL; fetch into :e_text;";

maxdb_query($link, $query);

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "CALL test_proc (?)");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

maxdb_stmt_bind_param($stmt, 's', $result);
maxdb_stmt_execute($stmt);

printf ("%s\n", $result);

maxdb_stmt_close ($stmt);
?>

Examples
MaxDB Functions
Examples


Installation

By using the --with-maxdb[=DIR] configuration option you enable PHP to access MaxDB databases. [DIR] points to the directory that contains the installed MaxDB SQLDBC package.

Windows users will need to enable php_maxdb.dll inside of php.ini.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

In order to have these functions available, you must compile PHP with MaxDB support. Additionally, you must have the MaxDB SQLDBC runtime library available to access the MaxDB server.

Documentation for MaxDB SQLDBC can be found at » http://maxdb.sap.com/documentation/.

Download the MaxDB SQLDBC package from » http://www.sdn.sap.com/irj/sdn/maxdb-downloads.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension defines resources.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
MaxDB


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

mbstring configuration options
Name | Default | Changeable | Changelog
mbstring.language | "neutral" | PHP_INI_PERDIR | Available since PHP 4.3.0.
mbstring.detect_order | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.http_input | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.http_output | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.script_encoding | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
mbstring.substitute_character | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in PHP <= 4.2.3; PHP_INI_SYSTEM | PHP_INI_PERDIR from PHP 4.3 through 5.2.6. Available since PHP 4.2.0.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Available since PHP 4.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | Available since PHP 5.1.2.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mbstring.language string

The default national language setting (NLS) used in mbstring. Note that this option automagically defines mbstring.internal_encoding and mbstring.internal_encoding should be placed after mbstring.language in php.ini

mbstring.encoding_translation boolean

Enables the transparent character encoding filter for the incoming HTTP queries, which performs detection and conversion of the input encoding to the internal character encoding.

mbstring.internal_encoding string

Defines the default internal character encoding.

mbstring.http_input string

Defines the default HTTP input character encoding.

mbstring.http_output string

Defines the default HTTP output character encoding.

mbstring.detect_order string

Defines default character code detection order. See also mb_detect_order().

mbstring.substitute_character string

Defines character to substitute for invalid character encoding.

mbstring.func_overload string

Overloads a set of single byte functions by the mbstring counterparts. See Function overloading for more information.

mbstring.strict_detection boolean

Enables the strict encoding detection.

According to the » HTML 4.01 specification, Web browsers are allowed to encode a form being submitted with a character encoding different from the one used for the page. See mb_http_input() to detect character encoding used by browsers.

Although popular browsers are capable of giving a reasonably accurate guess to the character encoding of a given HTML document, it would be better to set the charset parameter in the Content-Type HTTP header to the appropriate value by header() or default_charset ini setting.

Example #1 php.ini setting examples

; Set default language
mbstring.language        = Neutral; Set default language to Neutral(UTF-8) (default)
mbstring.language        = English; Set default language to English
mbstring.language        = Japanese; Set default language to Japanese

;; Set default internal encoding
;; Note: Make sure to use character encoding works with PHP
mbstring.internal_encoding    = UTF-8  ; Set internal encoding to UTF-8

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set default HTTP input character encoding
;; Note: Script cannot change http_input setting.
mbstring.http_input           = pass    ; No conversion.
mbstring.http_input           = auto    ; Set HTTP input to auto
                                ; "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS"
mbstring.http_input           = SJIS    ; Set HTTP2 input to  SJIS
mbstring.http_input           = UTF-8,SJIS,EUC-JP ; Specify order

;; Set default HTTP output character encoding
mbstring.http_output          = pass    ; No conversion
mbstring.http_output          = UTF-8   ; Set HTTP output encoding to UTF-8

;; Set default character encoding detection order
mbstring.detect_order         = auto    ; Set detect order to auto
mbstring.detect_order         = ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specify order

;; Set default substitute character
mbstring.substitute_character = 12307   ; Specify Unicode value
mbstring.substitute_character = none    ; Do not print character
mbstring.substitute_character = long    ; Long Example: U+3000,JIS+7E7E

Example #2 php.ini setting for EUC-JP users

;; Disable Output Buffering
output_buffering      = Off

;; Set HTTP header charset
default_charset       = EUC-JP

;; Set default language to Japanese
mbstring.language = Japanese

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set HTTP input encoding conversion to auto
mbstring.http_input   = auto

;; Convert HTTP output to EUC-JP
mbstring.http_output  = EUC-JP

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP

;; Do not print invalid characters
mbstring.substitute_character = none

Example #3 php.ini setting for SJIS users

;; Enable Output Buffering
output_buffering     = On

;; Set mb_output_handler to enable output conversion
output_handler       = mb_output_handler

;; Set HTTP header charset
default_charset      = Shift_JIS

;; Set default language to Japanese
mbstring.language = Japanese

;; Set http input encoding conversion to auto
mbstring.http_input  = auto

;; Convert to SJIS
mbstring.http_output = SJIS

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP

;; Do not print invalid characters
mbstring.substitute_character = none

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

MB_OVERLOAD_MAIL (integer)
MB_OVERLOAD_STRING (integer)
MB_OVERLOAD_REGEX (integer)
MB_CASE_UPPER (integer)
MB_CASE_LOWER (integer)
MB_CASE_TITLE (integer)
Resource Types
Summaries of supported encodings
Multibyte String


Summaries of supported encodings

Summaries of supported encodings
Name in the IANA character set registry:ISO-10646-UCS-4
Underlying character set:ISO 10646
Description: The Universal Character Set with 31-bit code space, standardized as UCS-4 by ISO/IEC 10646. It is kept synchronized with the latest version of the Unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:ISO-10646-UCS-4
Underlying character set:UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in big endian form.
Name in the IANA character set registry:ISO-10646-UCS-4
Underlying character set:UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in little endian form.
Name in the IANA character set registry:ISO-10646-UCS-2
Underlying character set:UCS-2
Description: The Universal Character Set with 16-bit code space, standardized as UCS-2 by ISO/IEC 10646. It is kept synchronized with the latest version of the unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:ISO-10646-UCS-2
Underlying character set:UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in big endian form.
Name in the IANA character set registry:ISO-10646-UCS-2
Underlying character set:UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in little endian form.
Name in the IANA character set registry:UTF-32
Underlying character set:Unicode
Description: Unicode Transformation Format of 32-bit unit width, whose encoding space refers to the Unicode's codeset standard. This encoding scheme wasn't identical to UCS-4 because the code space of Unicode were limited to a 21-bit value.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:UTF-32BE
Underlying character set:Unicode
Description:See above
Additional note: In contrast to UTF-32, strings are always assumed to be in big endian form.
Name in the IANA character set registry:UTF-32LE
Underlying character set:Unicode
Description:See above
Additional note: In contrast to UTF-32, strings are always assumed to be in little endian form.
Name in the IANA character set registry:UTF-16
Underlying character set:Unicode
Description: Unicode Transformation Format of 16-bit unit width. It's worth a note that UTF-16 is no longer the same specification as UCS-2 because the surrogate mechanism has been introduced since Unicode 2.0 and UTF-16 now refers to a 21-bit code space.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:UTF-16BE
Underlying character set:Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in big endian form.
Name in the IANA character set registry:UTF-16LE
Underlying character set:Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in little endian form.
Name in the IANA character set registry:UTF-8
Underlying character set:Unicode / UCS
Description: Unicode Transformation Format of 8-bit unit width.
Additional note:none
Name in the IANA character set registry:UTF-7
Underlying character set:Unicode
Description: A mail-safe transformation format of Unicode, specified in » RFC2152.
Additional note:none
Name in the IANA character set registry:(none)
Underlying character set:Unicode
Description: A variant of UTF-7 which is specialized for use in the » IMAP protocol.
Additional note:none
Name in the IANA character set registry: US-ASCII (preferred MIME name) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII
Underlying character set:ASCII / ISO 646
Description: American Standard Code for Information Interchange is a commonly-used 7-bit encoding. Also standardized as an international standard, ISO 646.
Additional note:(none)
Name in the IANA character set registry: EUC-JP (preferred MIME name) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese
Underlying character set: Compound of US-ASCII / JIS X0201:1997 (hankaku kana part) / JIS X0208:1990 / JIS X0212:1990
Description: As you see the name is derived from an abbreviation of Extended UNIX Code Packed Format for Japanese, this encoding is mostly used on UNIX or alike platforms. The original encoding scheme, Extended UNIX Code, is designed on the basis of ISO 2022.
Additional note: The character set referred to by EUC-JP is different to IBM932 / CP932, which are used by OS/2® and Microsoft® Windows®. For information interchange with those platforms, use EUCJP-WIN instead.
Name in the IANA character set registry:Shift_JIS (preferred MIME name) / MS_Kanji / csShift_JIS
Underlying character set:Compound of JIS X0201:1997 / JIS X0208:1997
Description: Shift_JIS was developed in early 80's, at the time personal Japanese word processors were brought into the market, in order to maintain compatiblities with the legacy encoding scheme JIS X 0201:1976. According to the IANA definition the codeset of Shift_JIS is slightly different to IBM932 / CP932. However, the names "SJIS" / "Shift_JIS" are often wrongly used to refer to these codesets.
Additional note:For the CP932 codemap, use SJIS-WIN instead.
Name in the IANA character set registry:(none)
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as EUC-JP, the underlying character set is different. That is, some code points map to different characters than EUC-JP.
Additional note:none
Name in the IANA character set registry:Windows-31J / csWindows31J
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as Shift_JIS, the underlying character set is different. That means some code points map to different characters than Shift_JIS.
Additional note:(none)
Name in the IANA character set registry:ISO-2022-JP (preferred MIME name) / csISO2022JP
Underlying character set: US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983
Description: » RFC1468
Additional note:(none)
Name in the IANA character set registry:JIS
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-1
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-2
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-3
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-4
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-6
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-7
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-8
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-9
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-10
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-13
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-14
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-15
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte2be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte2le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte4be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte4le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:BASE64
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:HTML-ENTITIES
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:7bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:8bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:EUC-CN
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:CP936
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:HZ
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:EUC-TW
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:CP950
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:BIG-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:EUC-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:UHC (CP949)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-2022-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:Windows-1251 (CP1251)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:Windows-1252 (CP1252)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:CP866 (IBM866)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:KOI8-R
Underlying character set:
Description:
Additional note:
Predefined Constants
Basics of Japanese multi-byte encodings
Multibyte String


HTTP Input and Output

HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.

Note: In PHP 4.3.2 or earlier versions, there was a limitation in this functionality that mbstring does not perform character encoding conversion in POST data if the enctype attribute in the form element is set to multipart/form-data. So you have to convert the incoming data by yourself in this case if necessary.
Beginning with PHP 4.3.3, if enctype for HTML form is set to multipart/form-data and mbstring.encoding_translation is set to On in php.ini the POST'ed variables and the names of uploaded files will be converted to the internal character encoding as well. However, the conversion isn't applied to the query keys.

  • HTTP Input

    There is no way to control HTTP input character conversion from a PHP script. To disable HTTP input character conversion, it has to be done in php.ini.

    Example #1 Disable HTTP input conversion in php.ini

    ;; Disable HTTP Input conversion
    mbstring.http_input = pass
    ;; Disable HTTP Input conversion (PHP 4.3.0 or higher)
    mbstring.encoding_translation = Off

    When using PHP as an Apache module, it is possible to override those settings in each Virtual Host directive in httpd.conf or per directory with .htaccess. Refer to the Configuration section and Apache Manual for details.

  • HTTP Output

    There are several ways to enable output character encoding conversion. One is using php.ini, another is using ob_start() with mb_output_handler() as the ob_start callback function.

Example #2 php.ini setting example

;; Enable output character encoding conversion for all PHP pages

;; Enable Output Buffering
output_buffering    = On

;; Set mb_output_handler to enable output conversion
output_handler      = mb_output_handler

Example #3 Script example

<?php

// Enable output character encoding conversion only for this page

// Set HTTP output character encoding to SJIS
mb_http_output('SJIS');

// Start buffering and specify "mb_output_handler" as
// callback function
ob_start('mb_output_handler');

?>

Basics of Japanese multi-byte encodings
Supported Character Encodings
Multibyte String


Installation

mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details.

The following configure options are related to the mbstring module.

  • --enable-mbstring: Enable mbstring functions. This option is required to use mbstring functions.

    libmbfl is necesarry for mbstring. libmbfl is bundled with mbstring. If libmbfl is already installed on the system, --with-libmbfl[=DIR] can be specified to use the installed library.

    As of PHP 4.3.0, mbstring extension provides enhanced support for Simplified Chinese, Traditional Chinese, Korean, and Russian in addition to Japanese.

    For PHP 4.3.3 or before,
To enable that feature, you will have to supply either one of the
following options to the LANG parameter
of --enable-mbstring=LANG;
--enable-mbstring=cn for Simplified Chinese support,
--enable-mbstring=tw for Traditional Chinese support,
--enable-mbstring=kr for Korean support,
--enable-mbstring=ru for Russian support, and
--enable-mbstring=ja for Japanese support (default).
 To enable all supported encoding, use --enable-mbstring=all.

    Note: As of PHP 4.3.4, all supported encoding by libmbfl is enabled with --enable-mbstring.

  • --enable-mbstr-enc-trans : Enable HTTP input character encoding conversion using mbstring conversion engine. If this feature is enabled, HTTP input character encoding may be converted to mbstring.internal_encoding automatically.

    Note: As of PHP 4.3.0, the option --enable-mbstr-enc-trans was eliminated and replaced with the runtime setting mbstring.encoding_translation. HTTP input character encoding conversion is enabled when this is set to On (the default is Off).

  • --disable-mbregex: Disable regular expression functions with multibyte character support.

Requirements
Runtime Configuration
Installing/Configuring


Basics of Japanese multi-byte encodings

Japanese characters can only be represented by multibyte encodings, and multiple encoding standards are used depending on platform and text purpose. To make matters worse, these encoding standards differ slightly from one another. In order to create a web application which would be usable in a Japanese environment, a developer has to keep these complexities in mind to ensure that the proper character encodings are used.

  • Storage for a character can be up to six bytes
  • Most Japanese multibyte characters appear twice as wide as single-byte characters. These characters are called "zen-kaku" in Japanese, which means "full width". Other, narrower, characters are called "han-kaku", which means "half width". The graphical properties of the characters, however, depends upon the type faces used to display them.
  • Some character encodings use shift(escape) sequences defined in ISO-2022 to switch the code map of the specific code area (00h to 7fh).
  • ISO-2022-JP should be used in SMTP/NNTP, and headers and entities should be reencoded as per RFC requirements. Although those are not requisites, it's still a good idea because several popular user agents cannot recognize any other encoding methods.
  • Web pages created for mobile phone services such as » i-mode, » Vodafone live!, or » EZweb are supposed to use Shift_JIS.

Summaries of supported encodings
HTTP Input and Output
Multibyte String


Function Overloading Feature

You might often find it difficult to get an existing PHP application to work in a given multibyte environment. This happens because most PHP applications out there are written with the standard string functions such as substr(), which are known to not properly handle multibyte-encoded strings.

mbstring supports a 'function overloading' feature which enables you to add multibyte awareness to such an application without code modification by overloading multibyte counterparts on the standard string functions. For example, mb_substr() is called instead of substr() if function overloading is enabled. This feature makes it easy to port applications that only support single-byte encodings to a multibyte environment in many cases.

To use function overloading, set mbstring.func_overload in php.ini to a positive value that represents a combination of bitmasks specifying the categories of functions to be overloaded. It should be set to 1 to overload the mail() function. 2 for string functions, 4 for regular expression functions. For example, if it is set to 7, mail, strings and regular expression functions will be overloaded. The list of overloaded functions are shown below.

Functions to be overloaded
value of mbstring.func_overload | original function | overloaded function
1 | mail() | mb_send_mail()
2 | strlen() | mb_strlen()
2 | strpos() | mb_strpos()
2 | strrpos() | mb_strrpos()
2 | substr() | mb_substr()
2 | strtolower() | mb_strtolower()
2 | strtoupper() | mb_strtoupper()
2 | stripos() | mb_stripos()
2 | strripos() | mb_strripos()
2 | strstr() | mb_strstr()
2 | stristr() | mb_stristr()
2 | strrchr() | mb_strrchr()
2 | substr_count() | mb_substr_count()
4 | ereg() | mb_ereg()
4 | eregi() | mb_eregi()
4 | ereg_replace() | mb_ereg_replace()
4 | eregi_replace() | mb_eregi_replace()
4 | split() | mb_split()

Note: It is not recommended to use the function overloading option in the per-directory context, because it's not confirmed yet to be stable enough in a production environment and may lead to undefined behaviour.

Supported Character Encodings
PHP Character Encoding Requirements
Multibyte String


PHP Character Encoding Requirements

Encodings of the following types are safely used with PHP.

  • A singlebyte encoding,

    • which has ASCII-compatible (ISO646 compatible) mappings for the characters in range of 00h to 7fh.

  • A multibyte encoding,

    • which has ASCII-compatible mappings for the characters in range of 00h to 7fh.
    • which don't use ISO2022 escape sequences.
    • which don't use a value from 00h to 7fh in any of the compounded bytes that represents a single character.

These are examples of character encodings that are unlikely to work with PHP.

JIS, SJIS, ISO-2022-JP, BIG-5

Although PHP scripts written in any of those encodings might not work, especially in the case where encoded strings appear as identifiers or literals in the script, you can almost avoid using these encodings by setting up the mbstring's transparent encoding filter function for incoming HTTP queries.

Note: It's highly discouraged to use SJIS, BIG5, CP936, CP949 and GB18030 for the internal encoding unless you are familiar with the parser, the scanner and the character encoding.

Note: If you are connecting to a database with PHP, it is recommended that you use the same character encoding for both the database and the internal encoding for ease of use and better performance.
If you are using PostgreSQL, the character encoding used in the database and the one used in PHP may differ as it supports automatic character set conversion between the backend and the frontend.

Function Overloading Feature
Multibyte String Functions
Multibyte String


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Multibyte String


Supported Character Encodings

Currently the following character encodings are supported by the mbstring module. Any of those Character encodings can be specified in the encoding parameter of mbstring functions.

The following character encodings are supported in this PHP extension:

  • UCS-4*
  • UCS-4BE
  • UCS-4LE*
  • UCS-2
  • UCS-2BE
  • UCS-2LE
  • UTF-32*
  • UTF-32BE*
  • UTF-32LE*
  • UTF-16*
  • UTF-16BE*
  • UTF-16LE*
  • UTF-7
  • UTF7-IMAP
  • UTF-8*
  • ASCII*
  • EUC-JP*
  • SJIS*
  • eucJP-win*
  • SJIS-win*
  • ISO-2022-JP
  • JIS
  • ISO-8859-1*
  • ISO-8859-2*
  • ISO-8859-3*
  • ISO-8859-4*
  • ISO-8859-5*
  • ISO-8859-6*
  • ISO-8859-7*
  • ISO-8859-8*
  • ISO-8859-9*
  • ISO-8859-10*
  • ISO-8859-13*
  • ISO-8859-14*
  • ISO-8859-15*
  • byte2be
  • byte2le
  • byte4be
  • byte4le
  • BASE64
  • HTML-ENTITIES
  • 7bit
  • 8bit
  • EUC-CN*
  • CP936
  • HZ
  • EUC-TW*
  • CP950
  • BIG-5*
  • EUC-KR*
  • UHC (CP949)
  • ISO-2022-KR
  • Windows-1251 (CP1251)
  • Windows-1252 (CP1252)
  • CP866 (IBM866)
  • KOI8-R*

* denotes encodings usable also in regular expressions.

Any php.ini entry which accepts an encoding name can also use the values "auto" and "pass". mbstring functions which accept an encoding name can also use the value "auto".

If "pass" is set, no character encoding conversion is performed.

If "auto" is set, it is expanded to the list of encodings defined per the NLS. For instance, if the NLS is set to Japanese, the value is assumed to be "ASCII,JIS,UTF-8,EUC-JP,SJIS".

See also mb_detect_order()

HTTP Input and Output
Function Overloading Feature
Multibyte String


Mcrypt ciphers

Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().

  • MCRYPT_3DES
  • MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)
  • MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)
  • MCRYPT_BLOWFISH
  • MCRYPT_CAST_128
  • MCRYPT_CAST_256
  • MCRYPT_CRYPT
  • MCRYPT_DES
  • MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)
  • MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)
  • MCRYPT_GOST
  • MCRYPT_IDEA (non-free)
  • MCRYPT_LOKI97 (libmcrypt > 2.4.x only)
  • MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)
  • MCRYPT_PANAMA (libmcrypt > 2.4.x only)
  • MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)
  • MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)
  • MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)
  • MCRYPT_RC2
  • MCRYPT_RC4 (libmcrypt 2.2.x only)
  • MCRYPT_RC6 (libmcrypt > 2.4.x only)
  • MCRYPT_RC6_128 (libmcrypt 2.2.x only)
  • MCRYPT_RC6_192 (libmcrypt 2.2.x only)
  • MCRYPT_RC6_256 (libmcrypt 2.2.x only)
  • MCRYPT_SAFER64
  • MCRYPT_SAFER128
  • MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)
  • MCRYPT_SERPENT(libmcrypt > 2.4.x only)
  • MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)
  • MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)
  • MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)
  • MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)
  • MCRYPT_TEAN (libmcrypt 2.2.x only)
  • MCRYPT_THREEWAY
  • MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)
  • MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )
  • MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)
  • MCRYPT_TWOFISH192
  • MCRYPT_TWOFISH256
  • MCRYPT_WAKE (libmcrypt > 2.4.x only)
  • MCRYPT_XTEA (libmcrypt > 2.4.x only)

You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).

Predefined Constants
Examples
Mcrypt


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mcrypt configuration options
Name | Default | Changeable | Changelog
mcrypt.algorithms_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
mcrypt.modes_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).

  • MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.
  • MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.
  • MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.
  • MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.
  • MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.
  • MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like "WAKE" or "RC4".

Some other mode and random device constants:

MCRYPT_ENCRYPT (integer)
MCRYPT_DECRYPT (integer)
MCRYPT_DEV_RANDOM (integer)
MCRYPT_DEV_URANDOM (integer)
MCRYPT_RAND (integer)

Resource Types
Mcrypt ciphers
Mcrypt


Examples

Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.

Example #1 Encrypt an input value with TripleDES under 2.2.x in ECB mode

<?php
$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
?>

This example will give you the encrypted data as a string in $encrypted_data.

If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.

Example #2 Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode

<?php
    $key = "this is a secret key";
    $input = "Let us meet at 9 o'clock at the secret place.";

    $td = mcrypt_module_open('tripledes', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $encrypted_data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
?>

This example will give you the encrypted data as a string in $encrypted_data. For a full example see mcrypt_module_open().

Mcrypt ciphers
Mcrypt Functions
Mcrypt


Installation

You need to compile PHP with the --with-mcrypt[=DIR] parameter to enable this extension. DIR is the mcrypt install directory. Make sure you compile libmcrypt with the option --disable-posix-threads.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

These functions work using » mcrypt. To use it, download libmcrypt-x.x.tar.gz from » http://mcrypt.sourceforge.net/ and follow the included installation instructions. Windows users will find all the needed compiled mcrypt binaries at » http://files.edin.dk/php/win32/mcrypt/.

As of PHP 5.0.0 you will need libmcrypt Version 2.5.6 or greater.

If you linked against libmcrypt 2.4.x or higher, the following additional block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE. With libmcrypt 2.4.x or higher another cipher mode is also available; nOFB.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

mcrypt_module_open() returns an encryption descriptor.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Mcrypt


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

M_PENDING (integer)
M_DONE (integer)
M_ERROR (integer)
M_FAIL (integer)
M_SUCCESS (integer)
Resource Types
MCVE Functions
MCVE


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/mcve.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

If installing without specifying the libmonetra path, PHP will attempt to look in the default LibMonetra Install location (/usr/local). If Monetra (MCVE) is in a non-standard location, run configure with: --with-mcve=$mcve_path, where $mcve_path is the path to your MCVE/Monetra installation. Please note that MCVE/Monetra support requires that $mcve_path/lib and $mcve_path/include exist, and include mcve.h or monetra.h under the include directory and libmcve.so and/or libmcve.a and/or libmonetra.so and/or libmonetra.a under the lib directory.

Since MCVE/Monetra has true server/client separation, there are no additional requirements for running PHP with MCVE support. To test your MCVE/Monetra extension in PHP, you may connect to testbox.monetra.com on port 8333 for IP, or port 8444 for SSL using the MCVE/Monetra PHP API. Use 'vitale' for your username, and 'test' for your password. Additional information about test facilities are available at » http://www.mainstreetsoftworks.com/.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

The LibMonetra (formerly libmcve) library.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension defines a MCVE_CONN resource returned by m_initconn().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
MCVE


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
Memtrack


Examples

Table of Contents

  • Creating large array in a function
Predefined Constants
Creating large array in a function
Memtrack


Creating large array in a function

Examples
Object overloading
Examples
PHP Manual

Basic example on using memtrack extension:

Example #1 Creating large array in a function

<?php

/* /tmp/example1.php */

function foo() {
    $a = array();
    for ($i = 0; $i < 10000; $i++) $a[] = "test";
    return $a;
}
$arr = foo();

?>

Run the example with the following command:

php -d memtrack.enabled=1 -d memtrack.soft_limit=1M -d memtrack.vm_limit=3M /tmp/example1.php

The above example will output something similar to:

Warning: [memtrack] [pid 26177] user function foo() executed in /tmp/example1.php on line 10 allocated 4194304 bytes in /tmp/example1.php on line 0
Warning: [memtrack] [pid 26177] virtual memory usage on shutdown: 32911360 bytes in Unknown on line 0
Examples
Object overloading
Examples


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Memtrack Configuration Options
Name | Default | Changeable
memtrack.enabled | "0" | PHP_INI_SYSTEM
memtrack.soft_limit | "0" | PHP_INI_ALL
memtrack.hard_limit | "0" | PHP_INI_ALL
memtrack.vm_limit | "0" | PHP_INI_ALL
memtrack.ignore_functions | "" | PHP_INI_SYSTEM

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

memtrack.enabled boolean

Disables or enables the extension. Default value is 0, i.e. disabled.

memtrack.soft_limit int

Soft memory limit.

The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the soft limit, but only if the function is not ignored.

Setting this option to 0 also disables both soft and hard limit warnings. Default value is 0, i.e. no warnings is produced.

memtrack.hard_limit int

Hard memory limit.

The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the hard limit, even if the function is ignored. Setting this option to 0 disables hard limit warnings completely. Default value is 0, i.e. no hard limit warnings is produced.

memtrack.vm_limit int

Virtual memory limit (set on a process).

This limit is checked only on shutdown and a warning is produced if the value is greater than or equal to the limit.

This option is currently supported only on OSes where mallinfo() function is available (i.e. Linux).

memtrack.ignore_functions string

A comma or whitespace-separated list of functions which are to be ignored by soft_limit. The values are case-insensitive, for class methods use class::method syntax.

Installation
Resource Types
Installing/Configuring


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/memtrack

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Memtrack


Constructs a new Message Formatter

MessageFormatter
MessageFormatter::formatMessage
MessageFormatter
PHP Manual

MessageFormatter::create

MessageFormatter::__construct

msgfmt_create

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::create -- MessageFormatter::__construct -- msgfmt_create — Constructs a new Message Formatter

Description

Object oriented style (method)

MessageFormatter MessageFormatter::create ( string $locale , string $pattern )

Object oriented style (constructor):

MessageFormatter::__construct ( string $locale , string $pattern )

Procedural style

MessageFormatter msgfmt_create ( string $locale , string $pattern )

Constructs a new Message Formatter

Parameters

locale

The locale to use when formatting arguments

pattern

The pattern string to stick arguments into. The pattern uses an 'apostrophe-friendly' syntax; it is run through » umsg_autoQuoteApostrophe before being interpreted.

Return Values

The formatter object

Examples

Example #1 msgfmt_create() example

<?php
$fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
$fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo $fmt->format(array(4560, 123, 4560/123));
$fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo $fmt->format(array(4560, 123, 4560/123));
?>

The above example will output:

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

See Also

  • msgfmt_format() - Format the message
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

MessageFormatter
MessageFormatter::formatMessage
MessageFormatter


Format the message

MessageFormatter::formatMessage
MessageFormatter::getErrorCode
MessageFormatter
PHP Manual

MessageFormatter::format

msgfmt_format

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::format -- msgfmt_format — Format the message

Description

Object oriented style

string MessageFormatter::format ( array $args )

Procedural style

string msgfmt_format ( MessageFormatter $fmt , array $args )

Format the message by substituting the data into the format string according to the locale rules

Parameters

fmt

The message formatter

args

Arguments to insert into the format string

Return Values

The formatted string, or FALSE if an error occurred

Examples

Example #1 msgfmt_format() example

<?php
$fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
$fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo $fmt->format(array(4560, 123, 4560/123));
$fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo $fmt->format(array(4560, 123, 4560/123));
?>

The above example will output:

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_format_message() - Quick format message
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

MessageFormatter::formatMessage
MessageFormatter::getErrorCode
MessageFormatter


Quick format message

MessageFormatter::create
MessageFormatter::format
MessageFormatter
PHP Manual

MessageFormatter::formatMessage

msgfmt_format_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::formatMessage -- msgfmt_format_message — Quick format message

Description

Object oriented style

static string MessageFormatter::formatMessage ( string $locale , string $pattern , array $args )

Procedural style

string msgfmt_format_message ( string $locale , string $pattern , array $args )

Quick formatting function that formats the string without having to explicitly create the formatter object. Use this function when the format operation is done only once and does not need and parameters or state to be kept.

Parameters

locale

The locale to use for formatting locale-dependent parts

pattern

The pattern string to insert things into. The pattern uses an 'apostrophe-friendly' syntax; it is run through » umsg_autoQuoteApostrophe before being interpreted.

args

The array of values to insert into the format string

Return Values

The formatted pattern string or FALSE if an error occurred

Examples

Example #1 msgfmt_format_message() example

<?php
echo msgfmt_format_message("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", array(4560, 123, 4560/123));
echo msgfmt_format_message("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum", array(4560, 123, 4560/123));

Example #2 OO example

<?php
echo msgfmt_format_message("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", array(4560, 123, 4560/123));
echo msgfmt_format_message("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum", array(4560, 123, 4560/123));
?>

The above example will output:

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

MessageFormatter::create
MessageFormatter::format
MessageFormatter


Get the error code from last operation

MessageFormatter::format
MessageFormatter::getErrorMessage
MessageFormatter
PHP Manual

MessageFormatter::getErrorCode

msgfmt_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getErrorCode -- msgfmt_get_error_code — Get the error code from last operation

Description

Object oriented style

int MessageFormatter::getErrorCode ( void )

Procedural style

int msgfmt_get_error_code ( MessageFormatter $fmt )

Get the error code from last operation.

Parameters

fmt

The message formatter

Return Values

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

Examples

Example #1 msgfmt_get_error_code() example

<?php
$fmt = msgfmt_create("en_US", "{0, number} monkeys on {1, number} trees");
$str = msgfmt_format($fmt, array());
if(!$str) {
    echo "ERROR: ".msgfmt_get_error_message($fmt) . " (" . msgfmt_get_error_code($fmt) . ")\n";
}
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0, number} monkeys on {1, number} trees");
$str = $fmt->format(array());
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>

The above example will output:

ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)

See Also

  • msgfmt_get_error_message() - Get the error text from the last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

MessageFormatter::format
MessageFormatter::getErrorMessage
MessageFormatter


Get the error text from the last operation

MessageFormatter::getErrorCode
MessageFormatter::getLocale
MessageFormatter
PHP Manual

MessageFormatter::getErrorMessage

msgfmt_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getErrorMessage -- msgfmt_get_error_message — Get the error text from the last operation

Description

Object oriented style

string MessageFormatter::getErrorMessage ( void )

Procedural style

string msgfmt_get_error_message ( MessageFormatter $fmt )

Get the error text from the last operation.

Parameters

fmt

The message formatter

Return Values

Description of the last error.

Examples

Example #1 msgfmt_get_error_message() example

<?php
$fmt = msgfmt_create("en_US", "{0, number} monkeys on {1, number} trees");
$str = msgfmt_format($fmt, array());
if(!$str) {
    echo "ERROR: ".msgfmt_get_error_message($fmt) . " (" . msgfmt_get_error_code($fmt) . ")\n";
}
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0, number} monkeys on {1, number} trees");
$str = $fmt->format(array());
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>

The above example will output:

ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)

See Also

  • msgfmt_get_error_code() - Get the error code from last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

MessageFormatter::getErrorCode
MessageFormatter::getLocale
MessageFormatter


Get the locale for which the formatter was created.

MessageFormatter::getErrorMessage
MessageFormatter::getPattern
MessageFormatter
PHP Manual

MessageFormatter::getLocale

msgfmt_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getLocale -- msgfmt_get_locale — Get the locale for which the formatter was created.

Description

Object oriented style

string MessageFormatter::getLocale ( void )

Procedural style

string msgfmt_get_locale ( NumberFormatter $formatter )

Get the locale for which the formatter was created.

Parameters

formatter

The formatter resource

Return Values

The locale name

Examples

Example #1 msgfmt_get_locale() example

<?php
$fmt = msgfmt_create('en_US', "Number {0,number}");
echo msgfmt_get_locale($fmt);
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter('en_US', "Number {0,number}");
echo $fmt->getLocale();
?>

The above example will output:

en_US

See Also

  • msgfmt_create() - Constructs a new Message Formatter

MessageFormatter::getErrorMessage
MessageFormatter::getPattern
MessageFormatter


Get the pattern used by the formatter

MessageFormatter::getLocale
MessageFormatter::parseMessage
MessageFormatter
PHP Manual

MessageFormatter::getPattern

msgfmt_get_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getPattern -- msgfmt_get_pattern — Get the pattern used by the formatter

Description

Object oriented style

string MessageFormatter::getPattern ( void )

Procedural style

string msgfmt_get_pattern ( MessageFormatter $fmt )

Get the pattern used by the formatter

Parameters

fmt

The message formatter

Return Values

The pattern string for this message formatter

Examples

Example #1 msgfmt_get_pattern() example

<?php
$fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";

msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n";

$fmt->setPattern("{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n";
?>

The above example will output:

Default pattern: '{0,number} monkeys on {1,number} trees'
Formatting result: 123 monkeys on 456 trees
New pattern: '{0,number} trees hosting {1,number} monkeys'
Formatted number: 123 trees hosting 456 monkeys

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_set_pattern() - Set the pattern used by the formatter

MessageFormatter::getLocale
MessageFormatter::parseMessage
MessageFormatter


Parse input string according to pattern

MessageFormatter::parseMessage
MessageFormatter::setPattern
MessageFormatter
PHP Manual

MessageFormatter::parse

msgfmt_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::parse -- msgfmt_parse — Parse input string according to pattern

Description

Object oriented style

array MessageFormatter::parse ( string $value )

Procedural style

array msgfmt_parse ( MessageFormatter $fmt , string $value )

Parses input string and return any extracted items as an array.

Parameters

fmt

The message formatter

value

The string to parse

Return Values

An array containing the items extracted, or FALSE on error

Examples

Example #1 msgfmt_parse() example

<?php
$fmt = msgfmt_create('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
$res = msgfmt_parse($fmt, "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($res);

$fmt = msgfmt_create('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
$res = msgfmt_parse($fmt, "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($res);
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
$res = $fmt->parse("4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($res);

$fmt = new MessageFormatter('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
$res = $fmt->parse("4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($res);
?>

The above example will output:

array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)
array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_format() - Format the message
  • msgfmt_parse_message() - Quick parse input string

MessageFormatter::parseMessage
MessageFormatter::setPattern
MessageFormatter


Quick parse input string

MessageFormatter::getPattern
MessageFormatter::parse
MessageFormatter
PHP Manual

MessageFormatter::parseMessage

msgfmt_parse_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::parseMessage -- msgfmt_parse_message — Quick parse input string

Description

Object oriented style

static array MessageFormatter::parseMessage ( string $locale , string $value )

Procedural style

array msgfmt_parse_message ( string $locale , string $value )

Parses input string without explicitly creating the formatter object. Use this function when the format operation is done only once and does not need and parameters or state to be kept.

Parameters

locale

The locale to use for parsing locale-dependent parts

value

The string to parse for items

Return Values

An array containing items extracted, or FALSE on error

Examples

Example #1 msgfmt_parse_message() example

<?php
$fmt = msgfmt_parse_message('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",
                            "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($fmt);

$fmt = msgfmt_parse_message('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum",
                            "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($fmt);
?>

Example #2 OO example

<?php
$fmt = MessageFormatter::parseMessage('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",
                            "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($fmt);

$fmt = MessageFormatter::parseMessage('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum",
                            "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($fmt);
?>

The above example will output:

array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)
array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_format_message() - Quick format message
  • msgfmt_parse() - Parse input string according to pattern

MessageFormatter::getPattern
MessageFormatter::parse
MessageFormatter


Set the pattern used by the formatter

MessageFormatter::parse
IntlDateFormatter
MessageFormatter
PHP Manual

MessageFormatter::setPattern

msgfmt_set_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::setPattern -- msgfmt_set_pattern — Set the pattern used by the formatter

Description

Object oriented style

bool MessageFormatter::setPattern ( string $pattern )

Procedural style

bool msgfmt_set_pattern ( MessageFormatter $fmt , string $pattern )

Set the pattern used by the formatter

Parameters

fmt

The message formatter

pattern

The pattern string to use in this message formatter. The pattern uses an 'apostrophe-friendly' syntax; it is run through » umsg_autoQuoteApostrophe before being interpreted.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 msgfmt_set_pattern() example

<?php
$fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";

msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n";

$fmt->setPattern("{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n";
?>

The above example will output:

Default pattern: '{0,number} monkeys on {1,number} trees'
Formatting result: 123 monkeys on 456 trees
New pattern: '{0,number} trees hosting {1,number} monkeys'
Formatted number: 123 trees hosting 456 monkeys

See Also

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_get_pattern() - Get the pattern used by the formatter

MessageFormatter::parse
IntlDateFormatter
MessageFormatter


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but is listed by mhash as supported, you can safely assume that this documentation is outdated.

  • MHASH_ADLER32
  • MHASH_CRC32
  • MHASH_CRC32B
  • MHASH_GOST
  • MHASH_HAVAL128
  • MHASH_HAVAL160
  • MHASH_HAVAL192
  • MHASH_HAVAL256
  • MHASH_MD4
  • MHASH_MD5
  • MHASH_RIPEMD160
  • MHASH_SHA1
  • MHASH_SHA256
  • MHASH_TIGER
  • MHASH_TIGER128
  • MHASH_TIGER160

Resource Types
Examples
Mhash


Examples

Example #1 Compute the MD5 digest and hmac and print it out as hex

<?php
$input = "what do ya want for nothing?";
$hash = mhash(MHASH_MD5, $input);
echo "The hash is " . bin2hex($hash) . "<br />\n";
$hash = mhash(MHASH_MD5, $input, "Jefe");
echo "The hmac is " . bin2hex($hash) . "<br />\n";
?>

This will produce:

The hash is d03cb659cbf9192dcd066272249f8412
The hmac is 750c783e6ab0b503eaa86e310a5db738

Predefined Constants
Mhash Functions
Mhash


Installation

You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash install directory.

As of PHP 5.3.0, the mhash extension is emulated thru the Hash extension. This makes the directory to the mhash installation have no effect, and requires the hash extension to be enabled for mhash support to be available.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To use it, download the mhash distribution from » its web site and follow the included installation instructions.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Mhash


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mimetype configuration options
Name | Default | Changeable | Changelog
mime_magic.debug | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Available since PHP 4.3.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mime_magic.debug bool

Enable/disable debugging.

mime_magic.magicfile string

The path to the magic.mime file.

Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

Resource Types
xattr
Mimetype


Installation

Warning

Mimetype extensions has been removed from PHP 5.3.0 in favor of Fileinfo.

You must compile PHP with the configure switch --with-mime-magic to get support for mime-type functions. The extension needs a copy of the simplified magic file that is distributed with the Apache httpd.

Note: The configure option has been changed from --enable-mime-magic to --with-mime-magic since PHP 4.3.2

Note: This extension is not capable of handling the fully decorated magic file that generally comes with standard Linux distro's and is supposed to be used with recent versions of file command.

Note: Note to Win32 Users
In order to use this module on a Windows environment, you must set the path to the bundled magic.mime file in your php.ini.

Example #1 Setting the path to magic.mime

mime_magic.magicfile = "$PHP_INSTALL_DIR\magic.mime"

Remember to substitute the $PHP_INSTALL_DIR for your actual path to PHP in the above example. e.g. c:\php

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Mimetype


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

MING_NEW (integer)
MING_ZLIB (integer)
SWFBUTTON_HIT (integer)
SWFBUTTON_DOWN (integer)
SWFBUTTON_OVER (integer)
SWFBUTTON_UP (integer)
SWFBUTTON_MOUSEUPOUTSIDE (integer)
SWFBUTTON_DRAGOVER (integer)
SWFBUTTON_DRAGOUT (integer)
SWFBUTTON_MOUSEUP (integer)
SWFBUTTON_MOUSEDOWN (integer)
SWFBUTTON_MOUSEOUT (integer)
SWFBUTTON_MOUSEOVER (integer)
SWFFILL_RADIAL_GRADIENT (integer)
SWFFILL_LINEAR_GRADIENT (integer)
SWFFILL_TILED_BITMAP (integer)
SWFFILL_CLIPPED_BITMAP (integer)
SWFTEXTFIELD_HASLENGTH (integer)
SWFTEXTFIELD_NOEDIT (integer)
SWFTEXTFIELD_PASSWORD (integer)
SWFTEXTFIELD_MULTILINE (integer)
SWFTEXTFIELD_WORDWRAP (integer)
SWFTEXTFIELD_DRAWBOX (integer)
SWFTEXTFIELD_NOSELECT (integer)
SWFTEXTFIELD_HTML (integer)
SWFTEXTFIELD_ALIGN_LEFT (integer)
SWFTEXTFIELD_ALIGN_RIGHT (integer)
SWFTEXTFIELD_ALIGN_CENTER (integer)
SWFTEXTFIELD_ALIGN_JUSTIFY (integer)
SWFACTION_ONLOAD (integer)
SWFACTION_ENTERFRAME (integer)
SWFACTION_UNLOAD (integer)
SWFACTION_MOUSEMOVE (integer)
SWFACTION_MOUSEDOWN (integer)
SWFACTION_MOUSEUP (integer)
SWFACTION_KEYDOWN (integer)
SWFACTION_KEYUP (integer)
SWFACTION_DATA (integer)
Resource Types
Examples
Ming


Examples

Table of Contents

  • SWFAction Examples
  • SWFSPrite basic examples
Predefined Constants
SWFAction Examples
Ming


SWFAction Examples

This simple example will move the red square across the window.

Example #1 swfaction() example

<?php
  $s = new SWFShape();
  $f = $s->addFill(0xff, 0, 0);
  $s->setRightFill($f);

  $s->movePenTo(-500, -500);
  $s->drawLineTo(500, -500);
  $s->drawLineTo(500, 500);
  $s->drawLineTo(-500, 500);
  $s->drawLineTo(-500, -500);

  $p = new SWFSprite();
  $i = $p->add($s);
  $i->setDepth(1);
  $p->nextFrame();

  for ($n=0; $n<5; ++$n) {
    $i->rotate(-15);
    $p->nextFrame();
  }

  $m = new SWFMovie();
  $m->setBackground(0xff, 0xff, 0xff);
  $m->setDimension(6000, 4000);

  $i = $m->add($p);
  $i->setDepth(1);
  $i->moveTo(-500,2000);
  $i->setName("box");

  $m->add(new SWFAction("/box.x += 3;"));
  $m->nextFrame();
  $m->add(new SWFAction("gotoFrame(0); play();"));
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example tracks down your mouse on the screen.

Example #2 swfaction() example

<?php

  $m = new SWFMovie();
  $m->setRate(36.0);
  $m->setDimension(1200, 800);
  $m->setBackground(0, 0, 0);

  /* mouse tracking sprite - empty, but follows mouse so we can
     get its x and y coordinates */

  $i = $m->add(new SWFSprite());
  $i->setName('mouse');

  $m->add(new SWFAction("
    startDrag('/mouse', 1); /* '1' means lock sprite to the mouse */
  "));

  /* might as well turn off antialiasing, since these are just squares. */

  $m->add(new SWFAction("
    this.quality = 0;
  "));

  /* morphing box */
  $r = new SWFMorph();
  $s = $r->getShape1();

  /* Note this is backwards from normal shapes.  No idea why. */
  $s->setLeftFill($s->addFill(0xff, 0xff, 0xff));
  $s->movePenTo(-40, -40);
  $s->drawLine(80, 0);
  $s->drawLine(0, 80);
  $s->drawLine(-80, 0);
  $s->drawLine(0, -80);

  $s = $r->getShape2();

  $s->setLeftFill($s->addFill(0x00, 0x00, 0x00));
  $s->movePenTo(-1, -1);
  $s->drawLine(2, 0);
  $s->drawLine(0, 2);
  $s->drawLine(-2, 0);
  $s->drawLine(0, -2);

  /* sprite container for morphing box -
     this is just a timeline w/ the box morphing */

  $box = new SWFSprite();
  $box->add(new SWFAction("
    stop();
  "));
  $i = $box->add($r);

  for ($n=0; $n<=20; ++$n) {
    $i->setRatio($n/20);
    $box->nextFrame();
  }

  /* this container sprite allows us to use the same action code many times */

  $cell = new SWFSprite();
  $i = $cell->add($box);
  $i->setName('box');

  $cell->add(new SWFAction("

    setTarget('box');

    /* ...x means the x coordinate of the parent, i.e. (..).x */
    dx = (/mouse.x + random(6)-3 - ...x)/5;
    dy = (/mouse.y + random(6)-3 - ...y)/5;
    gotoFrame(int(dx*dx + dy*dy));

  "));

  $cell->nextFrame();
  $cell->add(new SWFAction("

    gotoFrame(0);
    play();

  "));

  $cell->nextFrame();

  /* finally, add a bunch of the cells to the movie */

  for ($x=0; $x<12; ++$x) {
    for ($y=0; $y<8; ++$y) {
      $i = $m->add($cell);
      $i->moveTo(100*$x+50, 100*$y+50);
    }
  }

  $m->nextFrame();

  $m->add(new SWFAction("

    gotoFrame(1);
    play();

  "));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Same as above, but with nice colored balls...

Example #3 swfaction() example

<?php

  $m = new SWFMovie();
  $m->setDimension(11000, 8000);
  $m->setBackground(0x00, 0x00, 0x00);

  $m->add(new SWFAction("

this.quality = 0;
/frames.visible = 0;
startDrag('/mouse', 1);

  "));

  // mouse tracking sprite
  $t = new SWFSprite();
  $i = $m->add($t);
  $i->setName('mouse');

  $g = new SWFGradient();
  $g->addEntry(0, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.1, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.5, 0xff, 0xff, 0xff, 0x5f);
  $g->addEntry(1.0, 0xff, 0xff, 0xff, 0);

  // gradient shape thing
  $s = new SWFShape();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.03);
  $s->setRightFill($f);
  $s->movePenTo(-600, -600);
  $s->drawLine(1200, 0);
  $s->drawLine(0, 1200);
  $s->drawLine(-1200, 0);
  $s->drawLine(0, -1200);

  // need to make this a sprite so we can multColor it
  $p = new SWFSprite();
  $p->add($s);
  $p->nextFrame();

  // put the shape in here, each frame a different color
  $q = new SWFSprite();
  $q->add(new SWFAction("gotoFrame(random(7)+1); stop();"));
  $i = $q->add($p);

  $i->multColor(1.0, 1.0, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 0.75, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 0.5, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 1.0);
  $q->nextFrame();

  // finally, this one contains the action code
  $p = new SWFSprite();
  $i = $p->add($q);
  $i->setName('frames');
  $p->add(new SWFAction("

dx = (/:mousex-/:lastx)/3 + random(10)-5;
dy = (/:mousey-/:lasty)/3;
x = /:mousex;
y = /:mousey;
alpha = 100;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("

this.x = x;
this.y = y;
this.alpha = alpha;
x += dx;
y += dy;
dy += 3;
alpha -= 8;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("prevFrame(); play();"));
  $p->nextFrame();

  $i = $m->add($p);
  $i->setName('frames');
  $m->nextFrame();

  $m->add(new SWFAction("

lastx = mousex;
lasty = mousey;
mousex = /mouse.x;
mousey = /mouse.y;

++num;

if (num == 11)
  num = 1;

removeClip('char' & num);
duplicateClip(/frames, 'char' & num, num);

  "));

  $m->nextFrame();
  $m->add(new SWFAction("prevFrame(); play();"));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Examples
SWFSPrite basic examples
Examples


SWFSPrite basic examples

This simple example will spin gracefully a big red square.

Example #1 swfsprite() example

<?php
$s = new SWFShape();
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(-500, -500);
$s->drawLineTo(500, -500);
$s->drawLineTo(500, 500);
$s->drawLineTo(-500, 500);
$s->drawLineTo(-500, -500);

$p = new SWFSprite();
$i = $p->add($s);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();

$m = new SWFMovie();
$i = $m->add($p);
$i->moveTo(1500, 1000);
$i->setName("blah");

$m->setBackground(0xff, 0xff, 0xff);
$m->setDimension(3000, 2000);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFAction Examples
Ming Functions
Examples


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/ming.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To use Ming with PHP, you first need to build and install the Ming library. Source code and installation instructions are available at the Ming home page: » http://www.libming.org/ along with examples, a small tutorial, and the latest news.

Download the ming archive. Unpack the archive. Go in the Ming directory. make. make install.

This will build libming.so and install it into /usr/lib/, and copy ming.h into /usr/include/. Edit the PREFIX= line in the Makefile to change the installation directory.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Ming


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Misc. Configuration Options
Name | Default | Changeable | Changelog
ignore_user_abort | "0" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.bg | "#FFFFFF" | PHP_INI_ALL | Removed in PHP 6.0.0.
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ignore_user_abort boolean

FALSE by default. If changed to TRUE scripts will not be terminated after a client has aborted their connection.

See also ignore_user_abort().

highlight.bg string
highlight.comment string
highlight.default string
highlight.html string
highlight.keyword string
highlight.string string

Colors for Syntax Highlighting mode. Anything that's acceptable in <font color="??????"> would work.

browscap string

Name (e.g.: browscap.ini) and location of browser capabilities file. See also get_browser().

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CONNECTION_ABORTED (integer)
CONNECTION_NORMAL (integer)
CONNECTION_TIMEOUT (integer)
__COMPILER_HALT_OFFSET__ (integer)
Added in PHP 5.1.
Resource Types
Misc. Functions
Misc.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Misc.


Closes this database connection

Mongo
Mongo::connect
Mongo
PHP Manual

Mongo::close

(PECL mongo >=0.9.0)

Mongo::close — Closes this database connection

Description

public boolean Mongo::close ( void )

This method does not need to be called, except in unusual circumstances. The driver will cleanly close the database connection when the Mongo object goes out of scope.

If you are using a service where objects do not go out of scope between requests, you may wish to call close() at the end of your program to keep old connections from hanging around. However, it is probably more efficient to take advantage of this fact and simply use a persistent connection, which will automatically create a connection if needed and use it for as many requests as the application server allows it to exist.

You may also wish to call close() if you are unsure of the state of a connection and wish to guarantee a new connection will happen. For example:

<?php

$mongo = new Mongo();

/* do stuff where the db connection may be lost */

/* if $mongo is already connected, does nothing */
$mongo->connect();

?>

vs.

<?php

$mongo = new Mongo();

/* do stuff where the db connection may be lost */

/* guarantee a reconnection to the db server */
$mongo->close()
$mongo->connect();

?>

Parameters

This function has no parameters.

Return Values

Returns if the connection was successfully closed.

Mongo
Mongo::connect
Mongo


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mongo Configure Options
Name | Default | Changeable
mongo.default_host | "localhost" | PHP_INI_ALL
mongo.default_port | 27017 | PHP_INI_ALL
mongo.auto_reconnect | true | PHP_INI_SYSTEM
mongo.allow_persistent | true | PHP_INI_SYSTEM
mongo.max_persistent | -1 | PHP_INI_SYSTEM
mongo.max_connections | -1 | PHP_INI_SYSTEM
mongo.chunk_size | 262144 | PHP_INI_SYSTEM
mongo.cmd | "$" | PHP_INI_ALL

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mongo.default_host string

Default hostname when nothing is passed to the constructor.

mongo.default_port string

The default TCP port number to use when connecting to the database server if no other port is specified. The database's default is 27017.

mongo.auto_reconnect bool

Whether to reconnect to the database if the connection is lost.

mongo.allow_persistent bool

If persistent connections are allowed.

mongo.max_persistent int

The number of simultaneous persistent connections to allow. -1 allows unlimited persistent connections.

mongo.max_connections int

The number of simultaneous connections to allow. -1 allows unlimited connections.

mongo.chunk_size int

The number of bytes-per-chunk. Used in divvying up GridFS files. This number must be at least 100 less than 4 megabytes (max: 4194204) and it is recommended that it be less than that.

mongo.cmd string

A character to be used in place of $ in modifiers and comparisons.

Installation
Tutorial
Manual


Connects to a database server

Mongo::close
Mongo::connectUtil
Mongo
PHP Manual

Mongo::connect

(PECL mongo >=0.9.0)

Mongo::connect — Connects to a database server

Description

public boolean Mongo::connect ( void )

Parameters

This function has no parameters.

Return Values

If the connection was successful.

Errors/Exceptions

Throws MongoConnectionException if it fails to connect to the database.

Mongo::close
Mongo::connectUtil
Mongo


Connects with a database server

Mongo::connect
Mongo::__construct
Mongo
PHP Manual

Mongo::connectUtil

(PECL mongo >=0.9.0)

Mongo::connectUtil — Connects with a database server

Description

protected boolean Mongo::connectUtil ( string $username , string $password )

Parameters

username

A username used to identify the connection.

password

A password used to identify the connection.

Return Values

If the connection was successful.

Errors/Exceptions

Throws MongoConnectionException if it fails to connect to the databases.

Mongo::connect
Mongo::__construct
Mongo


Creates a new database connection object

Mongo::connectUtil
Mongo::dropDB
Mongo
PHP Manual

Mongo::__construct

(PECL mongo >=0.9.0)

Mongo::__construct — Creates a new database connection object

Description

  Mongo::__construct
  ([ string $server = "mongodb://localhost:27017"
 [, array $options = array("connect" => TRUE)
]] )

If no parameters are passed, this connects to "localhost:27017" (or whatever was specified in php.ini for mongo.default_host and mongo.default_port).

As of version 1.0.2, server can have a special form: mongodb://[username:password@]host1[:port1][,host2[:port2:],...]. Breaking this down, it starts with mongodb://, to indicate it is in this form. If username and password are specified, the constructor will attempt to authenticate the connection with the admin database before returning. Username and password are optional and must be followed by an @, if specified. At least one host must be given (port optional, always defaulting to 27017) and as many hosts as desired may be connected to. Host names are comma-separated and the constructor will return successfully if it connected to at least one host. If it could not connect to any of the hosts, it will throw a MongoConnectionException.

Warning

server Format

Before version 1.0.2, server could not be prefixed with mongodb://, contain username and password, or contain more than two hostnames. See the changelog below for more details.

If you elect not to connect immediately (you pass the option array("connect" => false)), you will need to call Mongo::connect() before doing any database operations.

<?php

$mongo = new Mongo("mongodb://localhost", array("connect" => false);

// throws a MongoException, as $mongo has not been fully initialized yet
$mongo->selectDB("foo")->command(array("distinct" => "bar", "key" => "age"));

// okay
$mongo->connect();
$mongo->selectDB("foo")->command(array("distinct" => "bar", "key" => "age"));

?>

Parameters

server

The server name.

options

An array of options for the connection. Currently available options include:

  • "connect"

    If the constructor should connect before returning. Default is TRUE.

  • "persist"

    If the connection should be persistent. If set, the connection will be persistent. The string representation of the value is used as an id for the connection, so two instances of Mongo that are initialized with array("persist" => "foobar") will share the same database connection, whereas an instance initialized with array("persist" => "barbaz") will use a different database connection.

Return Values

Returns a new database connection object.

Errors/Exceptions

Throws MongoConnectionException if it tries and fails to connect to the database for all hostnames given. It will also throw a MongoConnnectionException if an invalid username or password is given.

Changelog

Version Description
1.0.2 Changed constructor to take an array of options. Pre-1.0.2, the constructor took the following parameters:
server

The server name.

connect

Optional boolean parameter specifying if the constructor should connect to the database before returning. Defaults to TRUE.

persistent

If the connection should be persistent.

paired

If the connection should be paired.

Examples

Example #1 Mongo::__construct() paired connection example

This example shows how to connect the driver to a replica pair of Mongo servers.

<?php

// pass a comma-separated list of server names to the constructor
$m1 = new Mongo("mongodb://www.example1.com,www.example2.com");

// if the database servers are not running on the default port (27017),
// you'll need to specify the port
$m2 = new Mongo("mongodb://www.example1.com:12345,www.example.com:54321");

// you can connect to more that two, as well
$m3 = new Mongo("mongodb://localhost:27017,localhost:27018,localhost:27019");

?>

Example #2 Mongo::__construct() persistent connection example

A persistent connection will last for more than one request (usually... milage may vary depending on server). It can save significant time to reuse connections, as creating a connection is a time-intensive process.

A persistent connection is identified by the server string and and id string.

<?php

// creates a persistent connection
$m1 = new Mongo("mongodb://localhost", array("persist" => ""));

// uses the same connection as $m1
$m2 = new Mongo("mongodb://localhost", array("persist" => ""));

// creates a new connection
$m3 = new Mongo("mongodb://127.0.0.1", array("persist" => ""));

// creates a new connection
$m4 = new Mongo("mongodb://127.0.0.1:27017", array("persist" => ""));

// creates a new connection
$m5 = new Mongo("mongodb://localhost", array("persist" => "foo"));

// uses the $m5 connection
$m6 = new Mongo("mongodb://localhost", array("persist" => "foo"));

?>

Example #3 Mongo::__construct() authentication example

A user must exist in the admin database before attempting to use authentication. You can create one with the Mongo shell by running:

> use admin
switched to db admin
> db.addUser("testUser", "testPass");
{
        "_id" : ObjectId("4b21272fd9ab21611d19095c"),
        "user" : "testUser",
        "pwd" : "03b9b27e0abf1865e2f6fcbd9845dd59"
}
>

After creating a user with, in this case, username "testUser" and password "testPass", you can create an authenticated connection:

<?php

$m = new Mongo("mongodb://testUser:testPass@localhost");

?>
Mongo::connectUtil
Mongo::dropDB
Mongo


Core Classes

Table of Contents

  • The Mongo class
  • The MongoDB class
  • The MongoCollection class
  • The MongoCursor class

The core classes are the most important part of the driver.

Troubleshooting
Mongo
Mongo


Drops a database

Mongo::__construct
Mongo::forceError
Mongo
PHP Manual

Mongo::dropDB

(PECL mongo >=0.9.0)

Mongo::dropDB — Drops a database

Description

public array Mongo::dropDB ( mixed $db )

Parameters

db

The database to drop. Can be a MongoDB object or the name of the database.

Return Values

Returns the database response.

Mongo::__construct
Mongo::forceError
Mongo


Examples

This example shows how to connect, insert objects, query for objects, iterate through query results, and disconnect from a Mongo database.

Example #1 Mongo Example

<?php

// connect
$m = new Mongo();

// select a database
$db = $m->comedy;
$collection = $db->cartoons;

// add an element
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($obj);

// add another element, with a different "shape"
$obj = array( "title" => "XKCD", "online" => true );
$collection->insert($obj);

// find everything in the collection
$cursor = $collection->find();

// iterate through the results
foreach ($cursor as $obj) {
    echo $obj["title"] . "\n";
}

// disconnect
$m->close();

?>

The above example will output something similar to:

Calvin and Hobbes
XKCD
Tutorial
Querying
Manual


Exceptions

Table of Contents

  • The MongoException class
  • The MongoCursorException class
  • The MongoCursorTimeoutException class
  • The MongoConnectionException class
  • The MongoGridFSException class
bson_encode
MongoException
Mongo


Creates a database error on the database [deprecated]

Mongo::dropDB
Mongo::__get
Mongo
PHP Manual

Mongo::forceError()

(No version information available, might only be in SVN)

— Creates a database error on the database [deprecated]

Description

public bool Mongo::forceError ( void )

Use MongoDB::forceError() instead.

Parameters

This function has no parameters.

Return Values

Returns the database response.

Mongo::dropDB
Mongo::__get
Mongo


Functions

Table of Contents

  • Mongo Functions
MongoGridFSCursor::key
Mongo Functions
Mongo


Gets a database

Mongo::forceError
Mongo::lastError
Mongo
PHP Manual

Mongo::__get

(PECL mongo >=1.0.2)

Mongo::__get — Gets a database

Description

public MongoDB Mongo::__get ( string $dbname )

This is the cleanest way of getting a database. If the database name has any special characters, Mongo::selectDB() will need to be used. However, in most cases, this should be sufficient.

<?php

$mongo = new Mongo();

// the following two lines are equivalent
$db = $mongo->selectDB("foo");
$db = $mongo->foo;

?>

Parameters

dbname

The database name.

Return Values

Returns a new db object.

Errors/Exceptions

Throws InvalidArgumentException if the database name is invalid.

Mongo::forceError
Mongo::lastError
Mongo


GridFS Classes

Table of Contents

  • The MongoGridFS class
  • The MongoGridFSFile class
  • The MongoGridFSCursor class
MongoTimestamp::__toString
MongoGridFS
Mongo


Installation

This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/mongo.

Installing on *NIX

Run:

$ sudo pecl install mongo

Add the following line to your php.ini file:

extension=mongo.so

Manual Installation

For driver developers and people interested in the latest bugfixes, you can compile the driver from the latest source on » Github. Go to Github and click the "download" button. Then run:

$ tar zxvf mongodb-mongodb-php-driver-<commit_id>.tar.gz
$ cd mongodb-mongodb-php-driver-<commit_id>
$ phpize
$ ./configure
$ sudo make install

Make the following changes to php.ini:

  • 1. The build will display where it is installing the PHP driver with output that looks something like:

          Installing '/usr/lib/php/extensions/no-debug-zts-20060613/mongo.so'

    Make sure that it is the same as the PHP extension directory by runnning:

          $ php -i | grep extension_dir
        extension_dir => /usr/lib/php/extensions/no-debug-zts-20060613 =>
      /usr/lib/php/extensions/no-debug-zts-20060613

    If it's not, change the extension_dir in php.ini or move mongo.so.

  • 2. To load the extension on PHP startup, add a line:

          extension=mongo.so

OS X

If your system is unable to find autoconf, you'll need to install Xcode (available on your installation DVD).

Precompiled binaries are available from » Github (download the latest one with "osx" in the name that matches your version of PHP). These for use with MAMP and XAMPP, which come without the headers necessary to compile the extension from scratch. Extract mongo.so from the archive and add it to MAMP or XAMPP's extension directory. Add

      extension=mongo.so

to the php.ini file being used and restart the server.

Gentoo

On Gentoo using PECL you might get an error that libtool is the wrong version. Compiling from source you'll need to run aclocal and autoconf.

$ phpize && aclocal && autoconf && ./configure && make && make install

(Thanks to » @riklaunim)

Installing on Windows

VC8 and VC9 precompiled binaries are available for thread safe and non-thread-safe PHP 5.3 on » Github. VC6 precompiled binaries are available for thread safe and non-thread-safe PHP 5.2 and 5.3 from » php.net. Unzip the archive and put php_mongo.dll in your PHP extension directory ("ext" by default).

The latest (non-release) code is compiled into Windows binaries on every commit. The zip consists of a .zip with php_mongo.dll and a version.txt. Please keep the version.txt around so that if you have a question or problem, you can give the developers the exact version you're using. (The number is long and nonsensical, but it will make sense to the developers!)

To get the latest bug fixes (and possibly bugs), download the binary corresponding to the PHP you have installed:

  • » PHP 5.3 VC8 Non-Thread-Safe Mongo extension

  • » PHP 5.3 VC8 Thread-Safe Mongo extension

  • » PHP 5.3 VC9 Non-Thread-Safe Mongo extension

  • » PHP 5.3 VC9 Thread-Safe Mongo extension

Add the following line to your php.ini file:

extension=php_mongo.dll

Third-Party Installation Instructions

A number of people have created excellent tutorials on installing the PHP driver.

  • » PHP 5.3.1 with Xdebug, MongoDB and Lithium on Ubuntu 9.10 / Apache 2.2

    An excellent video that takes you step-by-step through installing Apache, PHP, Xdebug, MongoDB, and Lithium by Jon Adams.

  • » Installing MongoDB and the PHP driver on Ubuntu 9.04

    Spanish article by Javier Aranda (» English translation).

  • » OS X: Installing MongoDB and the PHP Mongo Driver

    By Matt Butcher.

Manual
Runtime Configuration
Manual


Check if there was an error on the most recent db operation performed [deprecated]

Mongo::__get
Mongo::listDBs
Mongo
PHP Manual

Mongo::lastError

(No version information available, might only be in SVN)

Mongo::lastError — Check if there was an error on the most recent db operation performed [deprecated]

Description

public array Mongo::lastError ( void )

Use MongoDB::lastError() instead.

Parameters

This function has no parameters.

Return Values

Returns the error, if there was one, or NULL.

Mongo::__get
Mongo::listDBs
Mongo


Lists all of the databases available.

Mongo::lastError
Mongo::pairConnect
Mongo
PHP Manual

Mongo::listDBs()

(No version information available, might only be in SVN)

— Lists all of the databases available.

Description

public array Mongo::listDBs ( void )

Parameters

This function has no parameters.

Return Values

Returns an associative array containing three fields. The first field is databases, which in turn contains an array. Each element of the array is an associative array corresponding to a database, giving the database's name, size, and if it's empty. The other two fields are totalSize (in bytes) and ok, which is 1 if this method ran successfully.

Mongo::lastError
Mongo::pairConnect
Mongo


Manual

Table of Contents

  • Installation
  • Runtime Configuration
  • Tutorial
  • Examples
  • Querying
  • Updates
  • Troubleshooting
Mongo
Installation
Mongo


Connects to paired database server [deprecated]

Mongo::listDBs
Mongo::pairPersistConnect
Mongo
PHP Manual

Mongo::pairConnect

(PECL mongo >=0.9.0)

Mongo::pairConnect — Connects to paired database server [deprecated]

Description

public boolean Mongo::pairConnect ( void )

Pass a string of the form "mongodb://server1,server2" to the constructor instead of using this method.

Parameters

This function has no parameters.

Return Values

If the connection was successful.

Errors/Exceptions

Throws MongoConnectionException if it fails to connect to the databases.

Mongo::listDBs
Mongo::pairPersistConnect
Mongo


Creates a persistent connection with paired database servers [deprecated]

Mongo::pairConnect
Mongo::persistConnect
Mongo
PHP Manual

Mongo::pairPersistConnect

(PECL mongo >=0.9.0)

Mongo::pairPersistConnect — Creates a persistent connection with paired database servers [deprecated]

Description

 public boolean Mongo::pairPersistConnect
  ([ string $username = ""
 [, string $password = ""
]] )

Pass "mongodb://server1,server2" and array("persist" => $id) to the constructor instead of using this method.

Parameters

username

A username used to identify the connection.

password

A password used to identify the connection.

Return Values

If the connection was successful.

Errors/Exceptions

Throws MongoConnectionException if it fails to connect to the databases.

Mongo::pairConnect
Mongo::persistConnect
Mongo


Creates a persistent connection with a database server [deprecated]

Mongo::pairPersistConnect
Mongo::prevError
Mongo
PHP Manual

Mongo::persistConnect

(PECL mongo >=0.9.0)

Mongo::persistConnect — Creates a persistent connection with a database server [deprecated]

Description

 public boolean Mongo::persistConnect
  ([ string $username = ""
 [, string $password = ""
]] )

Pass array("persist" => $id) to the constructor instead of using this method.

Parameters

username

A username used to identify the connection.

password

A password used to identify the connection.

Return Values

If the connection was successful.

Errors/Exceptions

Throws MongoConnectionException if it fails to connect to the databases.

Mongo::pairPersistConnect
Mongo::prevError
Mongo


Checks for the last error thrown during a database operation [deprecated]

Mongo::persistConnect
Mongo::resetError
Mongo
PHP Manual

Mongo::prevError

(No version information available, might only be in SVN)

Mongo::prevError — Checks for the last error thrown during a database operation [deprecated]

Description

public array Mongo::prevError ( void )

Use MongoDB::prevError() instead.

Parameters

This function has no parameters.

Return Values

Returns the error and the number of operations ago it occurred.

Mongo::persistConnect
Mongo::resetError
Mongo


Querying

Querying by _id

Every object inserted is automatically assigned a unique _id field, which is often a useful field to use in queries.

Suppose that we wish to find the document we just inserted. Inserting adds and _id field to the document, so we can query by that:

<?php

$person = array("name" => "joe");

$people->insert($person);

// now $joe has an _id field
$joe = $people->findOne(array("_id" => $person['_id']));

?>

Unless the user has specified otherwise, the _id field is a MongoId. The most common mistake is attepting to use a string to match a MongoId. Keep in mind that these are two different datatypes, and will not match each other in the same way that the string "array()" is not the same as an empty array. For example:

<?php

$person = array("name" => "joe");

$people->insert($person);

// convert the _id to a string
$pid = $person['_id'] . "";

// FAILS - $pid is a string, not a MongoId
$joe = $people->findOne(array("_id" => $pid));

?>

Arrays

Suppose that we wish to find all documents with an array element of a given value. For example, documents with a "gold" award, such as:

{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "awards" : ["gold", "silver", "bronze"]}

This can be done with a simple query, ignoring the fact that "awards" is an array:

<?php

  $cursor = $collection->find(array("awards" => "gold"));

?>

Suppose we are querying for a more complex object, if each element of the array were an object itself, such as:

{
     "_id" : ObjectId("4b06c282edb87a281e09dad9"),
     "awards" :
     [
        {
            "first place" : "gold"
        },
        {
            "second place" : "silver"
        },
        {
            "third place" :  "bronze"
        }
     ]
}

Still ignoring that this is an array, we can use dot notation to query the subobject:

<?php

  $cursor = $collection->find(array("awards.first place" => "gold"));

?>

Notice that it doesn't matter that there is a space in the the field name (although it may be best not to use spaces, just to make things more readable).

Examples
Updates
Manual


Clears any flagged errors on the connection [deprecated]

Mongo::prevError
Mongo::selectCollection
Mongo
PHP Manual

Mongo::resetError

(No version information available, might only be in SVN)

Mongo::resetError — Clears any flagged errors on the connection [deprecated]

Description

public array Mongo::resetError ( void )

Use MongoDB::resetError() instead.

Parameters

This function has no parameters.

Return Values

Returns the database response.

Mongo::prevError
Mongo::selectCollection
Mongo


Gets a database collection

Mongo::resetError
Mongo::selectDB
Mongo
PHP Manual

Mongo::selectCollection()

(No version information available, might only be in SVN)

— Gets a database collection

Description

public MongoCollection Mongo::selectCollection ( string|MongoDB $db , string $collection )

Parameters

db

The database name.

collection

The collection name.

Return Values

Returns a new collection object.

Errors/Exceptions

Throws InvalidArgumentException if the database or collection name is invalid.

Examples

Example #1 Mongo::selectCollection() example

<?php
$m = new Mongo();

$c1 = $m->selectCollection("foo", "bar.baz");
// which is equivalent to
$c2 = $m->selectDB("foo")->selectCollection("bar.baz");

// $c1 and $c2 now represent the same collection
?>
Mongo::resetError
Mongo::selectDB
Mongo


Gets a database

Mongo::selectCollection
Mongo::__toString
Mongo
PHP Manual

Mongo::selectDB

(PECL mongo >=0.9.0)

Mongo::selectDB — Gets a database

Description

public MongoDB Mongo::selectDB ( string $dbname )

Parameters

dbname

The database name.

Return Values

Returns a new db object.

Errors/Exceptions

Throws InvalidArgumentException if the database name is invalid.

Mongo::selectCollection
Mongo::__toString
Mongo


String representation of this connection

Mongo::selectDB
MongoDB
Mongo
PHP Manual

Mongo::__toString

(PECL mongo >=0.9.0)

Mongo::__toString — String representation of this connection

Description

public string Mongo::__toString ( void )

Parameters

This function has no parameters.

Return Values

Returns hostname and port for this connection.

Mongo::selectDB
MongoDB
Mongo


Troubleshooting

If you're having trouble, there are lots of resources you can turn to.

  • IRC

    The official MongoDB IRC room is irc.freenode.net/#mongodb. This is the fastest way to get help... if there are people around.

  • Mailing List

    » MongoDB's mailing list is a good (and usually very fast) way to get answers to questions.

  • Bug Tracker

    Found a bug? Want a feature? Have a question? File it in the » PHP driver's bug tracker.

Updates
Core Classes
Manual


Tutorial

Making a Connection

To connect to the database server, use one of the following:

<?php

$connection = new Mongo(); // connects to localhost:27017
$connection = new Mongo( "example.com" ); // connect to a remote host (default port)
$connection = new Mongo( "example.com:65432" ); // connect to a remote host at a given port

?>

Now $connection can be used to get a database.

Getting a Database

To select a database, use:

<?php

$db = $connection->dbname;

?>

The database does not need to be created in advance, you can create new databases by selecting them. Be careful of typos! You can inadvertently create a new database, which can cause confusing errors:

<?php

$db = $connection->mybiglongdbname;
// do some stuff
$db = $connection->mybiglongdbnme;
// now connected to a different database!

Getting A Collection

Getting a collection has the same syntax as getting a database:

<?php

$db = $connection->baz
$collection = $db->foobar;

// or, more succinctly
$collection = $connection->baz->foobar;

?>

Inserting a Document

Associative arrays are the basic object that can be saved to a collection in the database. A somewhat random "document" might be:

<?php

$doc = array( "name" => "MongoDB",
   "type" => "database",
   "count" => 1,
   "info" => (object)array( "x" => 203,
       "y" => 102),
   "versions" => array("0.9.7", "0.9.8", "0.9.9")
);

?>

Note that you can have nested arrays and objects. Objects and documents are almost synonymous in MongoDB: you could call $doc a document or an object, but the "info" field is always an object, never a document. This convention is used for all of the documentation.

To insert this document, use MongoCollection::insert():

<?php

$m = new Mongo();
$collection = $m->foo->bar;
$collection->insert( $doc );

?>

Finding Documents using MongoCollection::findOne()

To show that the document we inserted in the previous step is there, we can do a simple findOne() operation to get the first document in the collection. This method returns a single document (rather than the MongoCursor that MongoCollection::find() returns), and it's useful for things where there only is one document matching the query or you are only interested in one result.

<?php

$obj = $collection->findOne();
var_dump( $obj );

?>

and you should see

array(5) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["name"]
  string(7) "MongoDB"
  ["type"]=>
  string(8) "database"
  ["count"]=>
  int(1)
  ["info"]=>
  array (2) {
    ["x"]=>
    int(203)
    ["y"]=>
    int(102)
  }
  ["versions"]
  array(3) {
    [0]=>
    string(5) "0.9.7"
    [1]=>
    string(5) "0.9.8"
    [2]=>
    string(5) "0.9.9"
  }
}

Note the _id field has been added automatically to your document. MongoDB reserves element names that start with _ and $ for internal use.

Adding Multiple Documents

In order to do more interesting things with queries, let's add multiple simple documents to the collection. These documents will just be

<?php

array( "i" => value );

?>

and we can do this fairly efficiently in a loop

<?php

for($i=0; $i<100; $i++) {
    $collection->insert( array( "i" => $i ) );
}

?>

Notice that we can insert arrays with different key sets into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free".

Counting Documents in A Collection

Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the count() method.

<?php

echo $collection->count();

?>

and it should print 101.

MongoCollection::count() can take query and field arguments, as well. You can also do a count on a MongoCursor (see below), which will take into account any filters you have placed on your query.

Using a Cursor to Get All the Documents

In order to get all the documents in the collection, we will use MongoCollection::find(). The find() method returns a MongoCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out:

<?php

$cursor = $collection->find();
foreach ($cursor as $id => $value) {
    echo "$id: ";
    var_dump( $value );
}

?>

and that should print all 101 documents in the collection. $id is the _id field of a document, and $value is the document itself.

Setting Criteria for a Query

We can create a query to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following:

<?php

$query = array( "i" => 71 );
$cursor = $collection->find( $query );

while( $cursor->hasNext() ) {
    var_dump( $cursor->getNext() );
}

?>

and it should just print just one document

array(2) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["i"]=>
  int(71)
  ["_ns"]=>
  "testCollection"
}

Getting A Set of Documents With a Query

We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write:

<?php

$query = array( "i" => array( '$gt' => 50 ) ); //note the single quotes around '$gt'
$cursor = $coll->find( $query );

while( $cursor->hasNext() ) {
    var_dump( $cursor->getNext() );
}

?>

which should print the documents where i > 50. We could also get a range, say 20 < i <= 30:

<?php

$query = array( "i" => array( "\$gt" => 20, "\$lte" => 30 ) );
$cursor = $coll->find( $query );

while( $cursor->hasNext() ) {
    var_dump( $cursor->getNext() );
}

?>

As it is easy to forget to escape the "$", you can also choose your own special character to use instead of '$'. Choose a character that will not occur in your key names, e.g. ":", and add the following line to php.ini:

mongo.cmd = ":"

Then the example above would look like:

<?php

$query = array( "i" => array( ":gt" => 20, ":lte" => 30 ) );

?>

You can also change it in your code using ini_set("mongo.cmd", ":"). Of course, you can also just use single quotes around the $.

Creating An Index

MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you just specify the field that should be indexed, and specify if you want the index to be ascending (1) or descending (-1). The following creates an ascending index on the "i" field :

<?php

$coll->ensureIndex( array( "i" => 1 ) );  // create index on "i"
$coll->ensureIndex( array( "i" => -1, "j" => 1 ) );  // index on "i" descending, "j" ascending

?>

Runtime Configuration
Examples
Manual


Types

Table of Contents

  • The MongoId class
  • The MongoCode class
  • The MongoDate class
  • The MongoRegex class
  • The MongoBinData class
  • The MongoDBRef class
  • The MongoMinKey class
  • The MongoMaxKey class
  • The MongoTimestamp class

MongoDB allows programmers to save and query for data expressed in all of the basic PHP types, compound types (arrays, associative arrays, and objects), and a half-dozen classes provided by the MongoDB PHP driver (for regular expressions, dates, and other specialized applications).

MongoDB uses a storage format called "BSON," Binary Serializable Object Notation, which is similar to JSON but more compact and rich in types. Listed below is the exact byte size of each type (or information required to compute its size, in the case of variable-length types). Keep in mind that these sizes do not include field names. The size of an object can be manually computed, but it may be easier for programmers to call the bson_encode() function and take the length of the resulting string.

An example of manually computing BSON size for saving the object array("x" => null, "y" => 40):

4 bytes (object size)

1 byte  (type of "x" field)
2 bytes ("x" and "\0")
0 bytes (for null)

1 byte  (type of "y" field)
2 bytes ("y" and "\0")
4 bytes (for an integer)

1 byte  (end-of-object byte)
-----------------------
15 bytes

Simple Types

The built-in types are:

Type | Description | Size in MongoDB (bytes)
NULL | Fairly self-explanatory. | 0
boolean | TRUE and FALSE | 1
int | Integer values. | 4
float | Double values. | 8
string | Strings of UTF-8 characters. | string length + 1

Arrays and Objects

Arrays and objects can also be saved to the database. An array with ascending numeric keys will be saved as a an array, anything else will be saved as an object.

<?php

  // $scores will be saved as an array
  $scores = array(98, 100, 73, 85);
  $collection->insert(array("scores" => $scores);

// $scores will be saved as an object
$scores = array("quiz1" => 98, "midterm" => 100, "quiz2" => 73, "final" => 85);
$collection->insert(array("scores" => $scores);

?>

If you query for these objects using the database shell, they will look like:

> db.students.find()
{ "_id" : ObjectId("4b06beada9ad6390dab17c43"), "scores" : [ 98, 100, 73, 85 ] }
{ "_id" : ObjectId("4b06bebea9ad6390dab17c44"), "scores" : { "quiz1" : 98, "midterm" : 100, "quiz2" : 73, "final" : 85 } }

The database can also save arbitrary PHP objects (although they will be returned as associative arrays). The fields are used for the key/value pairs. For example, a blog post might look like:

<?php

  // the blog post class
  class Post {

  var $author;
  var $content;
  var $comments = array();
  var $date;

  public function __construct($author, $content) {
  $this->author = $author;
$this->content = $content;
    $this->date = new MongoDate();
  }

  public function setTitle($title) {
    $this->title = $title;
  }
}

// create a simple blog post and insert it into the database
$post1 = new Post("Adam", "This is a blog post");

$blog->insert($post1);

// there is nothing restricting the type of the "author" field, so we can make
// it a nested object
$author = array("name" => "Fred", "karma" => 42);
$post2 = new Post($author, "This is another blog post.");

// we create an extra field by setting the title
$post2->setTitle("Second Post");

$blog->insert($post2);

?>

From the database shell, this will look something like:

> db.blog.find()
{ "_id" : ObjectId("4b06c263edb87a281e09dad8"), "author" : "Adam", "content" : "This is a blog post", "comments" : [ ], "date" : "Fri Nov 20 2009 11:22:59 GMT-0500 (EST)" }
{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "author" : { "name" : "Fred", "karma" : 42 }, "content" : "This is a blog post", "comments" : [ ], "date" : "Fri Nov 20 2009 11:23:30 GMT-0500 (EST)", "title" : "Second Post" }

MongoDB Types

The Mongo PHP driver also defines a few new types to use with the database. See class documentation for details and examples.

Type | Description | Size in MongoDB (bytes)
MongoBinData | Binary data. | Number of bytes in binary data + 5
MongoCode | JavaScript code. | String length of code + object size of scope.
MongoDate | Dates and times. Stored as milliseconds since the epoch. | 8
MongoId Unique document id:

  • 4 bytes of timestamp

    No two records can have the same id if they were inserted at different times.

  • 3 bytes machine id

    No two records can have the same id if they were inserted on different machines

  • 2 bytes thread id

    No two records can have the same id if they were inserted by different threads running on the same machine.

  • 3 bytes incrementing value

    Each time an id is created, a global counter is incremented and used as the increment value of the next id.

Thus, no two records can have the same id unless a single process on a single machine managed to insert 256^3 (over 16 million) documents in one second, overflowing the increment field. 		12
MongoMinKey | Always smaller than any other value. | String length of code + object size of scope.
MongoMaxKey | JavaScript code. | Always larger than any other value.
MongoRegex | Regular expressions. | Number of characters in regular expression + number of flags
MongoTimestamp | Sharding timestamp | 8

Unsupported Types

Types supported by Mongo, but not the PHP driver:

Type | Description | Size in MongoDB (bytes)
long | As PHP does not support 8 byte integers, longs fetched from the database are converted to doubles. Integers will always be saved to the database as 4 byte ints (even on machines that support 8 byte ints) and doubles will be saved as 8 bytes doubles, so there is no way to save a long to the database with the PHP driver. | 8

MongoCursor::valid
MongoId
Mongo


Updates

Updates can be one of the the most complicated operation available with MongoDB. They combine a query with an action, modifying documents that match the criteria. They are also extremely powerful, allowing you to change documents quickly and replace them altogether. They are done in-place (when possible) with little overhead.

Updating Nested Objects

Suppose we wish to change the name of a comment's author in this document:

{
    "_id" : ObjectId("4b06c282edb87a281e09dad9"),
    "content" : "this is a blog post.",
    "comments" :
    [
        {
            "author" : "Mike",
            "comment" : "I think that blah blah blah...",
        },
        {
            "author" : "John",
            "comment" : "I disagree."
        }
    ]
}

In order to change an inner field, we use $set (so that all of the other fields are not removed!) with the index of comment to change:

<?php

$blog->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));

?>

Querying
Troubleshooting
Manual


Creates a new binary data object.

MongoBinData
MongoBinData::__toString
MongoBinData
PHP Manual

MongoBinData::__construct

(PECL mongo >= 0.8.1)

MongoBinData::__construct — Creates a new binary data object.

Description

public MongoBinData::__construct ( string $data [, int $type ] )

Creates a new binary data object.

There are five types of binary data currently recognized by the BSON spec: function (0x01), byte array (0x02), UUID (0x03), MD5 (0x05), and user defined (0x80). The default type is byte array (0x02). There is no particular difference in how the driver or server interpret different types, so by and large they are irrelevant for now. Any number (between 0 and 255) could be used for type, if the user is willing to assume the risk that the database might eventually do something with binary data based on type.

Parameters

data

Binary data.

type

Data type.

Return Values

Returns a new binary data object.

MongoBinData
MongoBinData::__toString
MongoBinData


The string representation of this binary data object.

MongoBinData::__construct
MongoDBRef
MongoBinData
PHP Manual

MongoBinData::__toString

(PECL mongo >= 0.8.1)

MongoBinData::__toString — The string representation of this binary data object.

Description

public string MongoBinData::__toString ( void )

Parameters

This function has no parameters.

Return Values

Returns the string "<Mongo Binary Data>". To access the contents of a MongoBinData, use the bin field.

MongoBinData::__construct
MongoDBRef
MongoBinData


Creates a new code object

MongoCode
MongoCode::__toString
MongoCode
PHP Manual

MongoCode::__construct

(PECL mongo >= 0.8.3)

MongoCode::__construct — Creates a new code object

Description

MongoCode::__construct ( string $code [, array $scope = array() ] )

Parameters

code

A string of code.

scope

The scope to use for the code.

Return Values

Returns a new code object.

Examples

Example #1 MongoCode::__construct() example

<?php

$code = new MongoCode('function() { '.
    'for(i=0;i<10;i++) {'.
        'db.foo.update({z : i}, {z : x});'.
    '}'.
    'return x-1;'.
 '}', array("x" => 4));
var_dump($code);

?>

The above example will output something similar to:

object(MongoCode)#1 (2) {
  ["scope"]=>
  array(1) {
    ["x"]=>
    int(4)
  }
  ["code"]=>
  string(80) "function() { for(i=0;i<10;i++) { db.foo.update({z : i}, {z : x}); } return x-1; }"
}

Example #2 Using MongoCode() with $where

This example queries a collection for elements where the 'x' fields is less than $y. Notice that PHP objects can be passed into the JavaScript scope and that the JavaScript function returns a boolean.

<?php

$cursor = $collection->find(array('$where' => new MongoCode('function() { return this.x < y; }', array('y'=>$y))));

?>
MongoCode
MongoCode::__toString
MongoCode


Returns this code as a string

MongoCode::__construct
MongoDate
MongoCode
PHP Manual

MongoCode::__toString

(PECL mongo >= 0.8.3)

MongoCode::__toString — Returns this code as a string

Description

public string MongoCode::__toString ( void )

Parameters

This function has no parameters.

Return Values

This code, the scope is not returned.

Examples

Example #1 MongoCode::__toString() example

<?php

$code = new MongoCode('return x;', array("x"=>"hi"));
echo "$code\n";

$code = new MongoCode('function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }');
echo "$code\n";

?>

The above example will output something similar to:

return x;
function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }
MongoCode::__construct
MongoDate
MongoCode


String representation of this collection

MongoCollection::save
MongoCollection::update
MongoCollection
PHP Manual

MongoCollection::__toString

(PECL mongo >=0.9.0)

MongoCollection::__toString — String representation of this collection

Description

public string MongoCollection::__toString ( void )

Parameters

This function has no parameters.

Return Values

Returns the full name of this collection.

Examples

Example #1 MongoCollection::__toString() example

<?php

$m = new Mongo();

$c1 = $m->foo->bar->baz;
echo "Working with collection $c1.";

$c2 = $m->selectCollection('[]', '&');
echo "Working with collection $c2.";

?>

The above example will output something similar to:

Working with collection foo.bar.baz.
Working with collection [].&.

MongoCollection::save
MongoCollection::update
MongoCollection


Inserts multiple documents into this collection

MongoCollection
MongoCollection::__construct
MongoCollection
PHP Manual

MongoCollection::batchInsert

(PECL mongo >=0.9.0)

MongoCollection::batchInsert — Inserts multiple documents into this collection

Description

public boolean MongoCollection::batchInsert ( array $a )

Parameters

a

An array of arrays.

Return Values

Returns if the arrays were saved.

Examples

Example #1 MongoCollection::batchInsert() example

Batch insertion is a quick way to add many elements to the database at once

<?php
$batch = array();
for ($i=0; $i<100; $i++) {
  $batch[] = array("i" => i);
}

$m = new Mongo();
$c = $m->foo->bar->baz;
$c->batchInsert($batch);

$cursor = $c->find()->sort(array("i" => 1));
while ($cursor->hasNext()) {
  $obj = $cursor->next();
  var_dump($obj["i"]);
}
?>

The above example will output something similar to:

int(0)
int(1)
int(2)
...
MongoCollection
MongoCollection::__construct
MongoCollection


Creates a new collection

MongoCollection::batchInsert
MongoCollection::count
MongoCollection
PHP Manual

MongoCollection::__construct

(PECL mongo >=0.9.0)

MongoCollection::__construct — Creates a new collection

Description

public MongoCollection::__construct ( MongoDB $db , string $name )

Parameters

MongoDB db

Parent database.

name

Name for this collection.

Return Values

Returns a new collection object.

Errors/Exceptions

Throws InvalidArgumentException if the collection name is invalid.

MongoCollection::batchInsert
MongoCollection::count
MongoCollection


Counts the number of documents in this collection

MongoCollection::__construct
MongoCollection::createDBRef
MongoCollection
PHP Manual

MongoCollection::count

(PECL mongo >=0.9.0)

MongoCollection::count — Counts the number of documents in this collection

Description

public int MongoCollection::count ([ mixed $query = array() ] )

Parameters

query

Array or object with fields to match.

Return Values

Returns the number of documents matching the query.

Examples

Example #1 MongoCollection::count() example

<?php

$collection->insert(array('x'=>1));
$collection->insert(array('x'=>2));
$collection->insert(array('x'=>3));

var_dump($collection->count());
var_dump($collection->count(array('x'=>1)));

?>

The above example will output something similar to:

int(3)
int(1)
MongoCollection::__construct
MongoCollection::createDBRef
MongoCollection


Creates a database reference

MongoCollection::count
MongoCollection::deleteIndex
MongoCollection
PHP Manual

MongoCollection::createDBRef

(PECL mongo >=0.9.0)

MongoCollection::createDBRef — Creates a database reference

Description

public array MongoCollection::createDBRef ( array $a )

Parameters

a

Object to which to create a reference.

Return Values

Returns a database reference array.

Examples

Example #1 MongoCollection::createDBRef() example

<?php

$songs = $db->songs;
$playlists = $db->playlists;

// create a reference to a song
$manamana = $songs->findOne(array('title' => 'Ma na ma na'));
$refToSong = $songs->createDBRef($manamana);

// add the reference to my playlist
$playlists->update(array('username' => 'me'), array('$push' => array('songlist' => $refToSong)));

?>

See Also

  • MongoCollection::getDBRef - Fetches the document pointed to by a database reference

MongoCollection::count
MongoCollection::deleteIndex
MongoCollection


Deletes an index from this collection

MongoCollection::createDBRef
MongoCollection::deleteIndexes
MongoCollection
PHP Manual

MongoCollection::deleteIndex

(PECL mongo >=0.9.0)

MongoCollection::deleteIndex — Deletes an index from this collection

Description

public array MongoCollection::deleteIndex ( string|array $keys )

Parameters

keys

Field or fields from which to delete the index.

Return Values

Returns the database response.

Examples

Example #1 MongoCollection::deleteIndex() example

This example passes the function string and array parameters.

<?php
$m = new Mongo();
$c = $m->example->indices;

// create an index
$c->ensureIndex(array("i"=>1));

// remove a simple index
$c->deleteIndex("i");

// create a multi-key index
$c->ensureIndex(array("j" => 1, "k" => 1));

// remove a multi-key index
$c->deleteIndex(array("j" => 1, "k" => 1));
?>
MongoCollection::createDBRef
MongoCollection::deleteIndexes
MongoCollection


Delete all indices for this collection

MongoCollection::deleteIndex
MongoCollection::drop
MongoCollection
PHP Manual

MongoCollection::deleteIndexes

(PECL mongo >=0.9.0)

MongoCollection::deleteIndexes — Delete all indices for this collection

Description

public array MongoCollection::deleteIndexes ( void )

Parameters

This function has no parameters.

Return Values

Returns the database response.

MongoCollection::deleteIndex
MongoCollection::drop
MongoCollection


Drops this collection

MongoCollection::deleteIndexes
MongoCollection::ensureIndex
MongoCollection
PHP Manual

MongoCollection::drop

(PECL mongo >=0.9.0)

MongoCollection::drop — Drops this collection

Description

public array MongoCollection::drop ( void )

Drops this collection and deletes its indices.

Parameters

This function has no parameters.

Return Values

Returns the database response.

MongoCollection::deleteIndexes
MongoCollection::ensureIndex
MongoCollection


Creates an index on the given field(s), or does nothing if the index already exists

MongoCollection::drop
MongoCollection::find
MongoCollection
PHP Manual

MongoCollection::ensureIndex

(PECL mongo >=0.9.0)

MongoCollection::ensureIndex — Creates an index on the given field(s), or does nothing if the index already exists

Description

public boolean MongoCollection::ensureIndex ( array $keys , array $options )

A unique index cannot be created on a field if multiple existing documents do not contain the field. The field is effectively NULL for these documents and thus already non-unique.

Parameters

keys

Field or fields to use as index.

options

This parameter is an associative array of the form array("optionname" => <boolean>, ...). Currently supported options are:

  • "unique"

    Create a unique index.

  • "dropDups"

    If a unique index is being created and duplicate values exist, drop all but one duplicate value.

  • "background"

    If you are using MongoDB version 1.3.2+, you can create indexes in the background while other operations are taking place. By default, index creation happens synchronously. If you specify TRUE with this option, index creation will be asynchronous.

Return Values

Returns TRUE.

Changelog

Version | Description
1.0.2 | Changed "options" parameter from boolean to array. Pre-1.0.2, the second parameter was an optional boolean value specifying a unique index.

Examples

Example #1 MongoCollection::ensureIndex() example

<?php

$c = new MongoCollection($db, 'foo');

// create an index on 'x' ascending
$c->ensureIndex(array('x' => 1));

// create an index on 'z' ascending and 'zz' descending
$c->ensureIndex(array('z' => 1, 'zz' => -1));

// create a unique index on 'x'
$c->ensureIndex(array('x' => 1), array("unique" => true));

?>

Example #2 Drop duplicates example

<?php

$collection->insert(array("username" => "joeschmoe"));
$collection->insert(array("username" => "joeschmoe"));

/*
 * index creation fails, you can't create a unique index on a key with
 * non-unique values
 */
$collection->ensureIndex(array("username" => 1), array("unique" => 1));

/*
 * index creation succeeds: one of the documents is removed from the collection
 */
$collection->ensureIndex(array("username" => 1), array("unique" => 1, "dropDups" => 1));

/*
 * now we have a unique index, more inserts with the same username (such as the
 * one below) will fail
 */
$collection->insert(array("username" => "joeschmoe"));

?>

See Also

MongoDB core docs on » indexes.

MongoCollection::drop
MongoCollection::find
MongoCollection


Querys this collection

MongoCollection::ensureIndex
MongoCollection::findOne
MongoCollection
PHP Manual

MongoCollection::find

(PECL mongo >=0.9.0)

MongoCollection::find — Querys this collection

Description

 public MongoCursor MongoCollection::find
  ([ array $query = array()
 [, array $fields = array()
]] )

Parameters

query

The fields for which to search.

fields

Fields of the results to return.

Return Values

Returns a cursor for the search results.

Examples

Example #1 MongoCollection::find() example

This example demonstrates how to search for a range.

<?php

// search for documents where 5 < x < 20
$rangeQuery = array('x' => array( '$gt' => 5, '$lt' => 20 ));

$cursor = $collection->find($rangeQuery);

?>

See Also

MongoDB core docs on » find.

MongoCollection::ensureIndex
MongoCollection::findOne
MongoCollection


Querys this collection, returning a single element

MongoCollection::find
MongoCollection::__get
MongoCollection
PHP Manual

MongoCollection::findOne

(PECL mongo >=0.9.0)

MongoCollection::findOne — Querys this collection, returning a single element

Description

 public array MongoCollection::findOne
  ([ array $query = array()
 [, array $fields = array()
]] )

Parameters

query

The fields for which to search.

fields

Fields of the results to return.

Return Values

Returns record matching the search or NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

MongoCollection::find
MongoCollection::__get
MongoCollection


Gets a collection

MongoCollection::findOne
MongoCollection::getDBRef
MongoCollection
PHP Manual

MongoCollection::__get

(PECL mongo >=1.0.2)

MongoCollection::__get — Gets a collection

Description

public MongoCollection MongoCollection::__get ( string $name )

A concise syntax for getting a collection with a dot-separated name. If a collection name contains strange characters, you may have to use MongoDB::selectCollection() instead.

<?php

$mongo = new Mongo();

// the following two lines are equivalent
$collection = $mongo->selectDB("foo")->selectCollection("bar.baz");
$collection = $mongo->foo->bar->baz;

?>

Parameters

name

The next string in the collection name.

Return Values

Returns the collection.

MongoCollection::findOne
MongoCollection::getDBRef
MongoCollection


Fetches the document pointed to by a database reference

MongoCollection::__get
MongoCollection::getIndexInfo
MongoCollection
PHP Manual

MongoCollection::getDBRef

(PECL mongo >=0.9.0)

MongoCollection::getDBRef — Fetches the document pointed to by a database reference

Description

public array MongoCollection::getDBRef ( array $ref )

Parameters

ref

A database reference.

Return Values

Returns the database document pointed to by the reference.

Examples

Example #1 MongoCollection::createDBRef() example

<?php

$playlists = $db->playlists;

$myList = $playlists->findOne(array('username' => 'me'));

// fetch each song in the playlist
foreach ($myList['songlist'] as $songRef) {
    $song = $playlists->getDBRef($songRef);
    echo $song['title'] . "\n";
}

?>

The above example will output something similar to:

Dazed and Confused
Ma na ma na
Bohemian Rhapsody

See Also

  • MongoCollection::createDBRef - Creates a database reference

MongoCollection::__get
MongoCollection::getIndexInfo
MongoCollection


Returns an array of index names for this collection

MongoCollection::getDBRef
MongoCollection::getName
MongoCollection
PHP Manual

MongoCollection::getIndexInfo

(PECL mongo >=0.9.0)

MongoCollection::getIndexInfo — Returns an array of index names for this collection

Description

public array MongoCollection::getIndexInfo ( void )

Parameters

This function has no parameters.

Return Values

Returns a list of index names.

MongoCollection::getDBRef
MongoCollection::getName
MongoCollection


Returns this collection's name

MongoCollection::getIndexInfo
MongoCollection::group
MongoCollection
PHP Manual

MongoCollection::getName

(PECL mongo >=0.9.0)

MongoCollection::getName — Returns this collection's name

Description

public string MongoCollection::getName ( void )

Parameters

This function has no parameters.

Return Values

Returns the name of this collection.

Examples

Example #1 MongoCollection::getName() example

<?php

$m = new Mongo();
$c = $m->foo->bar->baz;

echo "Working with collection " . $c->getName() . ".\n";

// the full namespace is given by the MongoCollection::__toString() method
echo "Working in namespace $c.\n";

?>

The above example will output something similar to:

Working with collection bar.baz.
Working in namespace foo.bar.baz.

MongoCollection::getIndexInfo
MongoCollection::group
MongoCollection


Performs an operation similar to SQL's GROUP BY command

MongoCollection::getName
MongoCollection::insert
MongoCollection
PHP Manual

MongoCollection::group

(PECL mongo >=0.9.2)

MongoCollection::group — Performs an operation similar to SQL's GROUP BY command

Description

public array MongoCollection::group ( array $keys , array $initial , string $reduce [, array $condition = array() ] )

Parameters

keys

Fields to group by.

initial

Initial value of the aggregation counter object.

reduce

A function that aggregates (reduces) the objects iterated.

condition

An condition that must be true for a row to be considered.

Return Values

Returns an array containing the result.

Examples

Example #1 MongoCollection::group() example

<?php

$collection->save(array("a" => 2));
$collection->save(array("b" => 5));
$collection->save(array("a" => 1));

// use all fields
$keys = array();

// set intial values
$initial = array("count" => 0);

// JavaScript function to perform
$reduce = "function (obj, prev) { prev.count++; }";

// only use documents where the "a" field is greater than 1
$condition = array("a" => array( '$gt' => 1));

$g = $collection->group($keys, $initial, $reduce, $condition);

var_dump($g);

?>

The above example will output something similar to:

array(4) {
  ["retval"]=>
  array(1) {
    [0]=>
    array(1) {
      ["count"]=>
      float(1)
    }
  }
  ["count"]=>
  float(1)
  ["keys"]=>
  int(1)
  ["ok"]=>
  float(1)
}
MongoCollection::getName
MongoCollection::insert
MongoCollection


Inserts an array into the collection

MongoCollection::group
MongoCollection::remove
MongoCollection
PHP Manual

MongoCollection::insert

(PECL mongo >=0.9.0)

MongoCollection::insert — Inserts an array into the collection

Description

public mixed MongoCollection::insert ( array $a [, boolean $safe = false ] )

Parameters

a

An array.

safe

If the database should check that the insert was successful.

Return Values

If safe was set, returns an array containing the status of the insert. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).

Errors/Exceptions

Throws MongoCursorException if safe is set and the insert fails. (Version 1.0.1+)

Examples

Example #1 MongoCollection::insert() _id example

Inserting an object will add an _id field to it, unless it is passed by reference.

<?php

$a = array('x' => 1);
$collection->insert($a);
var_dump($a)

$b = array('x' => 1);
$ref = &$b;
$collection->insert($ref);
var_dump($ref);

?>

The above example will output something similar to:

array(2) {
  ["x"]=>
  int(1)
  ["_id"]=>
  object(MongoId)#4 (0) {
  }
}
array(1) {
  ["x"]=>
  int(1)
}

Example #2 MongoCollection::insert() safe example

This example shows inserting two elements with the same _id, which causes a MongoCursorException to be thrown, as safe was set.

<?php

$person = array("name" => "Joe", "age" => 20);
$collection->insert($person, true);

// now $person has an _id field, so if we save it
// again, we will get an exception
try {
    $collection->insert($person, true);
}
catch(MongoCursorException $e) {
    echo "Can't save the same person twice!\n";
}

?>

See Also

MongoDB core docs on » insert.

MongoCollection::group
MongoCollection::remove
MongoCollection


Remove records from this collection

MongoCollection::insert
MongoCollection::save
MongoCollection
PHP Manual

MongoCollection::remove

(PECL mongo >=0.9.0)

MongoCollection::remove — Remove records from this collection

Description

public boolean MongoCollection::remove ( array $criteria [, boolean $justOne = FALSE ] )

Parameters

criteria

Description of records to remove.

justOne

Remove at most one record matching this criteria.

Return Values

Returns if the command was executed successfully.

Examples

Example #1 MongoCollection::remove() with justOne example

<?php

$radioactive = $db->radioactive;

// count how much more plutonium there is
$remaining = $radioactive->count(array('type' => 94));

$halflife = $remaining/2;

// remove half of it
while ($halflife > 0) {
    $uranium->remove(array('type' => 94), true);
    $halflife--;
}

?>

See Also

MongoDB core docs on » remove.

MongoCollection::insert
MongoCollection::save
MongoCollection


Saves an object to this collection

MongoCollection::remove
MongoCollection::__toString
MongoCollection
PHP Manual

MongoCollection::save

(PECL mongo >=0.9.0)

MongoCollection::save — Saves an object to this collection

Description

public boolean MongoCollection::save ( array $a )

If the object is from the database, update the existing database object, otherwise insert this object.

Parameters

a

Array to save.

Return Values

Returns if the object was saved.

Examples

Example #1 MongoCollection::save() example

<?php

$obj = array('x' => 1);

// insert $obj into the db
$collection->save($obj);

// add another field
$obj['foo'] = 'bar';

// $obj cannot be inserted again, causes duplicate _id error
$collection->insert($obj);

// save updates $obj with the new field
$collection->save($obj);

?>
MongoCollection::remove
MongoCollection::__toString
MongoCollection


Update records based on a given criteria

MongoCollection::__toString
MongoCollection::validate
MongoCollection
PHP Manual

MongoCollection::update

(PECL mongo >=0.9.0)

MongoCollection::update — Update records based on a given criteria

Description

public boolean MongoCollection::update ( array $criteria , array $newobj [, array $options = NULL ] )

Parameters

criteria

Description of the objects to update.

newobj

The object with which to update the matching records.

options

This parameter is an associative array of the form array("optionname" => <boolean>, ...). Currently supported options are:

  • "upsert"

    If no document matches $criteria, a new document will be created from $criteria and $newobj (see upsert example below).

  • "multiple"

    All documents matching $criteria will be updated. MongoCollection::update() has exactly the opposite behavior of MongoCollection::remove(): it updates one document by default, not all matching documents. It is recommended that you always specify whether you want to update multiple documents or a single document, as the database may change its default behavior at some point in the future.

Return Values

Returns if the update was successfully sent to the database.

Changelog

Version | Description
1.0.1 | Changed "options" parameter from boolean to array. Pre-1.0.1, the second parameter was an optional boolean value specifying an upsert.

Examples

Example #1 MongoCollection::update()

Adding an address field to a document.

<?php

$c->insert(array("firstname" => "Bob", "lastname" => "Jones" ));
$newdata = array('$set' => array("address" => "1 Smith Lane"));
$c->update(array("firstname" => "Bob"), $newdata);

var_dump($c->findOne(array("firstname" => "Bob")));

?>

The above example will output something similar to:

array(4) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["firstname"]=>
  string(3) "Bob"
  ["lastname"]=>
  string(5) "Jones"
  ["address"]=>
  string(12) "1 Smith Lane"
}

Example #2 MongoCollection::update() upsert example

Upserts can simplify code, as a single line can create the object if it does not exist yet and update it if it does.

<?php

$c->drop();
$c->update(array("uri" => "/summer_pics"), array('$inc' => array("page hits" => 1)), array("upsert" => true));
var_dump($c->findOne());

?>

The above example will output something similar to:

array(3) {
  ["_id"]=>
  object(MongoId)#9 (0) {
  }
  ["uri"]=>
  string(12) "/summer_pics"
  ["page hits"]=>
  int(1)
}

Example #3 MongoCollection::update() multiple example

By default, MongoCollection::update() will only update the first document matching $criteria that it finds. Using the "multiple" option can override this behavior, if needed.

This example adds a "gift" field to every person whose birthday is in the next day.

<?php

$today = array('$gt' => new MongoDate(), '$lt' => new MongoDate(strtotime("+1 day")));
$people->update("birthday" => $today), array('$set' => array('gift' => $surprise), array("multiple" => true));

?>

See Also

MongoDB core docs on » update.

MongoCollection::__toString
MongoCollection::validate
MongoCollection


Validates this collection

MongoCollection::update
MongoCursor
MongoCollection
PHP Manual

MongoCollection::validate

(PECL mongo >=0.9.0)

MongoCollection::validate — Validates this collection

Description

public array MongoCollection::validate ([ bool $scan_data = FALSE ] )

Parameters

scan_data

Only validate indices, not the base collection.

Return Values

Returns the database's evaluation of this object.

MongoCollection::update
MongoCursor
MongoCollection


Adds a top-level key/value pair to a query

MongoCursor
MongoCursor::__construct
MongoCursor
PHP Manual

MongoCursor::addOption

(PECL mongo >=1.0.4)

MongoCursor::addOption — Adds a top-level key/value pair to a query

Description

public MongoCursor MongoCursor::addOption ( string $key , mixed $value )

This is an advanced function and should not be used unless you know what you're doing.

A query can optionally be nested in a "query" field if other options, such as a sort or hint, are given. For instance, adding a sort causes the query to become a subfield of a bigger query object, like:

<?php

$query = array("query" => $query, "orderby" => $sort);

?>

This method is for adding a top-level field to a query. It makes the query a subobject (if it isn't already) and adds the key/value pair of your chosing to the top level.

Warning

It cannot be used to add extra criteria to a query on the fly. For instance, this will not work:

<?php

// NOT CORRECT
$cursor = $users->find()->addOption("name", "joe")->addOption("age", 20);

?>

This does not query for a user named "joe" with an age of 20.

Parameters

key

Fieldname to add.

value

Value to add.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::addOption() example

Using MongoCursor::skip() to skip over millions of results can become slow. One way around this is to use $min or $max options for the query. These can be handy, but they require an index on exactly the fields being searched for. This is an example of how to use $min as an alternative to MongoCursor::skip().

<?php

// make sure we have an index
$c->ensureIndex(array("ts" => 1));

// you may have to modify this to run in a reasonable amount of time on slow
// machines (should take about 30 seconds on a good machine)
for ($i = 0; $i < 30000000; $i++) {
    $c->insert(array("ts" => new MongoDate(), "i" => $i));
}

$now = strtotime("now");

// find documents inserted in the last 2 seconds
$cursor = $c->find()->addOption('$min', array("ts" => $now-2));

?>
MongoCursor
MongoCursor::__construct
MongoCursor


Create a new cursor

MongoCursor::addOption
MongoCursor::count
MongoCursor
PHP Manual

MongoCursor::__construct

(PECL mongo >=0.9.0)

MongoCursor::__construct — Create a new cursor

Description

MongoCursor::__construct ( resource $connection , string $ns [, array $query = array() [, array $fields = array() ]] )

Parameters

connection

Database connection.

ns

Full name of database and collection.

query

Database query.

fields

Fields to return.

Return Values

Returns the new cursor.

MongoCursor::addOption
MongoCursor::count
MongoCursor


Counts the number of results for this query

MongoCursor::__construct
MongoCursor::current
MongoCursor
PHP Manual

MongoCursor::count

(PECL mongo >=0.9.2)

MongoCursor::count — Counts the number of results for this query

Description

public int MongoCursor::count ([ boolean $all = FALSE ] )

Parameters

all

Send cursor limit and skip information to the count function, if applicable.

Return Values

The number of documents returned by this cursor's query.

Examples

Example #1 MongoCursor::count() example

<?php

$collection->insert(array('x'=>1));
$collection->insert(array('x'=>2));
$collection->insert(array('x'=>3));

$cursor = $collection->find();

var_dump($cursor->count());
var_dump($cursor->count(true));

$cursor->limit(2);

var_dump($cursor->count());
var_dump($cursor->count(true));

?>

The above example will output something similar to:

int(3)
int(3)
int(3)
int(2)

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

MongoCursor::__construct
MongoCursor::current
MongoCursor


Returns the current element

MongoCursor::count
MongoCursor::dead
MongoCursor
PHP Manual

MongoCursor::current

(PECL mongo >=0.9.0)

MongoCursor::current — Returns the current element

Description

public array MongoCursor::current ( void )

This field is NULL until MongoCursor::next() is called.

Parameters

This function has no parameters.

Return Values

The current result as an associative array.

MongoCursor::count
MongoCursor::dead
MongoCursor


Checks if there are documents that have not been sent yet from the database for this cursor

MongoCursor::current
MongoCursor::doQuery
MongoCursor
PHP Manual

MongoCursor::dead

(PECL mongo >=0.9.6)

MongoCursor::dead — Checks if there are documents that have not been sent yet from the database for this cursor

Description

public boolean MongoCursor::dead ( void )

The database sends responses in batches of documents, up to 4Mb of documents per response. This method checks if the database has more batches or if the result set has been exhausted.

A cursor being "dead" does not mean that MongoCursor::hasNext() will return FALSE, it only means that the database is done sending results to the client. The client should continue iterating through results until MongoCursor::hasNext() is FALSE.

Parameters

This function has no parameters.

Return Values

Returns if there are more results that have not been sent to the client, yet.

MongoCursor::current
MongoCursor::doQuery
MongoCursor


Execute the query.

MongoCursor::dead
MongoCursor::explain
MongoCursor
PHP Manual

MongoCursor::doQuery

(No version information available, might only be in SVN)

MongoCursor::doQuery — Execute the query.

Description

protected void MongoCursor::doQuery ( void )

Parameters

This function has no parameters.

Return Values

NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

MongoCursor::dead
MongoCursor::explain
MongoCursor


Return an explanation of the query, often useful for optimization and debugging

MongoCursor::doQuery
MongoCursor::getNext
MongoCursor
PHP Manual

MongoCursor::explain

(PECL mongo >=0.9.2)

MongoCursor::explain — Return an explanation of the query, often useful for optimization and debugging

Description

public array MongoCursor::explain ( void )

Parameters

This function has no parameters.

Return Values

Returns an explanation of the query.

Examples

Example #1 MongoCursor::explain() example

<?php

$cursor = $collection->find(array("x"=>1), array("y"))
$cursor->sort(array("z" => 1))->limit(4)->skip(5);

var_dump($cursor->explain());

?>

The above example will output something similar to:

array(8) {
  ["cursor"]=>
  string(15) "BtreeCursor x_1"
  ["startKey"]=>
  array(1) {
    ["x"]=>
    int(1)
  }
  ["endKey"]=>
  array(1) {
    ["x"]=>
    int(1)
  }
  ["nscanned"]=>
  float(4)
  ["n"]=>
  int(4)
  ["scanAndOrder"]=>
  int(1)
  ["millis"]=>
  int(3)
  ["allPlans"]=>
  array(2) {
    [0]=>
    array(3) {
      ["cursor"]=>
      string(15) "BtreeCursor x_1"
      ["startKey"]=>
      array(1) {
        ["x"]=>
        int(1)
      }
      ["endKey"]=>
      array(1) {
        ["x"]=>
        int(1)
      }
    }
    [1]=>
    array(3) {
      ["cursor"]=>
      string(11) "BasicCursor"
      ["startKey"]=>
      array(0) {
      }
      ["endKey"]=>
      array(0) {
      }
    }
  }
}

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

See Also

MongoDB core docs on » explain.

MongoCursor::doQuery
MongoCursor::getNext
MongoCursor


Return the next object to which this cursor points, and advance the cursor

MongoCursor::explain
MongoCursor::hasNext
MongoCursor
PHP Manual

MongoCursor::getNext

(PECL mongo >=0.9.0)

MongoCursor::getNext — Return the next object to which this cursor points, and advance the cursor

Description

public array MongoCursor::getNext ( void )

This equivalent to calling MongoCursor::next(), then MongoCursor::current().

Parameters

This function has no parameters.

Return Values

Returns the next object.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

MongoCursor::explain
MongoCursor::hasNext
MongoCursor


Checks if there are any more elements in this cursor

MongoCursor::getNext
MongoCursor::hint
MongoCursor
PHP Manual

MongoCursor::hasNext

(PECL mongo >=0.9.0)

MongoCursor::hasNext — Checks if there are any more elements in this cursor

Description

public boolean MongoCursor::hasNext ( void )

Parameters

This function has no parameters.

Return Values

Returns if there is another element.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

MongoCursor::getNext
MongoCursor::hint
MongoCursor


Gives the database a hint about the query

MongoCursor::hasNext
MongoCursor::immortal
MongoCursor
PHP Manual

MongoCursor::hint

(PECL mongo >=0.9.0)

MongoCursor::hint — Gives the database a hint about the query

Description

public MongoCursor MongoCursor::hint ( array $key_pattern )

Parameters

key_pattern

Indexes to use for the query.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

MongoCursor::hasNext
MongoCursor::immortal
MongoCursor


Sets whether this cursor will timeout

MongoCursor::hint
MongoCursor::key
MongoCursor
PHP Manual

MongoCursor::immortal

(PECL mongo >=1.0.1)

MongoCursor::immortal — Sets whether this cursor will timeout

Description

public MongoCursor MongoCursor::immortal ([ boolean $liveForever = true ] )

After remaining idle for some amount of time, cursor, by default, "die." This is generally the behavior one wants. The database cleans up a cursor once all of its results have been sent to the client, but if the client doesn't request all of the results, the cursor will languish there, taking up resources. Thus, after a few minutes, the cursor "times out" and the database assumes the client has gotten everything it needs and cleans up its the cursor's resources.

If, for some reason, you need a cursor to hang around for a long time, you can prevent the database from cleaning it up by using this method. However, if you make a cursor immortal, you need to iterate through all of its results (or at least until Cursor::dead() returns TRUE) or the cursor will hang around the database forever, taking up resources.

Parameters

liveForever

If the cursor should be immortal.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

MongoCursor::hint
MongoCursor::key
MongoCursor


Returns the current result's _id

MongoCursor::immortal
MongoCursor::limit
MongoCursor
PHP Manual

MongoCursor::key

(PECL mongo >=0.9.0)

MongoCursor::key — Returns the current result's _id

Description

public string MongoCursor::key ( void )

Parameters

This function has no parameters.

Return Values

The current result's _id as a string.

MongoCursor::immortal
MongoCursor::limit
MongoCursor


Limits the number of results returned

MongoCursor::key
MongoCursor::next
MongoCursor
PHP Manual

MongoCursor::limit

(PECL mongo >=0.9.0)

MongoCursor::limit — Limits the number of results returned

Description

public MongoCursor MongoCursor::limit ( int $num )

Parameters

num

The number of results to return.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

See Also

MongoDB core docs on » limit.

MongoCursor::key
MongoCursor::next
MongoCursor


Advances the cursor to the next result

MongoCursor::limit
MongoCursor::reset
MongoCursor
PHP Manual

MongoCursor::next

(PECL mongo >=0.9.0)

MongoCursor::next — Advances the cursor to the next result

Description

public void MongoCursor::next ( void )

Parameters

This function has no parameters.

Return Values

NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

MongoCursor::limit
MongoCursor::reset
MongoCursor


Clears the cursor

MongoCursor::next
MongoCursor::rewind
MongoCursor
PHP Manual

MongoCursor::reset

(PECL mongo >=0.9.0)

MongoCursor::reset — Clears the cursor

Description

public void MongoCursor::reset ( void )

Parameters

This function has no parameters.

Return Values

NULL.

MongoCursor::next
MongoCursor::rewind
MongoCursor


Returns the cursor to the beginning of the result set

MongoCursor::reset
MongoCursor::skip
MongoCursor
PHP Manual

MongoCursor::rewind

(PECL mongo >=0.9.0)

MongoCursor::rewind — Returns the cursor to the beginning of the result set

Description

public void MongoCursor::rewind ( void )

Parameters

This function has no parameters.

Return Values

NULL.

MongoCursor::reset
MongoCursor::skip
MongoCursor


Skips a number of results

MongoCursor::rewind
MongoCursor::slaveOkay
MongoCursor
PHP Manual

MongoCursor::skip

(PECL mongo >=0.9.0)

MongoCursor::skip — Skips a number of results

Description

public MongoCursor MongoCursor::skip ( int $num )

Parameters

num

The number of results to skip.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

MongoCursor::rewind
MongoCursor::slaveOkay
MongoCursor


Sets whether this query can be done on a slave

MongoCursor::skip
MongoCursor::snapshot
MongoCursor
PHP Manual

MongoCursor::slaveOkay

(PECL mongo >=0.9.4)

MongoCursor::slaveOkay — Sets whether this query can be done on a slave

Description

public MongoCursor MongoCursor::slaveOkay ([ boolean $okay = true ] )

This method will override the static class variable slaveOkay.

Parameters

okay

If it is okay to query the slave.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::slaveOkay() example

<?php

MongoCursor::$slaveOkay = false;

// cannot query slave
$cursor = $collection->find();

// can query slave
$cursor = $collection->find()->slaveOkay();

MongoCursor::$slaveOkay = true;

// can query slave
$cursor = $collection->find();

// cannot query slave
$cursor = $collection->find()->slaveOkay(false);

?>
MongoCursor::skip
MongoCursor::snapshot
MongoCursor


Use snapshot mode for the query

MongoCursor::slaveOkay
MongoCursor::sort
MongoCursor
PHP Manual

MongoCursor::snapshot

(PECL mongo >=0.9.4)

MongoCursor::snapshot — Use snapshot mode for the query

Description

public MongoCursor MongoCursor::snapshot ( void )

Use snapshot mode for the query. Snapshot mode assures no duplicates are returned, or objects missed, which were present at both the start and end of the query's execution (if an object is new during the query, or deleted during the query, it may or may not be returned, even with snapshot mode).

Note that short query responses (less than 1MB) are always effectively snapshotted.

Currently, snapshot mode may not be used with sorting or explicit hints.

Parameters

This function has no parameters.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

MongoCursor::slaveOkay
MongoCursor::sort
MongoCursor


Sorts the results by given fields

MongoCursor::snapshot
MongoCursor::tailable
MongoCursor
PHP Manual

MongoCursor::sort

(PECL mongo >=0.9.0)

MongoCursor::sort — Sorts the results by given fields

Description

public MongoCursor MongoCursor::sort ( array $fields )

Parameters

fields

The fields by which to sort.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::sort() example

<?php
// sort x ascending
$cursor->sort(array('x' => 1));

// the associative array is ordered, for instance, these two
// examples might yield different results:

// sort date ascending and age descending
$cursor->sort(array('date' => 1, 'age' => -1));

// sort age descending and date ascending
$cursor->sort(array('age' => -1, 'date' => 1));
?>
MongoCursor::snapshot
MongoCursor::tailable
MongoCursor


Sets whether this cursor will be left open after fetching the last results

MongoCursor::sort
MongoCursor::timeout
MongoCursor
PHP Manual

MongoCursor::tailable

(PECL mongo >=0.9.4)

MongoCursor::tailable — Sets whether this cursor will be left open after fetching the last results

Description

public MongoCursor MongoCursor::tailable ([ boolean $tail = true ] )

Mongo has a feature known as tailable cursors which are similar to the Unix "tail -f" command.

Tailable means cursor is not closed when the last data is retrieved. Rather, the cursor marks the final object's position. you can resume using the cursor later, from where it was located, if more data were received.

Like any "latent cursor", the cursor may become invalid at some point -- for example if that final object it references were deleted. Thus, you should be prepared to requery if the cursor is MongoCursor::dead().

Parameters

tail

If the cursor should be tailable.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::tailable() example

<?php

$cursor = $collection->find()->tailable();

$results = array();

while (1) {
    if (!$cursor->hasNext()) {
        // we've read all the results, exit
        if ($cursor->dead()) {
            break;
        }
        // read all results so far, wait for more
        sleep(10);
    }
    else {
        $results[] = $cursor->getNext();
    }
}

?>
MongoCursor::sort
MongoCursor::timeout
MongoCursor


Sets a client-side timeout for this query

MongoCursor::tailable
MongoCursor::valid
MongoCursor
PHP Manual

MongoCursor::timeout

(PECL mongo >=1.0.3)

MongoCursor::timeout — Sets a client-side timeout for this query

Description

public MongoCursor MongoCursor::timeout ( int $ms )

A timeout can be set at any time and will affect subsequent queries on the cursor, including fetching more results from the database. For example, to wait forever for an initial response but timeout after 100 ms for subsequent results, one could say:

<?php

$cursor = $collection->find();

// $cursor->hasNext() executes the query.  No timeout has been set, so the
// program will wait as long as necessary for a response.

while ($cursor->hasNext()) {
    $cursor->timeout(100);

    // now the timeout has been set, so if the cursor needs to get more results
    // from the database, it will only wait 100 ms for the database's reply

    try {
        print_r($cursor->getNext());
    }
    catch(MongoCursorTimeoutException $e) {
        echo "query took too long!";
    }
}

?>

A timeout of 0 (or a negative number) will wait forever so it can be used to reset the cursor if a timeout is no longer needed.

Parameters

ms

The number of milliseconds for the cursor to wait for a response. By default, the cursor will wait forever.

Return Values

This cursor.

Examples

Example #1 MongoCursor::timeout() example

A query where the cursor waits for one second for a response.

<?php

$cursor = $collection->find()->timeout(1000);

try {
  foreach ($cursor as $value) {
    print_r($value);
  }
}
catch(MongoCursorTimeoutException $e) {
  echo "query took too long!";
}

?>

Errors/Exceptions

Causes methods that fetch results to throw MongoCursorTimeoutExceptions if the query takes longer than the number of milliseconds specified.

MongoCursor::tailable
MongoCursor::valid
MongoCursor


Checks if the cursor is reading a valid result.

MongoCursor::timeout
Types
MongoCursor
PHP Manual

MongoCursor::valid

(PECL mongo >=0.9.0)

MongoCursor::valid — Checks if the cursor is reading a valid result.

Description

public boolean MongoCursor::valid ( void )

Parameters

This function has no parameters.

Return Values

If the current result is not null.

MongoCursor::timeout
Types
MongoCursor


Creates a new date.

MongoDate
MongoDate::__toString
MongoDate
PHP Manual

MongoDate::__construct

(PECL mongo >= 0.8.1)

MongoDate::__construct — Creates a new date.

Description

MongoDate::__construct ([ long $sec [, long $usec ]] )

Creates a new date. If no parameters are given, the current time is used.

Parameters

sec

Number of seconds since January 1st, 1970.

usec

Microseconds.

Return Values

Returns this new date.

Examples

Example #1 MongoDate::__construct() example

This example demonstrates creating a new date with the current time and a new date with a given time.

<?php

$d = new MongoDate();
echo "$d\n";
$d = new MongoDate(1234567890);
echo "$d\n";
$d = new MongoDate(strtotime("2009-05-01 00:00:01"));
echo "$d\n";

?>

The above example will output something similar to:

0.23660600 1235685067
0.00000000 1234567890
0.00000000 1241150401

See Also

  • MongoDate::__toString - Returns a string representation of this date

MongoDate
MongoDate::__toString
MongoDate


Returns a string representation of this date

MongoDate::__construct
MongoRegex
MongoDate
PHP Manual

MongoDate::__toString

(PECL mongo >= 0.8.1)

MongoDate::__toString — Returns a string representation of this date

Description

publicstring MongoDate::__toString ( void )

Returns a string representation of this date, similar to the representation returned by microtime()().

Parameters

This function has no parameters.

Return Values

This date.

MongoDate::__construct
MongoRegex
MongoDate


The name of this database

MongoDB::setProfilingLevel
MongoCollection
MongoDB
PHP Manual

MongoDB::__toString

(PECL mongo >=0.9.0)

MongoDB::__toString — The name of this database

Description

public string MongoDB::__toString ( void )

Parameters

This function has no parameters.

Return Values

Returns this database's name.

MongoDB::setProfilingLevel
MongoCollection
MongoDB


Log in to this database

MongoDB
MongoDB::command
MongoDB
PHP Manual

MongoDB::authenticate

(PECL mongo >=1.0.1)

MongoDB::authenticate — Log in to this database

Description

public array MongoDB::authenticate ( string $username , string $password )

This method causes its connection to be authenticated. If authentication is enabled for the database server (it's not, by default), you need to log in before the database will allow you to do anything.

This method is identical to running:

<?php

$salted = "${username}:mongo:${password}";
$hash = md5($salted);

$nonce = $db->command(array("getnonce" => 1));

$saltedHash = md5($nonce["nonce"]."${username}${hash}");

$result = $db->command(array("authenticate" => 1,
    "user" => $username,
    "nonce" => $nonce["nonce"],
    "key" => $saltedHash);

?>

Parameters

username

The username.

password

The password (in plaintext).

Return Values

Returns database response.

See Also

MongoDB core docs on » authenticate.

MongoDB
MongoDB::command
MongoDB


Execute a database command

MongoDB::authenticate
MongoDB::__construct
MongoDB
PHP Manual

MongoDB::command

(PECL mongo >=0.9.2)

MongoDB::command — Execute a database command

Description

public array MongoDB::command ( array $data )

Almost everything that is not a CRUD operation can be done with a database command. Need to know the database version? There's a command for that. Need to do aggregation? There's a command for that. Need to turn up logging? You get the idea.

This method is identical to running:

<?php

$db->selectCollection('$cmd')->findOne($data);

?>

Parameters

data

The query to send.

Return Values

Returns database response.

Examples

Example #1 MongoDB::command() "distinct" example

Finding all of the distinct values for a key.

<?php

$people->insert(array("name" => "Joe", "age" => 4));
$people->insert(array("name" => "Sally", "age" => 22));
$people->insert(array("name" => "Dave", "age" => 22));
$people->insert(array("name" => "Molly", "age" => 87));

$ages = $db->command(array("distinct" => "people", "key" => "age"));

foreach ($ages['values'] as $age) {
    echo "$age\n";
}

?>

The above example will output something similar to:

4
22
87

Example #2 MongoDB::command() MapReduce example

Get all users with at least on "sale" event, and how many times each of these users has had a sale.

<?php

// sample event document
$events->insert(array("user_id" => $id,
    "type" => $type,
    "time" => new MongoDate(),
    "desc" => $description));

// construct map and reduce functions
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
    "var sum = 0;".
    "for (var i in vals) {".
        "sum += vals[i];".
    "}".
    "return sum; }");

$sales = $db->command(array(
    "mapreduce" => "events",
    "map" => $map,
    "reduce" => $reduce,
    "query" => array("type" => "sale")));

$users = $db->selectCollection($sales['result'])->find();

foreach ($users as $user) {
    echo "{$user['_id']} had {$user['value']} sale(s).\n";
}

?>

The above example will output something similar to:

User 47cc67093475061e3d9536d2 had 3 sale(s).
User 49902cde5162504500b45c2c had 14 sale(s).
User 4af467e4fd543cce7b0ea8e2 had 1 sale(s).

Note: Using MongoCode
This example uses MongoCode, which can also take a scope argument. However, at the moment, MongoDB does not support using scopes in MapReduce. If you would like to use client-side variables in the MapReduce functions, you can add them to the global scope by using the optional scope field with the database command. See » MapReduce for more information.

If you are going to be using MapReduce, Prajwal Tuladhar created an API for Mongo PHP users which provides a nicer interface than the bare command. You can download it from » Github and there is a » blog post on how to use it.

See Also

MongoDB core docs on » database commands.

MongoDB::authenticate
MongoDB::__construct
MongoDB


Creates a new database

MongoDB::command
MongoDB::createCollection
MongoDB
PHP Manual

MongoDB::__construct

(PECL mongo >=0.9.0)

MongoDB::__construct — Creates a new database

Description

MongoDB::__construct ( Mongo $conn , string $name )

Parameters

Mongo conn

Database connection.

name

Database name.

Return Values

Returns the database.

Errors/Exceptions

Throws InvalidArgumentException if the database name is invalid.

MongoDB::command
MongoDB::createCollection
MongoDB


Creates a collection

MongoDB::__construct
MongoDB::createDBRef
MongoDB
PHP Manual

MongoDB::createCollection

(PECL mongo >=0.9.0)

MongoDB::createCollection — Creates a collection

Description

public MongoCollection MongoDB::createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )

This method is used to create capped collections and other collections requiring special options. It is identical to running:

<?php

$collection = $db->command(array("create" => $name, "size" => $size, "capped" => $capped, "max" => $max));

?>

See MongoDB::command() for more information about database commands.

Parameters

name

The name of the collection.

capped

If the collection should be a fixed size.

size

If the collection is fixed size, its size in bytes.

max

If the collection is fixed size, the maximum number of elements to store in the collection.

Return Values

Returns a collection object representing the new collection.

Examples

Example #1 MongoDB::createCollection() capped collection example

A capped collection is a special type of collection that has either a fixed or a fixed number of elements. Once the collection is "full," the oldest elements will be removed when new elements are added. Capped collections can be very useful for applications like logging, where you may want to reserve a certain amount of space for logs and not worry about them getting too big.

This example creates a very tiny log collection that will keep a maximum of 10 documents.

<?php

$log = $db->createCollection("logger", true, 10*1024, 10);

for ($i = 0; $i < 100; $i++) {
    $log->insert(array("level" => WARN, "msg" => "sample log message #$i", "ts" => new MongoDate()));
}

$msgs = $log->find();

foreach ($msgs as $msg) {
    echo $msg['msg']."\n";
}

?>

The above example will output something similar to:

sample log message #90
sample log message #91
sample log message #92
sample log message #93
sample log message #94
sample log message #95
sample log message #96
sample log message #97
sample log message #98
sample log message #99
MongoDB::__construct
MongoDB::createDBRef
MongoDB


Creates a database reference

MongoDB::createCollection
MongoDB::drop
MongoDB
PHP Manual

MongoDB::createDBRef

(PECL mongo >=0.9.0)

MongoDB::createDBRef — Creates a database reference

Description

public array MongoDB::createDBRef ( string $collection , mixed $a )

This method is a flexible interface for creating database refrences (see MongoDBRef).

Parameters

collection

The collection to which the database reference will point.

a

Object or _id to which to create a reference. If an object or associative array is given, this will create a reference using the _id field.

Return Values

Returns a database reference array.

MongoDB::createCollection
MongoDB::drop
MongoDB


Drops this database

MongoDB::createDBRef
MongoDB::dropCollection
MongoDB
PHP Manual

MongoDB::drop

(PECL mongo >=0.9.0)

MongoDB::drop — Drops this database

Description

public array MongoDB::drop ( void )

Parameters

This function has no parameters.

Return Values

Returns the database response.

MongoDB::createDBRef
MongoDB::dropCollection
MongoDB


Drops a collection

MongoDB::drop
MongoDB::execute
MongoDB
PHP Manual

MongoDB::dropCollection

(PECL mongo >=0.9.0)

MongoDB::dropCollection — Drops a collection

Description

public array MongoDB::dropCollection ( mixed $coll )

Parameters

coll

MongoCollection or name of collection to drop.

Return Values

Returns the database response.

MongoDB::drop
MongoDB::execute
MongoDB


Runs JavaScript code on the database server.

MongoDB::dropCollection
MongoDB::forceError
MongoDB
PHP Manual

MongoDB::execute

(No version information available, might only be in SVN)

MongoDB::execute — Runs JavaScript code on the database server.

Description

public array MongoDB::execute ( mixed $code [, array $args = array() ] )

The Mongo database server runs a JavaScript engine. This method allows you to run arbitary JavaScript on the database. This can be useful if you want touch a number of collections lightly, or process some results on the database side to reduce the amount that has to be sent to the client.

Parameters

code

MongoCode or string to execute.

args

Arguments to be passed to code.

Return Values

Returns the result of the evaluation.

Examples

Example #1 Simple MongoDB::execute() example

<?php

$response = $db->execute("function() { return 'Hello, world!'; }");
echo $response['retval'];

?>

The above example will output something similar to:

Hello, world!

Example #2 Parameter MongoDB::execute() example

The optional array of parameters will be passed to the JavaScript function.

<?php

$response = $db->execute("function(greeting, name) { return greeting+', '+name+'!'; }", array("Good bye", "Joe"));
echo $response['retval'];

?>

The above example will output something similar to:

Good bye, Joe!

Example #3 Scope example

If a MongoCode object is used instead of a string for the first parameter, a scope can be passed in which the JavaScript will be executed.

<?php

$func =
    "function(greeting, name) { ".
        "return greeting+', '+name+', says '+greeter;".
    "}";
$scope = array("greeter" => "Fred");

$code = new MongoCode($func, $scope);

$response = $db->execute($code, array("Goodbye", "Joe"));
echo $response['retval'];

?>

The above example will output something similar to:

Goodbye, Joe, says Fred
MongoDB::dropCollection
MongoDB::forceError
MongoDB


Creates a database error

MongoDB::execute
MongoDB::__get
MongoDB
PHP Manual

MongoDB::forceError()

(No version information available, might only be in SVN)

— Creates a database error

Description

public bool MongoDB::forceError ( void )

Parameters

This function has no parameters.

Return Values

Returns the database response.

MongoDB::execute
MongoDB::__get
MongoDB


Gets a collection

MongoDB::forceError
MongoDB::getDBRef
MongoDB
PHP Manual

MongoDB::__get

(PECL mongo >=1.0.2)

MongoDB::__get — Gets a collection

Description

public MongoCollection MongoDB::__get ( string $name )

This is the easiest way of getting a collection from a database object. If a collection name contains strange characters, you may have to use MongoDB::selectCollection() instead.

<?php

$mongo = new Mongo();

// the following two lines are equivalent
$collection = $mongo->selectDB("foo")->selectCollection("bar");
$collection = $mongo->foo->bar;

?>

Parameters

name

The name of the collection.

Return Values

Returns the collection.

MongoDB::forceError
MongoDB::getDBRef
MongoDB


Fetches the document pointed to by a database reference

MongoDB::__get
MongoDB::getGridFS
MongoDB
PHP Manual

MongoDB::getDBRef

(PECL mongo >=0.9.0)

MongoDB::getDBRef — Fetches the document pointed to by a database reference

Description

public array MongoDB::getDBRef ( array $ref )

Parameters

ref

A database reference.

Return Values

Returns the document pointed to by the reference.

MongoDB::__get
MongoDB::getGridFS
MongoDB


Fetches toolkit for dealing with files stored in this database

MongoDB::getDBRef
MongoDB::getProfilingLevel
MongoDB
PHP Manual

MongoDB::getGridFS

(PECL mongo >=0.9.0)

MongoDB::getGridFS — Fetches toolkit for dealing with files stored in this database

Description

public MongoGridFS MongoDB::getGridFS ([ string $prefix = "fs" ] )

Parameters

prefix

The prefix for the files and chunks collections.

Return Values

Returns a new gridfs object for this database.

MongoDB::getDBRef
MongoDB::getProfilingLevel
MongoDB


Gets this database's profiling level

MongoDB::getGridFS
MongoDB::lastError
MongoDB
PHP Manual

MongoDB::getProfilingLevel

(PECL mongo >=0.9.0)

MongoDB::getProfilingLevel — Gets this database's profiling level

Description

public int MongoDB::getProfilingLevel ( void )

Parameters

This function has no parameters.

Return Values

Returns the profiling level.

See Also

MongoDB core docs on » profiling and MongoDB::setProfilingLevel() - Sets this database's profiling level.

MongoDB::getGridFS
MongoDB::lastError
MongoDB


Check if there was an error on the most recent db operation performed

MongoDB::getProfilingLevel
MongoDB::listCollections
MongoDB
PHP Manual

MongoDB::lastError

(PECL mongo >=0.9.5)

MongoDB::lastError — Check if there was an error on the most recent db operation performed

Description

public array MongoDB::lastError ( void )

Parameters

This function has no parameters.

Return Values

Returns the error, if there was one.

Examples

Example #1 MongoDB::lastError() NULL error example

<?php
$db->resetError();
var_dump($db->lastError());
?>

The above example will output something similar to:

array(3) {
  ["err"]=>
  NULL
  ["n"]=>
  int(0)
  ["ok"]=>
  float(1)
}

Example #2 MongoDB::lastError() duplicate key example

<?php
$c = $db->selectCollection("foo");

// insert two documents with the same _id
$c->insert(array("_id" => 1));
$c->insert(array("_id" => 1));

var_dump($db->lastError());
?>

The above example will output something similar to:

array(3) {
  ["err"]=>
  string(64) "E11000 duplicate key errorindex: foo.foo.$_id_  dup key: { : 1 }"
  ["n"]=>
  int(0)
  ["ok"]=>
  float(1)
}
MongoDB::getProfilingLevel
MongoDB::listCollections
MongoDB


Get a list of collections in this database

MongoDB::lastError
MongoDB::prevError
MongoDB
PHP Manual

MongoDB::listCollections

(PECL mongo >=0.9.0)

MongoDB::listCollections — Get a list of collections in this database

Description

public array MongoDB::listCollections ( void )

Parameters

This function has no parameters.

Return Values

Returns a list of MongoCollections.

Examples

Example #1 MongoDB::listCollections() example

The following example demonstrates dropping each collection in a database.

<?php

$m = new Mongo();
$db = $m->selectDB("sample");

$list = $db->listCollections();
foreach ($list as $collection) {
    echo "removing $collection... ";
    $collection->drop();
    echo "gone\n";
}

?>

The above example will output something similar to:

removing sample.blog.posts... gone
removing sample.critical.docs... gone
removing sample.taxes... gone
...
MongoDB::lastError
MongoDB::prevError
MongoDB


Checks for the last error thrown during a database operation

MongoDB::listCollections
MongoDB::repair
MongoDB
PHP Manual

MongoDB::prevError

(PECL mongo >=0.9.5)

MongoDB::prevError — Checks for the last error thrown during a database operation

Description

public array MongoDB::prevError ( void )

Parameters

This function has no parameters.

Return Values

Returns the error and the number of operations ago it occurred.

MongoDB::listCollections
MongoDB::repair
MongoDB


Repairs and compacts this database

MongoDB::prevError
MongoDB::resetError
MongoDB
PHP Manual

MongoDB::repair

(PECL mongo >=0.9.0)

MongoDB::repair — Repairs and compacts this database

Description

public array MongoDB::repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] )

Parameters

preserve_cloned_files

If cloned files should be kept if the repair fails.

backup_original_files

If original files should be backed up.

Return Values

Returns db response.

See Also

MongoDB core docs on » repair.

MongoDB::prevError
MongoDB::resetError
MongoDB


Clears any flagged errors on the database

MongoDB::repair
MongoDB::selectCollection
MongoDB
PHP Manual

MongoDB::resetError

(PECL mongo >=0.9.5)

MongoDB::resetError — Clears any flagged errors on the database

Description

public array MongoDB::resetError ( void )

Parameters

This function has no parameters.

Return Values

Returns the database response.

MongoDB::repair
MongoDB::selectCollection
MongoDB


Gets a collection

MongoDB::resetError
MongoDB::setProfilingLevel
MongoDB
PHP Manual

MongoDB::selectCollection

(PECL mongo >=0.9.0)

MongoDB::selectCollection — Gets a collection

Description

public MongoCollection MongoDB::selectCollection ( string $name )

Parameters

name

The name of the collection.

Return Values

Returns the collection.

MongoDB::resetError
MongoDB::setProfilingLevel
MongoDB


Sets this database's profiling level

MongoDB::selectCollection
MongoDB::__toString
MongoDB
PHP Manual

MongoDB::setProfilingLevel

(PECL mongo >=0.9.0)

MongoDB::setProfilingLevel — Sets this database's profiling level

Description

public int MongoDB::setProfilingLevel ( int $level )

Parameters

level

Profiling level.

Return Values

Returns the previous profiling level.

MongoDB::selectCollection
MongoDB::__toString
MongoDB


Creates a new database reference

MongoDBRef
MongoDBRef::get
MongoDBRef
PHP Manual

MongoDBRef::create

(PECL mongo >= 0.9.0)

MongoDBRef::create — Creates a new database reference

Description

public static array MongoDBRef::create ( string $collection , mixed $id [, string $database ] )

If no database is given, the current database is used.

Parameters

collection

Collection name.

id

The _id field of the object to which to link.

database

Database name.

Return Values

Returns the reference.

Examples

Example #1 MongoDBRef::create() example

<?php
$addresses = $db->addresses;
$people = $db->people;

// save $address so it has an _id
$addresses->insert($address);

// create a reference
$ref = MongoDBRef::create($addresses->name, $address['_id']);

// set the field in $person
$person['address'] = $ref;
$people->save($person);
?>

See Also

  • MongoDB::createDBRef - Creates a database reference
  • MongoCollection::createDBRef - Creates a database reference

MongoDBRef
MongoDBRef::get
MongoDBRef


Fetches the object pointed to by a reference

MongoDBRef::create
MongoDBRef::isRef
MongoDBRef
PHP Manual

MongoDBRef::get

(PECL mongo >= 0.9.0)

MongoDBRef::get — Fetches the object pointed to by a reference

Description

public static array MongoDBRef::get ( MongoDB $db , array $ref )

Parameters

db

Database to use.

ref

Reference to fetch.

Return Values

Returns the document to which the reference refers or NULL if the document does not exist (the reference is broken).

Examples

Example #1 MongoCollection::createDBRef() example

<?php

// get $person out of the db
$person = $people->findOne();

// dereference the address
$address = MongoDBRef::get($people->db, $person['address']);

?>

See Also

  • MongoDB::getDBRef - Fetches the document pointed to by a database reference
  • MongoCollection::getDBRef - Fetches the document pointed to by a database reference

MongoDBRef::create
MongoDBRef::isRef
MongoDBRef


Checks if an array is a database reference

MongoDBRef::get
MongoMinKey
MongoDBRef
PHP Manual

MongoDBRef::isRef

(PECL mongo >= 0.9.0)

MongoDBRef::isRef — Checks if an array is a database reference

Description

public static boolean MongoDBRef::isRef ( mixed $ref )

This not actually follow the reference, so it does not determine if it is broken or not. It merely checks that ref is in valid database reference format (in that it is an object or array with $ref and $id fields).

Parameters

ref

Array or object to check.

Return Values

Returns if ref is a reference.

MongoDBRef::get
MongoMinKey
MongoDBRef


Creates new file collections

MongoGridFS
MongoGridFS::drop
MongoGridFS
PHP Manual

MongoGridFS::__construct

(PECL mongo >=0.9.0)

MongoGridFS::__construct — Creates new file collections

Description

MongoGridFS::__construct ( MongoDB $db [, string $prefix = "fs" ] )

Files as stored across two collections, the first containing file meta information, the second containing chunks of the actual file. By default, fs.files and fs.chunks are the collection names used.

Use one argument to specify a prefix other than "fs":

$fs = new MongoGridFS($db, "myfiles");
uses myfiles.files and myfiles.chunks collections.

Parameters

db

Database.

files

Optional collection name prefix.

MongoGridFS
MongoGridFS::drop
MongoGridFS


Drops the files and chunks collections

MongoGridFS::__construct
MongoGridFS::find
MongoGridFS
PHP Manual

MongoGridFS::drop

(PECL mongo >=0.9.0)

MongoGridFS::drop — Drops the files and chunks collections

Description

public array MongoGridFS::drop ( void )

Parameters

This function has no parameters.

Return Values

The database response.

MongoGridFS::__construct
MongoGridFS::find
MongoGridFS


Queries for files

MongoGridFS::drop
MongoGridFS::findOne
MongoGridFS
PHP Manual

MongoGridFS::find

(PECL mongo >=0.9.0)

MongoGridFS::find — Queries for files

Description

 public MongoGridFSCursor MongoGridFS::find
  ([ array $query = array()
 [, array $fields = array()
]] )

Parameters

query

The query.

fields

Fields to return.

Return Values

A file cursor to the results.

MongoGridFS::drop
MongoGridFS::findOne
MongoGridFS


Returns a single file matching the criteria

MongoGridFS::find
MongoGridFS::remove
MongoGridFS
PHP Manual

MongoGridFS::findOne

(PECL mongo >=0.9.0)

MongoGridFS::findOne — Returns a single file matching the criteria

Description

public MongoGridFSFile MongoGridFS::findOne ([ mixed $query = array() ] )

Parameters

query

The filename or criteria for which to search.

Return Values

Returns a file or NULL.

MongoGridFS::find
MongoGridFS::remove
MongoGridFS


Removes files from the collections

MongoGridFS::findOne
MongoGridFS::storeBytes
MongoGridFS
PHP Manual

MongoGridFS::remove

(PECL mongo >=0.9.0)

MongoGridFS::remove — Removes files from the collections

Description

public boolean MongoGridFS::remove ([ array $criteria = array() [, boolean $just_one = FALSE ]] )

Parameters

query

The filename or criteria for which to search.

just_one

If only one matching file should be removed.

Return Values

Returns if the removal was successful.

MongoGridFS::findOne
MongoGridFS::storeBytes
MongoGridFS


Chunkifies and stores bytes in the database

MongoGridFS::remove
MongoGridFS::storeFile
MongoGridFS
PHP Manual

MongoGridFS::storeBytes

(PECL mongo >=0.9.2)

MongoGridFS::storeBytes — Chunkifies and stores bytes in the database

Description

public mixed MongoGridFS::storeBytes ( string $bytes [, array $extra = array() ] )

Parameters

bytes

A string of bytes to store.

extra

Other metadata to add to the file saved.

Return Values

The _id of the object saved.

MongoGridFS::remove
MongoGridFS::storeFile
MongoGridFS


Stores a file in the database

MongoGridFS::storeBytes
MongoGridFS::storeUpload
MongoGridFS
PHP Manual

MongoGridFS::storeFile

(PECL mongo >=0.9.0)

MongoGridFS::storeFile — Stores a file in the database

Description

public mixed MongoGridFS::storeFile ( string $filename [, array $extra = array() ] )

Parameters

filename

The name of the file.

extra

Other metadata to add to the file saved.

Return Values

Returns the _id of the saved object.

MongoGridFS::storeBytes
MongoGridFS::storeUpload
MongoGridFS


Saves an uploaded file to the database

MongoGridFS::storeFile
MongoGridFSFile
MongoGridFS
PHP Manual

MongoGridFS::storeUpload

(PECL mongo >=0.9.0)

MongoGridFS::storeUpload — Saves an uploaded file to the database

Description

public mixed MongoGridFS::storeUpload ( string $name [, string $filename ] )

Parameters

name

The name field of the uploaded file.

filename

String to be used as filename field in the database.

Return Values

Returns the _id of the uploaded file.

MongoGridFS::storeFile
MongoGridFSFile
MongoGridFS


Create a new cursor

MongoGridFSCursor
MongoGridFSCursor::current
MongoGridFSCursor
PHP Manual

MongoGridFSCursor::__construct

(PECL mongo >=0.9.0)

MongoGridFSCursor::__construct — Create a new cursor

Description

MongoGridFSCursor::__construct ( MongoGridFS $gridfs , resource $connection , string $ns [, array $query = array() [, array $fields = array() ]] )

Parameters

gridfs

Related GridFS collection.

connection

Database connection.

ns

Full name of database and collection.

query

Database query.

fields

Fields to return.

Return Values

Returns the new cursor.

MongoGridFSCursor
MongoGridFSCursor::current
MongoGridFSCursor


Returns the current file

MongoGridFSCursor::__construct
MongoGridFSCursor::getNext
MongoGridFSCursor
PHP Manual

MongoGridFSCursor::current

(PECL mongo >=0.9.0)

MongoGridFSCursor::current — Returns the current file

Description

public MongoGridFSFile MongoGridFSCursor::current ( void )

Parameters

This function has no parameters.

Return Values

The current file.

MongoGridFSCursor::__construct
MongoGridFSCursor::getNext
MongoGridFSCursor


Return the next file to which this cursor points, and advance the cursor

MongoGridFSCursor::current
MongoGridFSCursor::key
MongoGridFSCursor
PHP Manual

MongoGridFSCursor::getNext

(PECL mongo >=0.9.0)

MongoGridFSCursor::getNext — Return the next file to which this cursor points, and advance the cursor

Description

public MongoGridFSFile MongoGridFSCursor::getNext ( void )

Parameters

This function has no parameters.

Return Values

Returns the next file.

MongoGridFSCursor::current
MongoGridFSCursor::key
MongoGridFSCursor


Returns the current result's filename

MongoGridFSCursor::getNext
Functions
MongoGridFSCursor
PHP Manual

MongoGridFSCursor::key

(PECL mongo >=0.9.0)

MongoGridFSCursor::key — Returns the current result's filename

Description

public string MongoGridFSCursor::key ( void )

Parameters

This function has no parameters.

Return Values

The current result's filename.

MongoGridFSCursor::getNext
Functions
MongoGridFSCursor


Create a new GridFS file

MongoGridFSFile
MongoGridFSFile::getBytes
MongoGridFSFile
PHP Manual

MongoGridfsFile::__construct

(PECL mongo >=0.9.0)

MongoGridfsFile::__construct — Create a new GridFS file

Description

MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )

Parameters

gridfs

The parent MongoGridFS instance.

file

A file from the database.

Return Values

Returns a new MongoGridFSFile.

MongoGridFSFile
MongoGridFSFile::getBytes
MongoGridFSFile


Returns this file's contents as a string of bytes

MongoGridfsFile::__construct
MongoGridFSFile::getFilename
MongoGridFSFile
PHP Manual

MongoGridFSFile::getBytes

(PECL mongo >=0.9.0)

MongoGridFSFile::getBytes — Returns this file's contents as a string of bytes

Description

public string MongoGridFSFile::getBytes ( void )

Warning: this will load the file into memory. If the file is bigger than your memory, this will cause problems!

Parameters

This function has no parameters.

Return Values

Returns a string of the bytes in the file.

MongoGridfsFile::__construct
MongoGridFSFile::getFilename
MongoGridFSFile


Returns this file's filename

MongoGridFSFile::getBytes
MongoGridFSFile::getSize
MongoGridFSFile
PHP Manual

MongoGridFSFile::getFilename

(PECL mongo >=0.9.0)

MongoGridFSFile::getFilename — Returns this file's filename

Description

public string MongoGridFSFile::getFilename ( void )

Parameters

This function has no parameters.

Return Values

Returns the filename.

MongoGridFSFile::getBytes
MongoGridFSFile::getSize
MongoGridFSFile


Returns this file's size

MongoGridFSFile::getFilename
MongoGridFSFile::write
MongoGridFSFile
PHP Manual

MongoGridFSFile::getSize

(PECL mongo >=0.9.0)

MongoGridFSFile::getSize — Returns this file's size

Description

public int MongoGridFSFile::getSize ( void )

Parameters

This function has no parameters.

Return Values

Returns this file's size

MongoGridFSFile::getFilename
MongoGridFSFile::write
MongoGridFSFile


Writes this file to the filesystem

MongoGridFSFile::getSize
MongoGridFSCursor
MongoGridFSFile
PHP Manual

MongoGridFSFile::write

(PECL mongo >=0.9.0)

MongoGridFSFile::write — Writes this file to the filesystem

Description

public int MongoGridFSFile::write ([ string $filename = NULL ] )

Parameters

filename

The location to which to write the file. If none is given, the stored filename will be used.

Return Values

Returns the number of bytes written.

MongoGridFSFile::getSize
MongoGridFSCursor
MongoGridFSFile


Creates a new id

MongoId
MongoId::getTimestamp
MongoId
PHP Manual

MongoId::__construct

(PECL mongo >= 0.8.0)

MongoId::__construct — Creates a new id

Description

MongoId::__construct ([ string $id = NULL ] )

Parameters

id

A string to use as the id. Must be 24 hexidecimal characters. If an invalid string is passed to this constructor, the constructor will ignore it and create a new id value.

Return Values

Returns a new id.

Examples

Example #1 MongoId::__construct() example

This example shows how to create a new id. This is seldom necessary, as the driver adds an id to arrays automatically before storing them in the database.

<?php

  $id1 = new MongoId();
  echo "$id1\n";

  $id2 = new MongoId();
  echo "$id2\n";

  ?>

The above example will output something similar to:

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d

Example #2 Parameter example

This example shows how to use a string parameter to initialize a MongoId with a given value.

<?php
  $id1 = new MongoId();

  // create a new id from $id1
  $id2 = new MongoId("$id1");

  // show that $id1 and $id2 have the same hexidecimal value
  var_dump($id1 == $id2);
  ?>

The above example will output something similar to:

bool(true)

See Also

  • MongoId::__toString - Returns a hexidecimal representation of this id

MongoId
MongoId::getTimestamp
MongoId


Gets the number of seconds since the epoch that this id was created

MongoId::__construct
MongoId::__toString
MongoId
PHP Manual

MongoId::getTimestamp

(PECL mongo >= 1.0.1)

MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created

Description

public int MongoId::getTimestamp ( void )

This returns the same thing as running time()() when the id is created.

Parameters

This function has no parameters.

Return Values

Returns the number of seconds since the epoch that this id was created. There are only four bytes of timestamp stored, so MongoDate is a better choice for storing exact or wide-ranging times.

MongoId::__construct
MongoId::__toString
MongoId


Returns a hexidecimal representation of this id

MongoId::getTimestamp
MongoCode
MongoId
PHP Manual

MongoId::__toString

(PECL mongo >= 0.8.0)

MongoId::__toString — Returns a hexidecimal representation of this id

Description

public string MongoId::__toString ( void )

Parameters

This function has no parameters.

Return Values

This id.

Examples

Example #1 MongoId::__toString() example

<?php

$m = new Mongo();
$collection = $m->selectDB("foo")->selectCollection("bar");

$collection->insert(array( "x" => "y" ));
$collection->insert(array( "x" => "y" ));

$cursor = $collection->find();
$r1 = cursor->next();
$r2 = cursor->next();

echo $r1["_id"] . "\n";
echo $r2["_id"] . "\n";

?>

The above example will output something similar to:

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d
MongoId::getTimestamp
MongoCode
MongoId


Creates a new regular expression

MongoRegex
MongoRegex::__toString
MongoRegex
PHP Manual

MongoRegex::__construct

(PECL mongo >= 0.8.1)

MongoRegex::__construct — Creates a new regular expression

Description

MongoRegex::__construct ( string $regex )

Creates a new regular expression.

Parameters

regex

Regular expression string of the form /expr/flags.

Return Values

Returns a new regular expression.

Examples

Example #1 MongoRegex::__construct() example

This example uses a regular expression to query for all documents with a username field matching a regular expression.

<?php

$joe_search = new MongoRegex("/j[o0]e/i");
$cursor = $collection->find(array("username" => $joe_search));

?>

See Also

  • MongoRegex::__toString - A string representation of this regular expression

MongoRegex
MongoRegex::__toString
MongoRegex


A string representation of this regular expression

MongoRegex::__construct
MongoBinData
MongoRegex
PHP Manual

MongoRegex::__toString

(PECL mongo >= 0.8.1)

MongoRegex::__toString — A string representation of this regular expression

Description

public string MongoRegex::__toString ( void )

Returns a string representation of this regular expression.

Parameters

This function has no parameters.

Return Values

This regular expression in the form "/expr/flags".

Examples

Example #1 MongoRegex::__toString() example

<?php

$r = new MongoRegex( "/[a-fA-F0-9]{16}/g" );
echo $r->regex . "\n";
echo $r->flags . "\n";
echo "$r\n";

?>

The above example will output something similar to:

[a-fA-F0-9]{16}
g
/[a-fA-F0-9]{16}/g

MongoRegex::__construct
MongoBinData
MongoRegex


Creates a new timestamp.

MongoTimestamp
MongoTimestamp::__toString
MongoTimestamp
PHP Manual

MongoTimestamp::__construct

(PECL mongo >= 1.0.1)

MongoTimestamp::__construct — Creates a new timestamp.

Description

MongoTimestamp::__construct ([ long $sec [, long $inc ]] )

Creates a new timestamp. If no parameters are given, the current time is used and the increment is automatically provided. The increment is set to 0 when the module is loaded and is incremented every time this constructor is called (without the $inc parameter passed in).

Parameters

sec

Number of seconds since January 1st, 1970.

inc

Increment.

Return Values

Returns this new timestamp.

See Also

  • MongoTimestamp::__toString - Returns a string representation of this timestamp

MongoTimestamp
MongoTimestamp::__toString
MongoTimestamp


Returns a string representation of this timestamp

MongoTimestamp::__construct
GridFS Classes
MongoTimestamp
PHP Manual

MongoTimestamp::__toString

(PECL mongo >= 1.0.1)

MongoTimestamp::__toString — Returns a string representation of this timestamp

Description

publicstring MongoTimestamp::__toString ( void )

Returns the "sec" field of this timestamp.

Parameters

This function has no parameters.

Return Values

The seconds since epoch represented by this timestamp.

MongoTimestamp::__construct
GridFS Classes
MongoTimestamp


Opens a new file

KTaglib_MPEG_File
KTaglib_MPEG_File::getAudioProperties
KTaglib_MPEG_File
PHP Manual

KTaglib_MPEG_File::__construct

(0.0.1)

KTaglib_MPEG_File::__construct — Opens a new file

Description

KTaglib_MPEG_File::__construct ( string $filename )

Opens a new MPEG file.

Parameters

filename

The file to read

Examples

Example #1 Opens a new MP3 file and read the title

<?php
$mpeg = new KTaglib_MPEG_File('example.mp3');
echo $mpeg->getID3v1Tag()->getTitle();
?>

KTaglib_MPEG_File
KTaglib_MPEG_File::getAudioProperties
KTaglib_MPEG_File


Returns an object that provides access to the audio properties

KTaglib_MPEG_File::__construct
KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_File
PHP Manual

KTaglib_MPEG_File::getAudioProperties

(0.0.1)

KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties

Description

public KTaglib_MPEG_File: KTaglib_MPEG_File::getAudioProperties ( void )

Returns an object that provides access to the audio properties of the mpeg file.

Return Values

Returns an KTaglib_MPEG_AudioProperties object or false.

KTaglib_MPEG_File::__construct
KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_File


Returns an object representing an ID3v1 tag

KTaglib_MPEG_File::getAudioProperties
KTaglib_MPEG_File::getID3v2Tag
KTaglib_MPEG_File
PHP Manual

KTaglib_MPEG_File::getID3v1Tag

(0.0.1)

KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag

Description

public KTaglib_ID3v1_Tag KTaglib_MPEG_File::getID3v1Tag ([ bool $create = false ] )

Returns an object that represents an ID3v1 tag, which can be used to get information about the ID3v1 tag.

Return Values

Returns an KTaglib_MPEG_ID3v1Tag object or false if there is no ID3v1 tag.

KTaglib_MPEG_File::getAudioProperties
KTaglib_MPEG_File::getID3v2Tag
KTaglib_MPEG_File


Returns a ID3v2 object

KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_AudioProperties
KTaglib_MPEG_File
PHP Manual

KTaglib_MPEG_File::getID3v2Tag

(0.0.1)

KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object

Description

public KTaglib_ID3v2_Tag KTaglib_MPEG_File::getID3v2Tag ([ bool $create = false ] )

Returns a ID3v2 object for the mpeg file. If no ID3v2 Tag is present, an KTaglib_TagNotFoundException is thrown.

Return Values

Returns the KTaglib_ID3v2_Tag object of the MPEG file or false if there is no ID3v2 tag

KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_AudioProperties
KTaglib_MPEG_File


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

mSQL configuration options
Name | Default | Changeable | Changelog
msql.allow_persistent | "1" | PHP_INI_ALL |
msql.max_persistent | "-1" | PHP_INI_ALL |
msql.max_links | "-1" | PHP_INI_ALL |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

msql.allow_persistent boolean

Whether to allow persistent mSQL connections.

msql.max_persistent integer

The maximum number of persistent mSQL connections per process.

msql.max_links integer

The maximum number of mSQL connections per process, including persistent connections.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

MSQL_ASSOC (integer)
MSQL_NUM (integer)
MSQL_BOTH (integer)
Resource Types
Examples
mSQL


Examples

Table of Contents

  • mSQL usage example
Predefined Constants
mSQL usage example
mSQL


mSQL usage example

Examples
mSQL Functions
Examples
PHP Manual

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a mSQL database.

Example #1 mSQL usage example

<?php
/* Connecting, selecting database */
$link = msql_connect('localhost', 'username', 'password')
    or die('Could not connect : ' . msql_error($link));

msql_select_db('database', $link)
    or die('Could not select database');

/* Issue SQL query */
$query = 'SELECT * FROM my_table';
$result = msql_query($query, $link) or die('Query failed : ' . msql_error());

/* Printing results in HTML */
echo "<table>\n";
while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($row as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

/* Free result set */
msql_free_result($result);

/* Close connection */
msql_close($link);
?>

Examples
mSQL Functions
Examples


Installation

In order to have these functions available, you must compile PHP with msql support by using the --with-msql[=DIR] option. DIR is the mSQL base install directory, defaults to /usr/local/msql3.

Note: Note to Win32 Users
In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: msql.dll

Requirements
Runtime Configuration
Installing/Configuring


Resource Types

There are two resource types used in the mSQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
mSQL


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MS SQL Server configuration options
Name | Default | Changeable | Changelog
mssql.allow_persistent | "1" | PHP_INI_SYSTEM |
mssql.max_persistent | "-1" | PHP_INI_SYSTEM |
mssql.max_links | "-1" | PHP_INI_SYSTEM |
mssql.min_error_severity | "10" | PHP_INI_ALL |
mssql.min_message_severity | "10" | PHP_INI_ALL |
mssql.compatability_mode | "0" | PHP_INI_ALL |
mssql.connect_timeout | "5" | PHP_INI_ALL |
mssql.timeout | "60" | PHP_INI_ALL | Available since PHP 4.1.0.
mssql.textsize | "-1" | PHP_INI_ALL |
mssql.textlimit | "-1" | PHP_INI_ALL |
mssql.batchsize | "0" | PHP_INI_ALL | Available since PHP 4.0.4.
mssql.datetimeconvert | "1" | PHP_INI_ALL | Available since PHP 4.2.0.
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
mssql.max_procs | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
mssql.charset | "" | PHP_INI_ALL | Available since PHP 5.1.2 when built with FreeTDS 7.0 or greater.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

MSSQL_ASSOC (integer)
Return an associative array. Used on mssql_fetch_array()'s result_type parameter.
MSSQL_NUM (integer)
Return an array with numeric keys. Used on mssql_fetch_array()'s result_type parameter.
MSSQL_BOTH (integer)
Return an array with both numeric keys and keys with their field name. This is the default value for mssql_fetch_array()'s result_type parameter.
SQLTEXT (integer)
Indicates the 'TEXT' type in MSSQL, used by mssql_bind()'s type parameter.
SQLVARCHAR (integer)
Indicates the 'VARCHAR' type in MSSQL, used by mssql_bind()'s type parameter.
SQLCHAR (integer)
Indicates the 'CHAR' type in MSSQL, used by mssql_bind()'s type parameter.
SQLINT1 (integer)
Represents one byte, with a range of -128 to 127.
SQLINT2 (integer)
Represents two bytes, with a range of -32768 to 32767.
SQLINT4 (integer)
Represents four bytes, with a range of -2147483648 to 2147483647.
SQLBIT (integer)
Indicates the 'BIT' type in MSSQL, used by mssql_bind()'s type parameter.
SQLFLT4 (integer)
Represents an four byte float.
SQLFLT8 (integer)
Represents an eight byte float.
Resource Types
Mssql Functions
Mssql


Installation

The MSSQL extension is enabled by adding extension=php_mssql.dll to php.ini.

To get these functions to work, you have to compile PHP with --with-mssql[=DIR], where DIR is the FreeTDS install prefix. And FreeTDS should be compiled using --enable-msdblib.

Warning

MS SQL functions are aliases to Sybase functions if PHP is compiled with Sybase extension and without MS SQL extension.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

Requirements for Win32 platforms.

The extension requires the MS SQL Client Tools to be installed on the system where PHP is installed. The Client Tools can be installed from the MS SQL Server CD or by copying ntwdblib.dll from \winnt\system32 on the server to \winnt\system32 on the PHP box. Copying ntwdblib.dll will only provide access through named pipes. Configuration of the client will require installation of all the tools.

Requirements for Unix/Linux platforms.

To use the MSSQL extension on Unix/Linux, you first need to build and install the FreeTDS library. Source code and installation instructions are available at the FreeTDS home page: » http://www.freetds.org/

Note: On Windows, the DBLIB from Microsoft is used. Functions that return a column name are based on the dbcolname() function in DBLIB. DBLIB was developed for SQL Server 6.x where the max identifier length is 30. For this reason, the maximum column length is 30 characters. On platforms where FreeTDS is used (Linux), this is not a problem.

Note: On Windows, if you're using MSSQL 2005 or greater you must copy the ntwdblib.dll into the directory where you have installed php and overwrite the one thats already in there. This is due to the version distributed is old and outdated. Alternatively you can use the ODBC, PDO_DBLIB or PDO_ODBC extensions, to talk to MSSQL.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

mssql link

A connection link returned by mssql_connect() and mssql_pconnect().

mssql result

A result handle returned by mssql_query() on SELECT queries.

mssql statement

A statement handle returned by mssql_init().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Mssql


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MySQL Configuration Options
Name | Default | Changeable | Changelog
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL | Available since PHP 4.0.1.
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "60" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.3.2. Available since PHP 4.3.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mysql.allow_persistent boolean

Whether to allow persistent connections to MySQL.

mysql.max_persistent integer

The maximum number of persistent MySQL connections per process.

mysql.max_links integer

The maximum number of MySQL connections per process, including persistent connections.

mysql.trace_mode boolean

Trace mode. When mysql.trace_mode is enabled, warnings for table/index scans, non free result sets, and SQL-Errors will be displayed. (Introduced in PHP 4.3.0)

mysql.default_port string

The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.

mysql.default_socket string

The default socket name to use when connecting to a local database server if no other socket name is specified.

mysql.default_host string

The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in SQL safe mode.

mysql.default_user string

The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in SQL safe mode.

mysql.default_password string

The default password to use when connecting to the database server if no other password is specified. Doesn't apply in SQL safe mode.

mysql.connect_timeout integer

Connect timeout in seconds. On Linux this timeout is also used for waiting for the first answer from the server.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Since PHP 4.3.0 it is possible to specify additional client flags for the mysql_connect() and mysql_pconnect() functions. The following constants are defined:

MySQL client constants
Constant | Description
MYSQL_CLIENT_COMPRESS | Use compression protocol
MYSQL_CLIENT_IGNORE_SPACE | Allow space after function names
MYSQL_CLIENT_INTERACTIVE | Allow interactive_timeout seconds (instead of wait_timeout) of inactivity before closing the connection.
MYSQL_CLIENT_SSL | Use SSL encryption. This flag is only available with version 4.x of the MySQL client library or newer. Version 3.23.x is bundled both with PHP 4 and Windows binaries of PHP 5.

The function mysql_fetch_array() uses a constant for the different types of result arrays. The following constants are defined:

MySQL fetch constants
Constant | Description
MYSQL_ASSOC | Columns are returned into the array having the fieldname as the array index.
MYSQL_BOTH | Columns are returned into the array having both a numerical index and the fieldname as the array index.
MYSQL_NUM | Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

Resource Types
Examples
MySQL


Examples

Table of Contents

  • MySQL extension overview example
Predefined Constants
MySQL extension overview example
MySQL


MySQL extension overview example

Examples
MySQL Functions
Examples
PHP Manual

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MySQL database.

Example #1 MySQL extension overview example

<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');

// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?>

Examples
MySQL Functions
Examples


Installation

For compiling, simply use the --with-mysql[=DIR] configuration option where the optional [DIR] points to the MySQL installation directory.

Although this MySQL extension is compatible with MySQL 4.1.0 and greater, it doesn't support the extra functionality that these versions provide. For that, use the MySQLi extension.

If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any conflicts.

Installation on Linux Systems

PHP 4

The option --with-mysql is enabled by default. This default behavior may be disabled with the --without-mysql configure option. If MySQL is enabled without specifying the path to the MySQL install DIR, PHP will use the bundled MySQL client libraries.

Users who run other applications that use MySQL (for example, auth-mysql) should not use the bundled library, but rather specify the path to MySQL's install directory, like so: --with-mysql=/path/to/mysql. This will force PHP to use the client libraries installed by MySQL, thus avoiding any conflicts.

PHP 5+

MySQL is not enabled by default, nor is the MySQL library bundled with PHP. Read this FAQ for details on why. Use the --with-mysql[=DIR] configure option to include MySQL support. You can download headers and libraries from » MySQL.

Installation on Windows Systems

PHP 4

The PHP MySQL extension is compiled into PHP.

PHP 5+

MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Although copying libmysql.dll to the Windows system directory also works (because the system directory is by default in the system's PATH), it's not recommended.

As with enabling any PHP extension (such as php_mysql.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located. See also the Manual Windows Installation Instructions. An example extension_dir value for PHP 5 is c:\php\ext

Note: If when starting the web server an error similar to the following occurs: "Unable to load dynamic library './php_mysql.dll'", this is because php_mysql.dll and/or libmysql.dll cannot be found by the system.

MySQL Installation Notes

Warning

Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode extension. See the recode extension for more information.

Note: If you need charsets other than latin (default), you have to install external (not bundled) libmysql with compiled charset support.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

In order to have these functions available, you must compile PHP with MySQL support.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
MySQL


Stop embedded server

MySQLi_Driver
mysqli_driver::embedded_server_start
MySQLi_Driver
PHP Manual

mysqli_driver::embedded_server_end

mysqli_embedded_server_end

(PHP 5)

mysqli_driver::embedded_server_end -- mysqli_embedded_server_end — Stop embedded server

Description

void mysqli_driver::embedded_server_end ( void )
void mysqli_embedded_server_end ( void )
Warning

This function is currently not documented; only its argument list is available.

MySQLi_Driver
mysqli_driver::embedded_server_start
MySQLi_Driver


Initialize and start embedded server

mysqli_driver::embedded_server_end
MySQLi_Warning
MySQLi_Driver
PHP Manual

mysqli_driver::embedded_server_start

mysqli_embedded_server_start

(PHP 5)

mysqli_driver::embedded_server_start -- mysqli_embedded_server_start — Initialize and start embedded server

Description

bool mysqli_driver::embedded_server_start ( bool $start , array $arguments , array $groups )
bool mysqli_embedded_server_start ( bool $start , array $arguments , array $groups )
Warning

This function is currently not documented; only its argument list is available.

mysqli_driver::embedded_server_end
MySQLi_Warning
MySQLi_Driver


Get current field offset of a result pointer

MySQLi_Result
mysqli_result::data_seek
MySQLi_Result
PHP Manual

mysqli_result->current_field

mysqli_field_tell

(PHP 5)

mysqli_result->current_field -- mysqli_field_tell — Get current field offset of a result pointer

Description

Object oriented style (property):

mysqli_result
int $current_field ;

Procedural style:

int mysqli_field_tell ( mysqli_result $result )

Returns the position of the field cursor used for the last mysqli_fetch_field() call. This value can be used as an argument to mysqli_field_seek().

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns current offset of field cursor.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {

        /* get fieldpointer offset */
        $currentfield = $result->current_field;

        printf("Column %d:\n", $currentfield);
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {

        /* get fieldpointer offset */
        $currentfield = mysqli_field_tell($result);

        printf("Column %d:\n", $currentfield);
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Column 1:
Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Column 2:
Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

  • mysqli_fetch_field() - Returns the next field in the result set
  • mysqli_field_seek() - Set result pointer to a specified field offset

MySQLi_Result
mysqli_result::data_seek
MySQLi_Result


Adjusts the result pointer to an arbitary row in the result

mysqli_result->current_field
mysqli_result::fetch_all
MySQLi_Result
PHP Manual

mysqli_result::data_seek

mysqli_data_seek

(PHP 5)

mysqli_result::data_seek -- mysqli_data_seek — Adjusts the result pointer to an arbitary row in the result

Description

Object oriented style (method):

bool mysqli_result::data_seek ( int $offset )

Procedural style:

bool mysqli_data_seek ( mysqli_result $result , int $offset )

The mysqli_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

offset

The field offset. Must be between zero and the total number of rows minus one (0..mysqli_num_rows() - 1).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function can only be used with buffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($result = $mysqli->query( $query)) {

    /* seek to row no. 400 */
    $result->data_seek(399);

    /* fetch row */
    $row = $result->fetch_row();

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";

if ($result = mysqli_query($link, $query)) {

    /* seek to row no. 400 */
    mysqli_data_seek($result, 399);

    /* fetch row */
    $row = mysqli_fetch_row($result);

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

City: Benin City  Countrycode: NGA

See Also

  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_num_rows() - Gets the number of rows in a result

mysqli_result->current_field
mysqli_result::fetch_all
MySQLi_Result


Fetches all result rows as an associative array, a numeric array, or both

mysqli_result::data_seek
mysqli_result::fetch_array
MySQLi_Result
PHP Manual

mysqli_result::fetch_all

mysqli_fetch_all

(PHP 5 >= 5.3.0)

mysqli_result::fetch_all -- mysqli_fetch_all — Fetches all result rows as an associative array, a numeric array, or both

Description

Object oriented style (method):

mixed mysqli_result::fetch_all ([ int $resulttype = MYSQLI_NUM ] )

Procedural style:

mixed mysqli_fetch_all ( mysqli_result $result [, int $resulttype = MYSQLI_NUM ] )

mysqli_fetch_all() fetches all result rows and returns the result set as an associative array, a numeric array, or both.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

resulttype

This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.

Return Values

Returns an array of associative or numeric arrays holding result rows.

MySQL Native Driver Only

Available only with mysqlnd.

As mysqli_fetch_all() returns all the rows as an array in a single step, it may consume more memory than some similar functions such as mysqli_fetch_array(), which only returns one row at a time from the result set. Further, if you need to iterate over the result set, you will need a looping construct that will further impact performance. For these reasons mysqli_fetch_all() should only be used in those situations where the fetched result set will be sent to another layer for processing.

See Also

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_query() - Performs a query on the database

mysqli_result::data_seek
mysqli_result::fetch_array
MySQLi_Result


Fetch a result row as an associative, a numeric array, or both

mysqli_result::fetch_all
mysqli_result::fetch_assoc
MySQLi_Result
PHP Manual

mysqli_result::fetch_array

mysqli_fetch_array

(PHP 5)

mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both

Description

Object oriented style (method):

mixed mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] )

Procedural style:

mixed mysqli_fetch_array ( mysqli_result $result [, int $resulttype = MYSQLI_BOTH ] )

Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

resulttype

This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.

By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.

Return Values

Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli->query($query);

/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

/* free result set */
$result->close();

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);

/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

The above example will output:

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

See Also

  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitary row in the result

mysqli_result::fetch_all
mysqli_result::fetch_assoc
MySQLi_Result


Fetch a result row as an associative array

mysqli_result::fetch_array
mysqli_result::fetch_field_direct
MySQLi_Result
PHP Manual

mysqli_result::fetch_assoc

mysqli_fetch_assoc

(PHP 5)

mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row as an associative array

Description

Object oriented style (method):

array mysqli_result::fetch_assoc ( void )

Procedural style:

array mysqli_fetch_assoc ( mysqli_result $result )

Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysqli_fetch_row() or add alias names.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitary row in the result

mysqli_result::fetch_array
mysqli_result::fetch_field_direct
MySQLi_Result


Returns the next field in the result set

mysqli_result::fetch_field_direct
mysqli_result::fetch_fields
MySQLi_Result
PHP Manual

mysqli_result::fetch_field

mysqli_fetch_field

(PHP 5)

mysqli_result::fetch_field -- mysqli_fetch_field — Returns the next field in the result set

Description

Object oriented style (method):

object mysqli_result::fetch_field ( void )

Procedural style:

object mysqli_fetch_field ( mysqli_result $result )

Returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns an object which contains field definition information or FALSE if no field information is available.

Object properties
Property | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | The default value for this field, represented as a string
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {

        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {

        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

  • mysqli_num_fields() - Get the number of fields in a result
  • mysqli_fetch_field_direct() - Fetch meta-data for a single field
  • mysqli_fetch_fields() - Returns an array of objects representing the fields in a result set
  • mysqli_field_seek() - Set result pointer to a specified field offset

mysqli_result::fetch_field_direct
mysqli_result::fetch_fields
MySQLi_Result


Fetch meta-data for a single field

mysqli_result::fetch_assoc
mysqli_result::fetch_field
MySQLi_Result
PHP Manual

mysqli_result::fetch_field_direct

mysqli_fetch_field_direct

(PHP 5)

mysqli_result::fetch_field_direct -- mysqli_fetch_field_direct — Fetch meta-data for a single field

Description

Object oriented style (method):

object mysqli_result::fetch_field_direct ( int $fieldnr )

Procedural style:

object mysqli_fetch_field_direct ( mysqli_result $result , int $fieldnr )

Returns an object which contains field definition information from the specified result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

fieldnr

The field number. This value must be in the range from 0 to number of fields - 1.

Return Values

Returns an object which contains field definition information or FALSE if no field information for specified fieldnr is available.

Object attributes
Attribute | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | The default value for this field, represented as a string
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = $result->fetch_field_direct(1);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n", $finfo->type);

    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = mysqli_fetch_field_direct($result, 1);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n", $finfo->type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

  • mysqli_num_fields() - Get the number of fields in a result
  • mysqli_fetch_field() - Returns the next field in the result set
  • mysqli_fetch_fields() - Returns an array of objects representing the fields in a result set

mysqli_result::fetch_assoc
mysqli_result::fetch_field
MySQLi_Result


Returns an array of objects representing the fields in a result set

mysqli_result::fetch_field
mysqli_result::fetch_object
MySQLi_Result
PHP Manual

mysqli_result::fetch_fields

mysqli_fetch_fields

(PHP 5)

mysqli_result::fetch_fields -- mysqli_fetch_fields — Returns an array of objects representing the fields in a result set

Description

Object oriented style (method):

array mysqli_result::fetch_fields ( void )

Procedural Style:

array mysqli_fetch_fields ( mysqli_result $result )

This function serves an identical purpose to the mysqli_fetch_field() function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns an array of objects which contains field definition information or FALSE if no field information is available.

Object properties
Property | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | The default value for this field, represented as a string
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    $finfo = $result->fetch_fields();

    foreach ($finfo as $val) {
        printf("Name:     %s\n", $val->name);
        printf("Table:    %s\n", $val->table);
        printf("max. Len: %d\n", $val->max_length);
        printf("Flags:    %d\n", $val->flags);
        printf("Type:     %d\n\n", $val->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all columns */
    $finfo = mysqli_fetch_fields($result);

    foreach ($finfo as $val) {
        printf("Name:     %s\n", $val->name);
        printf("Table:    %s\n", $val->table);
        printf("max. Len: %d\n", $val->max_length);
        printf("Flags:    %d\n", $val->flags);
        printf("Type:     %d\n\n", $val->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

  • mysqli_num_fields() - Get the number of fields in a result
  • mysqli_fetch_field_direct() - Fetch meta-data for a single field
  • mysqli_fetch_field() - Returns the next field in the result set

mysqli_result::fetch_field
mysqli_result::fetch_object
MySQLi_Result


Returns the current row of a result set as an object

mysqli_result::fetch_fields
mysqli_result::fetch_row
MySQLi_Result
PHP Manual

mysqli_result::fetch_object

mysqli_fetch_object

(PHP 5)

mysqli_result::fetch_object -- mysqli_fetch_object — Returns the current row of a result set as an object

Description

Object oriented style (method):

object mysqli_result::fetch_object ([ string $class_name [, array $params ]] )

Procedural style:

object mysqli_fetch_object ( mysqli_result $result [, string $class_name [, array $params ]] )

The mysqli_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

class_name

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

Return Values

Returns an object with string properties that corresponds to the fetched row or NULL if there are no more rows in resultset.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

Changelog

Version | Description
5.0.0 | Added the ability to return as a different object.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($obj = $result->fetch_object()) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($obj = mysqli_fetch_object($result)) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitary row in the result

mysqli_result::fetch_fields
mysqli_result::fetch_row
MySQLi_Result


Get a result row as an enumerated array

mysqli_result::fetch_object
mysqli_result->field_count
MySQLi_Result
PHP Manual

mysqli_result::fetch_row

mysqli_fetch_row

(PHP 5)

mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an enumerated array

Description

Object oriented style (method):

mixed mysqli_result::fetch_row ( void )

Procedural style:

mixed mysqli_fetch_row ( mysqli_result $result )

Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

mysqli_fetch_row() returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in result set.

Note: This function sets NULL fields to the PHP NULL value.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($row = $result->fetch_row()) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_row($result)) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitary row in the result

mysqli_result::fetch_object
mysqli_result->field_count
MySQLi_Result


Get the number of fields in a result

mysqli_result::fetch_row
mysqli_result::field_seek
MySQLi_Result
PHP Manual

mysqli_result->field_count

mysqli_num_fields

(PHP 5)

mysqli_result->field_count -- mysqli_num_fields — Get the number of fields in a result

Description

Object oriented style (property):

mysqli_result
int $field_count;

Procedural style:

int mysqli_num_fields ( mysqli_result $result )

Returns the number of fields from specified result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

The number of fields from a result set.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = $result->field_count;

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = mysqli_query($link, "SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = mysqli_num_fields($result);

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Result set has 5 fields.

See Also

  • mysqli_fetch_field() - Returns the next field in the result set

mysqli_result::fetch_row
mysqli_result::field_seek
MySQLi_Result


Set result pointer to a specified field offset

mysqli_result->field_count
mysqli_result::free
MySQLi_Result
PHP Manual

mysqli_result::field_seek

mysqli_field_seek

(PHP 5)

mysqli_result::field_seek -- mysqli_field_seek — Set result pointer to a specified field offset

Description

Object oriented style (method):

bool mysqli_result::field_seek ( int $fieldnr )

Procedural style:

bool mysqli_field_seek ( mysqli_result $result , int $fieldnr )

Sets the field cursor to the given offset. The next call to mysqli_fetch_field() will retrieve the field definition of the column associated with that offset.

Note: To seek to the beginning of a row, pass an offset value of zero.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

fieldnr

The field number. This value must be in the range from 0 to number of fields - 1.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for 2nd column */
    $result->field_seek(1);
    $finfo = $result->fetch_field();

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);

    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for 2nd column */
    mysqli_field_seek($result, 1);
    $finfo = mysqli_fetch_field($result);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

See Also

  • mysqli_fetch_field() - Returns the next field in the result set

mysqli_result->field_count
mysqli_result::free
MySQLi_Result


Frees the memory associated with a result

mysqli_result::field_seek
mysqli_result->lengths
MySQLi_Result
PHP Manual

mysqli_result::free

mysqli_free_result

(PHP 5)

mysqli_result::free -- mysqli_free_result — Frees the memory associated with a result

Description

Object oriented style (all methods are equivalent):

void mysqli_result::free ( void )
void mysqli_result::close ( void )
void mysqli_result::free_result ( void )

Procedural style:

void mysqli_free_result ( mysqli_result $result )

Frees the memory associated with the result.

Note: You should always free your result with mysqli_free_result(), when your result object is not needed anymore.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

No value is returned.

See Also

  • mysqli_query() - Performs a query on the database
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

mysqli_result::field_seek
mysqli_result->lengths
MySQLi_Result


Returns the lengths of the columns of the current row in the result set

mysqli_result::free
mysqli_result->num_rows
MySQLi_Result
PHP Manual

mysqli_result->lengths

mysqli_fetch_lengths

(PHP 5)

mysqli_result->lengths -- mysqli_fetch_lengths — Returns the lengths of the columns of the current row in the result set

Description

Object oriented style (property):

mysqli_result
array $lengths;

Procedural style:

array mysqli_fetch_lengths ( mysqli_result $result )

The mysqli_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.

mysqli_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = $mysqli->query($query)) {

    $row = $result->fetch_row();

    /* display column lengths */
    foreach ($result->lengths as $i => $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = mysqli_query($link, $query)) {

    $row = mysqli_fetch_row($result);

    /* display column lengths */
    foreach (mysqli_fetch_lengths($result) as $i => $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Field  1 has Length  3
Field  2 has Length  5
Field  3 has Length 13
Field  4 has Length  9
Field  5 has Length  6
Field  6 has Length  1
Field  7 has Length  6
Field  8 has Length  4
Field  9 has Length  6
Field 10 has Length  6
Field 11 has Length  5
Field 12 has Length 44
Field 13 has Length  7
Field 14 has Length  3
Field 15 has Length  2
mysqli_result::free
mysqli_result->num_rows
MySQLi_Result


Gets the number of rows in a result

mysqli_result->lengths
MySQLi_Driver
MySQLi_Result
PHP Manual

mysqli_result->num_rows

mysqli_num_rows

(PHP 5)

mysqli_result->num_rows -- mysqli_num_rows — Gets the number of rows in a result

Description

Object oriented style (property):

mysqli_result
int $num_rows;

Procedural style:

int mysqli_num_rows ( mysqli_result $result )

Returns the number of rows in the result set.

The use of mysqli_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns number of rows in the result set.

Note: If the number of rows is greater than maximal int value, the number will be returned as a string.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = mysqli_num_rows($result);

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Result set has 239 rows.

See Also

  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_query() - Performs a query on the database

mysqli_result->lengths
MySQLi_Driver
MySQLi_Result


Returns the total number of rows changed, deleted, or inserted by the last executed statement

MySQLi_STMT
mysqli_stmt::attr_get
MySQLi_STMT
PHP Manual

mysqli_stmt->affected_rows

mysqli_stmt_affected_rows

(PHP 5)

mysqli_stmt->affected_rows -- mysqli_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement

Description

Object oriented style (property):

mysqli_stmt
int $affected_rows;

Procedural style :

int mysqli_stmt_affected_rows ( mysqli_stmt $stmt )

Returns the number of rows affected by INSERT, UPDATE, or DELETE query.

This function only works with queries which update a table. In order to get the number of rows from a SELECT query, use mysqli_stmt_num_rows() instead.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error. NULL indicates an invalid argument was supplied to the function.

Note: If the number of affected rows is greater than maximal PHP int value, the number of affected rows will be returned as a string value.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create temp table */
$mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    $stmt->bind_param("s", $code);

    /* execute statement */
    $stmt->execute();

    printf("rows inserted: %d\n", $stmt->affected_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create temp table */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = mysqli_prepare($link, $query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    mysqli_stmt_bind_param($stmt, "s", $code);

    /* execute statement */
    mysqli_stmt_execute($stmt);

    printf("rows inserted: %d\n", mysqli_stmt_affected_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

rows inserted: 17

See Also

  • mysqli_stmt_num_rows() - Return the number of rows in statements result set
  • mysqli_prepare() - Prepare a SQL statement for execution

MySQLi_STMT
mysqli_stmt::attr_get
MySQLi_STMT


Used to get the current value of a statement attribute

mysqli_stmt->affected_rows
mysqli_stmt::attr_set
MySQLi_STMT
PHP Manual

mysqli_stmt::attr_get

mysqli_stmt_attr_get

(PHP 5)

mysqli_stmt::attr_get -- mysqli_stmt_attr_get — Used to get the current value of a statement attribute

Description

Object oriented style (method):

int mysqli_stmt::attr_get ( int $attr )

Procedural style:

int mysqli_stmt_attr_get ( mysqli_stmt $stmt , int $attr )

Gets the current value of a statement attribute.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

attr

The attribute that you want to get.

Return Values

Returns FALSE if the attribute is not found, otherwise returns the value of the attribute.

mysqli_stmt->affected_rows
mysqli_stmt::attr_set
MySQLi_STMT


Used to modify the behavior of a prepared statement

mysqli_stmt::attr_get
mysqli_stmt::bind_param
MySQLi_STMT
PHP Manual

mysqli_stmt::attr_set

mysqli_stmt_attr_set

(PHP 5)

mysqli_stmt::attr_set -- mysqli_stmt_attr_set — Used to modify the behavior of a prepared statement

Description

Object oriented style (method):

bool mysqli_stmt::attr_set ( int $attr , int $mode )

Procedural style:

bool mysqli_stmt_attr_set ( mysqli_stmt $stmt , int $attr , int $mode )

Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

attr

The attribute that you want to set. It can have one of the following values:

Attribute values
Character | Description
MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH | If set to 1, causes mysqli_stmt_store_result() to update the metadata MYSQL_FIELD->max_length value.
MYSQLI_STMT_ATTR_CURSOR_TYPE | Type of cursor to open for statement when mysqli_stmt_execute() is invoked. mode can be MYSQLI_CURSOR_TYPE_NO_CURSOR (the default) or MYSQLI_CURSOR_TYPE_READ_ONLY.
MYSQLI_STMT_ATTR_PREFETCH_ROWS | Number of rows to fetch from server at a time when using a cursor. mode can be in the range from 1 to the maximum value of unsigned long. The default is 1.

If you use the MYSQLI_STMT_ATTR_CURSOR_TYPE option with MYSQLI_CURSOR_TYPE_READ_ONLY, a cursor is opened for the statement when you invoke mysqli_stmt_execute(). If there is already an open cursor from a previous mysqli_stmt_execute() call, it closes the cursor before opening a new one. mysqli_stmt_reset() also closes any open cursor before preparing the statement for re-execution. mysqli_stmt_free_result() closes any open cursor.

If you open a cursor for a prepared statement, mysqli_stmt_store_result() is unnecessary.

mode

The value to assign to the attribute.

mysqli_stmt::attr_get
mysqli_stmt::bind_param
MySQLi_STMT


Binds variables to a prepared statement as parameters

mysqli_stmt::attr_set
mysqli_stmt::bind_result
MySQLi_STMT
PHP Manual

mysqli_stmt::bind_param

mysqli_stmt_bind_param

(PHP 5)

mysqli_stmt::bind_param -- mysqli_stmt_bind_param — Binds variables to a prepared statement as parameters

Description

Object oriented style (method):

bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

Procedural style:

bool mysqli_stmt_bind_param ( mysqli_stmt $stmt , string $types , mixed &$var1 [, mixed &$... ] )

Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare().

Note: If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packets.

Note: Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

types

A string that contains one or more characters which specify the types for the corresponding bind variables:

Type specification chars
Character | Description
i | corresponding variable has type integer
d | corresponding variable has type double
s | corresponding variable has type string
b | corresponding variable is a blob and will be sent in packets

var1

The number of variables and length of string types must match the parameters in the statement.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
mysqli_stmt_execute($stmt);

printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));

/* close statement and connection */
mysqli_stmt_close($stmt);

/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", mysqli_affected_rows($link));

/* close connection */
mysqli_close($link);
?>

The above example will output:

1 Row inserted.
1 Row deleted.

See Also

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_prepare() - Prepare a SQL statement for execution
  • mysqli_stmt_send_long_data() - Send data in blocks
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

mysqli_stmt::attr_set
mysqli_stmt::bind_result
MySQLi_STMT


Binds variables to a prepared statement for result storage

mysqli_stmt::bind_param
mysqli_stmt::close
MySQLi_STMT
PHP Manual

mysqli_stmt::bind_result

mysqli_stmt_bind_result

(PHP 5)

mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables to a prepared statement for result storage

Description

Object oriented style (method):

bool mysqli_stmt::bind_result ( mixed &$var1 [, mixed &$... ] )

Procedural style:

bool mysqli_stmt_bind_result ( mysqli_stmt $stmt , mixed &$var1 [, mixed &$... ] )

Binds columns in the result set to variables.

When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ... .

Note: Note that all columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.
A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch() is called.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

var1

The variable to be bound.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    $stmt->execute();

    /* bind variables to prepared statement */
    $stmt->bind_result($col1, $col2);

    /* fetch values */
    while ($stmt->fetch()) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    $stmt->close();
}
/* close connection */
$mysqli->close();

?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = mysqli_prepare($link, "SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    mysqli_stmt_execute($stmt);

    /* bind variables to prepared statement */
    mysqli_stmt_bind_result($stmt, $col1, $col2);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

AFG Afghanistan
ALB Albania
DZA Algeria
ASM American Samoa
AND Andorra

See Also

  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_prepare() - Prepare a SQL statement for execution
  • mysqli_stmt_prepare() - Prepare a SQL statement for execution
  • mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

mysqli_stmt::bind_param
mysqli_stmt::close
MySQLi_STMT


Closes a prepared statement

mysqli_stmt::bind_result
mysqli_stmt::data_seek
MySQLi_STMT
PHP Manual

mysqli_stmt::close

mysqli_stmt_close

(PHP 5)

mysqli_stmt::close -- mysqli_stmt_close — Closes a prepared statement

Description

Object oriented style (method):

bool mysqli_stmt::close ( void )

Procedural style:

bool mysqli_stmt_close ( mysqli_stmt $stmt )

Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_prepare() - Prepare a SQL statement for execution

mysqli_stmt::bind_result
mysqli_stmt::data_seek
MySQLi_STMT


Seeks to an arbitrary row in statement result set

mysqli_stmt::close
mysqli_stmt->errno
MySQLi_STMT
PHP Manual

mysqli_stmt::data_seek

mysqli_stmt_data_seek

(PHP 5)

mysqli_stmt::data_seek -- mysqli_stmt_data_seek — Seeks to an arbitrary row in statement result set

Description

Object oriented style (method):

void mysqli_stmt::data_seek ( int $offset )

Procedural style:

void mysqli_stmt_data_seek ( mysqli_stmt $stmt , int $offset )

Seeks to an arbitrary result pointer in the statement result set.

mysqli_stmt_store_result() must be called prior to mysqli_stmt_data_seek().

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

offset

Must be between zero and the total number of rows minus one (0.. mysqli_stmt_num_rows() - 1).

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* store result */
    $stmt->store_result();

    /* seek to row no. 400 */
    $stmt->data_seek(399);

    /* fetch values */
    $stmt->fetch();

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* store result */
    mysqli_stmt_store_result($stmt);

    /* seek to row no. 400 */
    mysqli_stmt_data_seek($stmt, 399);

    /* fetch values */
    mysqli_stmt_fetch($stmt);

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

City: Benin City  Countrycode: NGA

See Also

  • mysqli_prepare() - Prepare a SQL statement for execution

mysqli_stmt::close
mysqli_stmt->errno
MySQLi_STMT


Returns the error code for the most recent statement call

mysqli_stmt::data_seek
mysqli_stmt->error
MySQLi_STMT
PHP Manual

mysqli_stmt->errno

mysqli_stmt_errno

(PHP 5)

mysqli_stmt->errno -- mysqli_stmt_errno — Returns the error code for the most recent statement call

Description

Object oriented style (property):

mysqli_stmt
int $errno;

Procedural style :

int mysqli_stmt_errno ( mysqli_stmt $stmt )

Returns the error code for the most recently invoked statement function that can succeed or fail.

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

An error code value. Zero means no error occurred.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %d.\n", $stmt->errno);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %d.\n", mysqli_stmt_errno($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Error: 1146.

See Also

  • mysqli_stmt_error() - Returns a string description for last statement error
  • mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

mysqli_stmt::data_seek
mysqli_stmt->error
MySQLi_STMT


Returns a string description for last statement error

mysqli_stmt->errno
mysqli_stmt::execute
MySQLi_STMT
PHP Manual

mysqli_stmt->error

mysqli_stmt_error

(PHP 5)

mysqli_stmt->error -- mysqli_stmt_error — Returns a string description for last statement error

Description

Object oriented style (property):

mysqli_stmt
string $error;

Procedural style:

string mysqli_stmt_error ( mysqli_stmt $stmt )

Returns a containing the error message for the most recently invoked statement function that can succeed or fail.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %s.\n", $stmt->error);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %s.\n", mysqli_stmt_error($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Error: Table 'world.myCountry' doesn't exist.

See Also

  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

mysqli_stmt->errno
mysqli_stmt::execute
MySQLi_STMT


Executes a prepared Query

mysqli_stmt->error
mysqli_stmt::fetch
MySQLi_STMT
PHP Manual

mysqli_stmt::execute

mysqli_stmt_execute

(PHP 5)

mysqli_stmt::execute -- mysqli_stmt_execute — Executes a prepared Query

Description

Object oriented style (method):

bool mysqli_stmt::execute ( void )

Procedural style:

bool mysqli_stmt_execute ( mysqli_stmt $stmt )

Executes a query that has been previously prepared using the mysqli_prepare() function. When executed any parameter markers which exist will automatically be replaced with the appropriate data.

If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function. Likewise, if the query yields a result set the mysqli_stmt_fetch() function is used.

Note: When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);

$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
$stmt->execute();

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
$stmt->execute();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row()) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    $result->close();
}

/* remove table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = mysqli_prepare($link, $query);

mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
mysqli_stmt_execute($stmt);

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
mysqli_stmt_execute($stmt);

/* close statement */
mysqli_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = mysqli_query($link, $query)) {
    while ($row = mysqli_fetch_row($result)) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    mysqli_free_result($result);
}

/* remove table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */
mysqli_close($link);
?>

The above example will output:

Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)

See Also

  • mysqli_prepare() - Prepare a SQL statement for execution
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

mysqli_stmt->error
mysqli_stmt::fetch
MySQLi_STMT


Fetch results from a prepared statement into the bound variables

mysqli_stmt::execute
mysqli_stmt->field_count
MySQLi_STMT
PHP Manual

mysqli_stmt::fetch

mysqli_stmt_fetch

(PHP 5)

mysqli_stmt::fetch -- mysqli_stmt_fetch — Fetch results from a prepared statement into the bound variables

Description

Object oriented style (method):

bool mysqli_stmt::fetch ( void )

Procedural style:

bool mysqli_stmt_fetch ( mysqli_stmt $stmt )

Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().

Note: Note that all columns must be bound by the application before calling mysqli_stmt_fetch().

Note: Data are transferred unbuffered without calling mysqli_stmt_store_result() which can decrease performance (but reduces memory cost).

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Return Values
Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occurred
NULL | No more rows/data exists or data truncation occurred

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = $mysqli->prepare($query)) {

    /* execute statement */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = mysqli_prepare($link, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)

See Also

  • mysqli_prepare() - Prepare a SQL statement for execution
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage

mysqli_stmt::execute
mysqli_stmt->field_count
MySQLi_STMT


Returns the number of field in the given statement

mysqli_stmt::fetch
mysqli_stmt::free_result
MySQLi_STMT
PHP Manual

mysqli_stmt->field_count

mysqli_stmt_field_count

(PHP 5)

mysqli_stmt->field_count -- mysqli_stmt_field_count — Returns the number of field in the given statement

Description

mysqli_stmt
int $field_count;
int mysqli_stmt_field_count ( mysqli_stmt $stmt )
Warning

This function is currently not documented; only its argument list is available.

mysqli_stmt::fetch
mysqli_stmt::free_result
MySQLi_STMT


Frees stored result memory for the given statement handle

mysqli_stmt->field_count
mysqli_stmt::get_warnings
MySQLi_STMT
PHP Manual

mysqli_stmt::free_result

mysqli_stmt_free_result

(PHP 5)

mysqli_stmt::free_result -- mysqli_stmt_free_result — Frees stored result memory for the given statement handle

Description

Object oriented style (method):

void mysqli_stmt::free_result ( void )

Procedural style:

void mysqli_stmt_free_result ( mysqli_stmt $stmt )

Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result().

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

No value is returned.

See Also

  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement

mysqli_stmt->field_count
mysqli_stmt::get_warnings
MySQLi_STMT


Get result of SHOW WARNINGS

mysqli_stmt::free_result
mysqli_stmt->insert_id
MySQLi_STMT
PHP Manual

mysqli_stmt::get_warnings

mysqli_stmt_get_warnings

(PHP 5 >= 5.1.0)

mysqli_stmt::get_warnings -- mysqli_stmt_get_warnings — Get result of SHOW WARNINGS

Description

object mysqli_stmt::get_warnings ( mysqli_stmt $stmt )
object mysqli_stmt_get_warnings ( mysqli_stmt $stmt )
Warning

This function is currently not documented; only its argument list is available.

mysqli_stmt::free_result
mysqli_stmt->insert_id
MySQLi_STMT


Get the ID generated from the previous INSERT operation

mysqli_stmt::get_warnings
mysqli_stmt::num_rows
MySQLi_STMT
PHP Manual

mysqli_stmt->insert_id

mysqli_stmt_insert_id

(PHP 5)

mysqli_stmt->insert_id -- mysqli_stmt_insert_id — Get the ID generated from the previous INSERT operation

Description

mysqli_stmt
int $insert_id;
mixed mysqli_stmt_insert_id ( mysqli_stmt $stmt )
Warning

This function is currently not documented; only its argument list is available.

mysqli_stmt::get_warnings
mysqli_stmt::num_rows
MySQLi_STMT


Return the number of rows in statements result set

mysqli_stmt->insert_id
mysqli_stmt->param_count
MySQLi_STMT
PHP Manual

mysqli_stmt::num_rows

mysqli_stmt_num_rows

(PHP 5)

mysqli_stmt::num_rows -- mysqli_stmt_num_rows — Return the number of rows in statements result set

Description

Object oriented style (property):

mysqli_stmt
int $num_rows;

Procedural style :

int mysqli_stmt_num_rows ( mysqli_stmt $stmt )

Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.

If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

An integer representing the number of rows in result set.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Number of rows: 20.

See Also

  • mysqli_stmt_affected_rows() - Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • mysqli_prepare() - Prepare a SQL statement for execution
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement

mysqli_stmt->insert_id
mysqli_stmt->param_count
MySQLi_STMT


Returns the number of parameter for the given statement

mysqli_stmt::num_rows
mysqli_stmt::prepare
MySQLi_STMT
PHP Manual

mysqli_stmt->param_count

mysqli_stmt_param_count

(PHP 5)

mysqli_stmt->param_count -- mysqli_stmt_param_count — Returns the number of parameter for the given statement

Description

Object oriented style (property):

mysqli_stmt
int $param_count;

Procedural style:

int mysqli_stmt_param_count ( mysqli_stmt $stmt )

Returns the number of parameter markers present in the prepared statement.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns an integer representing the number of parameters.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = $stmt->param_count;
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = mysqli_prepare($link, "SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = mysqli_stmt_param_count($stmt);
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Statement has 2 markers.

See Also

  • mysqli_prepare() - Prepare a SQL statement for execution

mysqli_stmt::num_rows
mysqli_stmt::prepare
MySQLi_STMT


Prepare a SQL statement for execution

mysqli_stmt->param_count
mysqli_stmt::reset
MySQLi_STMT
PHP Manual

mysqli_stmt::prepare

mysqli_stmt_prepare

(PHP 5)

mysqli_stmt::prepare -- mysqli_stmt_prepare — Prepare a SQL statement for execution

Description

Object oriented style (method)

mixed mysqli_stmt::prepare ( string $query )

Procedure style:

bool mysqli_stmt_prepare ( mysqli_stmt $stmt , string $query )

Prepares the SQL query pointed to by the null-terminated string query.

The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

query

The query, as a string. It must consist of a single SQL statement.

You can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note: You should not add a terminating semicolon or \g to the statement.

Note: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt =  $mysqli->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, 'SELECT District FROM City WHERE Name=?')) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Amersfoort is in district Utrecht

See Also

mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare, mysqli_stmt_execute() - Executes a prepared Query, mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables, mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters, mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage mysqli_stmt_close() - Closes a prepared statement.

mysqli_stmt->param_count
mysqli_stmt::reset
MySQLi_STMT


Resets a prepared statement

mysqli_stmt::prepare
mysqli_stmt::result_metadata
MySQLi_STMT
PHP Manual

mysqli_stmt::reset

mysqli_stmt_reset

(PHP 5)

mysqli_stmt::reset -- mysqli_stmt_reset — Resets a prepared statement

Description

Object oriented style (method):

bool mysqli_stmt::reset ( void )

Procedural style:

bool mysqli_stmt_reset ( mysqli_stmt $stmt )

Resets a prepared statement on client and server to state after prepare.

It resets the statement on the server, data sent using mysqli_stmt_send_long_data(), unbuffered result sets and current errors. It does not clear bindings or stored result sets. Stored result sets will be cleared when executing the prepared statement (or closing it).

To prepare a statement with another query use function mysqli_stmt_prepare().

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_prepare() - Prepare a SQL statement for execution

mysqli_stmt::prepare
mysqli_stmt::result_metadata
MySQLi_STMT


Returns result set metadata from a prepared statement

mysqli_stmt::reset
mysqli_stmt::send_long_data
MySQLi_STMT
PHP Manual

mysqli_stmt::result_metadata

mysqli_stmt_result_metadata

(PHP 5)

mysqli_stmt::result_metadata -- mysqli_stmt_result_metadata — Returns result set metadata from a prepared statement

Description

Object oriented style (method):

mysqli_result mysqli_stmt::result_metadata ( void )

Procedural style:

mysqli_result mysqli_stmt_result_metadata ( mysqli_stmt $stmt )

If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object that can be used to process the meta information such as total number of fields and individual field information.

Note: This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:

  • mysqli_num_fields()

  • mysqli_fetch_field()

  • mysqli_fetch_field_direct()

  • mysqli_fetch_fields()

  • mysqli_field_count()

  • mysqli_field_seek()

  • mysqli_field_tell()

  • mysqli_free_result()

The result set structure should be freed when you are done with it, which you can do by passing it to mysqli_free_result()

Note: The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_stmt_fetch().

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns a result object or FALSE if an error occurred.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query("DROP TABLE IF EXISTS friends");
$mysqli->query("CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = $mysqli->prepare("SELECT id, name FROM friends");
$stmt->execute();

/* get resultset for metadata */
$result = $stmt->result_metadata();

/* retrieve field information from metadata result set */
$field = $result->fetch_field();

printf("Fieldname: %s\n", $field->name);

/* close resultset */
$result->close();

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = mysqli_prepare($link, "SELECT id, name FROM friends");
mysqli_stmt_execute($stmt);

/* get resultset for metadata */
$result = mysqli_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = mysqli_fetch_field($result);

printf("Fieldname: %s\n", $field->name);

/* close resultset */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

See Also

  • mysqli_prepare() - Prepare a SQL statement for execution
  • mysqli_free_result() - Frees the memory associated with a result

mysqli_stmt::reset
mysqli_stmt::send_long_data
MySQLi_STMT


Send data in blocks

mysqli_stmt::result_metadata
mysqli_stmt::sqlstate
MySQLi_STMT
PHP Manual

mysqli_stmt::send_long_data

mysqli_stmt_send_long_data

(PHP 5)

mysqli_stmt::send_long_data -- mysqli_stmt_send_long_data — Send data in blocks

Description

Object oriented style (method)

bool mysqli_stmt::send_long_data ( int $param_nr , string $data )

Procedural style:

bool mysqli_stmt_send_long_data ( mysqli_stmt $stmt , int $param_nr , string $data )

Allows to send parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of max_allowed_packet. This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

param_nr

Indicates which parameter to associate the data with. Parameters are numbered beginning with 0.

data

A string containing data to be sent.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
    $stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
?>

See Also

  • mysqli_prepare() - Prepare a SQL statement for execution
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

mysqli_stmt::result_metadata
mysqli_stmt::sqlstate
MySQLi_STMT


Returns SQLSTATE error from previous statement operation

mysqli_stmt::send_long_data
mysqli_stmt::store_result
MySQLi_STMT
PHP Manual

mysqli_stmt::sqlstate

mysqli_stmt_sqlstate

(PHP 5)

mysqli_stmt::sqlstate -- mysqli_stmt_sqlstate — Returns SQLSTATE error from previous statement operation

Description

Object oriented style (property):

mysqli_stmt
string $sqlstate;

Procedural style:

string mysqli_stmt_sqlstate ( mysqli_stmt $stmt )

Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see » http://dev.mysql.com/doc/mysql/en/error-handling.html.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Notes

Note: Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %s.\n", $stmt->sqlstate);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %s.\n", mysqli_stmt_sqlstate($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Error: 42S02.

See Also

  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

mysqli_stmt::send_long_data
mysqli_stmt::store_result
MySQLi_STMT


Transfers a result set from a prepared statement

mysqli_stmt::sqlstate
MySQLi_Result
MySQLi_STMT
PHP Manual

mysqli_stmt::store_result

mysqli_stmt_store_result

(PHP 5)

mysqli_stmt::store_result -- mysqli_stmt_store_result — Transfers a result set from a prepared statement

Description

Object oriented style (method):

bool mysqli_stmt::store_result ( void )

Procedural style:

bool mysqli_stmt_store_result ( mysqli_stmt $stmt )

You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data.

Note: It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance in all cases. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata() returns NULL.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* free result */
    $stmt->free_result();

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* free result */
    mysqli_stmt_free_result($stmt);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Number of rows: 20.

See Also

  • mysqli_prepare() - Prepare a SQL statement for execution
  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables

mysqli_stmt::sqlstate
MySQLi_Result
MySQLi_STMT


The __construct purpose

MySQLi_Warning
mysqli_warning::next
MySQLi_Warning
PHP Manual

mysqli_warning::__construct

(No version information available, might only be in SVN)

mysqli_warning::__construct — The __construct purpose

Description

mysqli_warning::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

MySQLi_Warning
mysqli_warning::next
MySQLi_Warning


The next purpose

mysqli_warning::__construct
Aliases and deprecated Mysqli Functions
MySQLi_Warning
PHP Manual

mysqli_warning::next

(No version information available, might only be in SVN)

mysqli_warning::next — The next purpose

Description

public void mysqli_warning::next ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

mysqli_warning::__construct
Aliases and deprecated Mysqli Functions
MySQLi_Warning


Gets the number of affected rows in a previous MySQL operation

MySQLi
mysqli::autocommit
MySQLi
PHP Manual

mysqli->affected_rows

mysqli_affected_rows

(PHP 5)

mysqli->affected_rows -- mysqli_affected_rows — Gets the number of affected rows in a previous MySQL operation

Description

Object oriented style (property):

mysqli
int $affected_rows;

Procedural style:

int mysqli_affected_rows ( mysqli $link )

Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.

For SELECT statements mysqli_affected_rows() works like mysqli_num_rows().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.

Note: If the number of affected rows is greater than maximal int value, the number of affected rows will be returned as a string.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);

$mysqli->query("ALTER TABLE Language ADD Status int default 0");

/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);

/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);

/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);

$result->close();

/* Delete table Language */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));

mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");

/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));

/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));

/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));

mysqli_free_result($result);

/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");

/* close connection */
mysqli_close($link);
?>

The above example will output:

Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169

See Also

  • mysqli_num_rows() - Gets the number of rows in a result
  • mysqli_info() - Retrieves information about the most recently executed query

MySQLi
mysqli::autocommit
MySQLi


Turns on or off auto-commiting database modifications

mysqli->affected_rows
mysqli::change_user
MySQLi
PHP Manual

mysqli::autocommit

mysqli_autocommit

(PHP 5)

mysqli::autocommit -- mysqli_autocommit — Turns on or off auto-commiting database modifications

Description

Object oriented style (method)

bool mysqli::autocommit ( bool $mode )

Procedural style:

bool mysqli_autocommit ( mysqli $link , bool $mode )

Turns on or off auto-commit mode on queries for the database connection.

To determine the current state of autocommit use the SQL command SELECT @@autocommit.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

mode

Whether to turn on auto-commit or not.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function doesn't work with non transactional table types (like MyISAM or ISAM).

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
$mysqli->autocommit(TRUE);

if ($result = $mysqli->query("SELECT @@autocommit")) {
    $row = $result->fetch_row();
    printf("Autocommit is %s\n", $row[0]);
    $result->free();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
mysqli_autocommit($link, TRUE);

if ($result = mysqli_query($link, "SELECT @@autocommit")) {
    $row = mysqli_fetch_row($result);
    printf("Autocommit is %s\n", $row[0]);
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Autocommit is 1

See Also

  • mysqli_commit() - Commits the current transaction
  • mysqli_rollback() - Rolls back current transaction

mysqli->affected_rows
mysqli::change_user
MySQLi


Changes the user of the specified database connection

mysqli::autocommit
mysqli::character_set_name
MySQLi
PHP Manual

mysqli::change_user

mysqli_change_user

(PHP 5)

mysqli::change_user -- mysqli_change_user — Changes the user of the specified database connection

Description

Object oriented style (method):

bool mysqli::change_user ( string $user , string $password , string $database )

Procedural style:

bool mysqli_change_user ( mysqli $link , string $user , string $password , string $database )

Changes the user of the specified database connection and sets the current database.

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

user

The MySQL user name.

password

The MySQL password.

database

The database to change to.

If desired, the NULL value may be passed resulting in only changing the user and not selecting a database. To select a database in this case use the mysqli_select_db() function.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.

Examples

Example #1 Object oriented style

<?php

/* connect database test */
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
$mysqli->query("SET @a:=1");

/* reset all and select a new database */
$mysqli->change_user("my_user", "my_password", "world");

if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database: %s\n", $row[0]);
    $result->close();
}

if ($result = $mysqli->query("SELECT @a")) {
    $row = $result->fetch_row();
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
/* connect database test */
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
mysqli_query($link, "SET @a:=1");

/* reset all and select a new database */
mysqli_change_user($link, "my_user", "my_password", "world");

if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database: %s\n", $row[0]);
    mysqli_free_result($result);
}

if ($result = mysqli_query($link, "SELECT @a")) {
    $row = mysqli_fetch_row($result);
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Default database: world
Value of variable a is NULL

See Also

  • mysqli_connect() - Open a new connection to the MySQL server
  • mysqli_select_db() - Selects the default database for database queries

mysqli::autocommit
mysqli::character_set_name
MySQLi


Returns the default character set for the database connection

mysqli::change_user
mysqli->client_info
MySQLi
PHP Manual

mysqli::character_set_name

mysqli_character_set_name

(PHP 5)

mysqli::character_set_name -- mysqli_character_set_name — Returns the default character set for the database connection

Description

Object oriented style (method):

string mysqli::character_set_name ( void )

Procedural style:

string mysqli_character_set_name ( mysqli $link )

Returns the current character set for the database connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

The default character set for the current connection

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = $mysqli->character_set_name();
printf ("Current character set is %s\n", $charset);

$mysqli->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = mysqli_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
mysqli_close($link);
?>

The above example will output:

Current character set is latin1_swedish_ci

See Also

  • mysqli_client_encoding() - Alias of mysqli_character_set_name
  • mysqli_real_escape_string() - Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

mysqli::change_user
mysqli->client_info
MySQLi


Returns the MySQL client version as a string

mysqli::character_set_name
mysqli->client_version
MySQLi
PHP Manual

mysqli->client_info

mysqli_get_client_info

(PHP 5)

mysqli->client_info -- mysqli_get_client_info — Returns the MySQL client version as a string

Description

Object oriented style (property):

mysqli
string $client_info;

Procedural style:

string mysqli_get_client_info ( mysqli $link )

Returns a string that represents the MySQL client library version.

Return Values

A string that represents the MySQL client library version

Examples

Example #1 mysqli_get_client_info

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %s\n", mysqli_get_client_info());
?>

See Also

  • mysqli_get_client_version() - Get MySQL client info
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

mysqli::character_set_name
mysqli->client_version
MySQLi


Get MySQL client info

mysqli->client_info
mysqli::close
MySQLi
PHP Manual

mysqli->client_version

mysqli_get_client_version

(PHP 5)

mysqli->client_version -- mysqli_get_client_version — Get MySQL client info

Description

Object oriented style (property):

mysqli
int $client_version;

Procedural style:

int mysqli_get_client_version ( mysqli $link )

Returns client version number as an integer.

Return Values

A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100.

This is useful to quickly determine the version of the client library to know if some capability exits.

Examples

Example #1 mysqli_get_client_version

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %d\n", mysqli_get_client_version());
?>

See Also

  • mysqli_get_client_info() - Returns the MySQL client version as a string
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

mysqli->client_info
mysqli::close
MySQLi


Closes a previously opened database connection

mysqli->client_version
mysqli::commit
MySQLi
PHP Manual

mysqli::close

mysqli_close

(PHP 5)

mysqli::close -- mysqli_close — Closes a previously opened database connection

Description

Object oriented style (method):

bool mysqli::close ( void )

Procedural style:

bool mysqli_close ( mysqli $link )

Closes a previously opened database connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See mysqli_connect().

See Also

  • mysqli_connect() - Open a new connection to the MySQL server
  • mysqli_init() - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli_real_connect() - Opens a connection to a mysql server

mysqli->client_version
mysqli::commit
MySQLi


Commits the current transaction

mysqli::close
mysqli->connect_errno
MySQLi
PHP Manual

mysqli::commit

mysqli_commit

(PHP 5)

mysqli::commit -- mysqli_commit — Commits the current transaction

Description

Object oriented style (method)

bool mysqli::commit ( void )

Procedural style:

bool mysqli_commit ( mysqli $link )

Commits the current transaction for the database connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE Language LIKE CountryLanguage Type=InnoDB");

/* set autocommit to off */
$mysqli->autocommit(FALSE);

/* Insert some values */
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
$mysqli->commit();

/* drop table */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* set autocommit to off */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage Type=InnoDB");

/* Insert some values */
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
mysqli_commit($link);

/* close connection */
mysqli_close($link);
?>

See Also

  • mysqli_autocommit() - Turns on or off auto-commiting database modifications
  • mysqli_rollback() - Rolls back current transaction

mysqli::close
mysqli->connect_errno
MySQLi


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MySQLi Configuration Options
Name | Default | Changeable | Changelog
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mysqli.default_port | "3306" | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_socket | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_host | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_user | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_pw | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.5.
mysqli.allow_local_infile | "1" | PHP_INI_SYSTEM | Available since PHP 5.2.4.
mysqli.cache_size | "2000" | PHP_INI_SYSTEM | Available since PHP 5.3.0.

For further details and definitions of the above PHP_INI_* constants, see the chapter on configuration changes.

Here's a short explanation of the configuration directives.

mysqli.allow_persistent integer

Enable the ability to create persistent connections using mysqli_connect().

mysqli.max_persistent integer

Maximum of persistent connections that can be made. Set to 0 for unlimited.

mysqli.max_links integer

The maximum number of MySQL connections per process.

mysqli.default_port integer

The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.

mysqli.default_socket string

The default socket name to use when connecting to a local database server if no other socket name is specified.

mysqli.default_host string

The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in safe mode.

mysqli.default_user string

The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in safe mode.

mysqli.default_pw string

The default password to use when connecting to the database server if no other password is specified. Doesn't apply in safe mode.

mysqli.reconnect integer

Automatically reconnect if the connection was lost.

mysqli.allow_local_infile integer

mysqli.cache_size integer

Available only with mysqlnd.

Installation
Resource Types
Installing/Configuring


Open a new connection to the MySQL server

mysqli->connect_error
mysqli::debug
MySQLi
PHP Manual

mysqli::__construct

mysqli_connect

(PHP 5)

mysqli::__construct -- mysqli_connect — Open a new connection to the MySQL server

Description

Object oriented style (constructor):

  mysqli::__construct
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] )

Procedural style

 mysqli mysqli_connect
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] )

Opens a connection to the MySQL Server running on.

Parameters

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

Prepending host by p: opens a persistent connection. mysqli_change_user() is automatically called on connections opened from the connection pool.

username

The MySQL user name.

passwd

If not provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

dbname

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used.

Note: Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.

Return Values

Returns an object which represents the connection to a MySQL Server.

Changelog

Version | Description
5.3.0 | Added the ability of persistent connections.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

/*
 * This is the "official" OO way to do it,
 * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
 */
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

/*
 * Use this instead of $connect_error if you need to ensure
 * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
 */
if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

Example #2 Object oriented style when extending mysqli class

<?php

class foo_mysqli extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::__construct($host, $user, $pass, $db);

        if (mysqli_connect_error()) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

Example #3 Procedural style

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

The above example will output:

Success... MySQL host info: localhost via TCP/IP

Notes

Note: OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error() function or the mysqli->connect_error property like in the examples above.

Note: If it is necessary to set options, such as the connection timeout, mysqli_real_connect() must be used instead.

Note: Calling the constructor with no parameters is the same as calling mysqli_init().

Note: Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

See Also

  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_options() - Set options
  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_close() - Closes a previously opened database connection

mysqli->connect_error
mysqli::debug
MySQLi


Returns the error code from last connect call

mysqli::commit
mysqli->connect_error
MySQLi
PHP Manual

mysqli->connect_errno

mysqli_connect_errno

(PHP 5)

mysqli->connect_errno -- mysqli_connect_errno — Returns the error code from last connect call

Description

mysqli
string $connect_errno;
int mysqli_connect_errno ( void )

Returns the last error code number from the last call to mysqli_connect().

Note: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Return Values

An error code value for the last call to mysqli_connect(), if it failed. zero means no error occurred.

Examples

Example #1 Object oriented style

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

if ($mysqli->connect_errno) {
    die('Connect Error: ' . $mysqli->connect_errno);
}
?>

Example #2 Procedural style

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_errno());
}
?>

The above example will output:

Connect Error: 1045

See Also

  • mysqli_connect() - Open a new connection to the MySQL server
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

mysqli::commit
mysqli->connect_error
MySQLi


Returns a string description of the last connect error

mysqli->connect_errno
mysqli::__construct
MySQLi
PHP Manual

mysqli->connect_error

mysqli_connect_error

(PHP 5)

mysqli->connect_error -- mysqli_connect_error — Returns a string description of the last connect error

Description

mysqli
string $connect_error;
string mysqli_connect_error ( void )

Returns the last error message string from the last call to mysqli_connect().

Return Values

A string that describes the error. NULL is returned if no error occurred.

Examples

Example #1 Object oriented style

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}
?>

Example #2 Procedural style

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_error());
}
?>

The above example will output:

Connect Error: Access denied for user 'fake_user'@'localhost' (using password: YES)

Notes

Warning

The mysqli->connect_error property only works properly as of PHP versions 5.2.9 and 5.3.0. Use the mysqli_connect_error() function if compatibility with earlier PHP versions is required.

See Also

  • mysqli_connect() - Open a new connection to the MySQL server
  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

mysqli->connect_errno
mysqli::__construct
MySQLi


Predefined Constants

MYSQLI_READ_DEFAULT_GROUP

Read options from the named group from my.cnf or the file specified with MYSQLI_READ_DEFAULT_FILE

MYSQLI_READ_DEFAULT_FILE

Read options from the named option file instead of from my.cnf

MYSQLI_OPT_CONNECT_TIMEOUT

Connect timeout in seconds

MYSQLI_OPT_LOCAL_INFILE

Enables command LOAD LOCAL INFILE

MYSQLI_INIT_COMMAND

Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.

MYSQLI_CLIENT_SSL

Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library

MYSQLI_CLIENT_COMPRESS

Use compression protocol

MYSQLI_CLIENT_INTERACTIVE

Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable.

MYSQLI_CLIENT_IGNORE_SPACE

Allow spaces after function names. Makes all functions names reserved words.

MYSQLI_CLIENT_NO_SCHEMA

Don't allow the db_name.tbl_name.col_name syntax.

MYSQLI_CLIENT_MULTI_QUERIES

Allows multiple semicolon-delimited queries in a single mysqli_query() call.

MYSQLI_STORE_RESULT

For using buffered resultsets

MYSQLI_USE_RESULT

For using unbuffered resultsets

MYSQLI_ASSOC

Columns are returned into the array having the fieldname as the array index.

MYSQLI_NUM

Columns are returned into the array having an enumerated index.

MYSQLI_BOTH

Columns are returned into the array having both a numerical index and the fieldname as the associative index.

MYSQLI_NOT_NULL_FLAG

Indicates that a field is defined as NOT NULL

MYSQLI_PRI_KEY_FLAG

Field is part of a primary index

MYSQLI_UNIQUE_KEY_FLAG

Field is part of a unique index.

MYSQLI_MULTIPLE_KEY_FLAG

Field is part of an index.

MYSQLI_BLOB_FLAG

Field is defined as BLOB

MYSQLI_UNSIGNED_FLAG

Field is defined as UNSIGNED

MYSQLI_ZEROFILL_FLAG

Field is defined as ZEROFILL

MYSQLI_AUTO_INCREMENT_FLAG

Field is defined as AUTO_INCREMENT

MYSQLI_TIMESTAMP_FLAG

Field is defined as TIMESTAMP

MYSQLI_SET_FLAG

Field is defined as SET

MYSQLI_NUM_FLAG

Field is defined as NUMERIC

MYSQLI_PART_KEY_FLAG

Field is part of an multi-index

MYSQLI_GROUP_FLAG

Field is part of GROUP BY

MYSQLI_TYPE_DECIMAL

Field is defined as DECIMAL

MYSQLI_TYPE_NEWDECIMAL

Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up)

MYSQLI_TYPE_BIT

Field is defined as BIT (MySQL 5.0.3 and up)

MYSQLI_TYPE_TINY

Field is defined as TINYINT

MYSQLI_TYPE_SHORT

Field is defined as SMALLINT

MYSQLI_TYPE_LONG

Field is defined as INT

MYSQLI_TYPE_FLOAT

Field is defined as FLOAT

MYSQLI_TYPE_DOUBLE

Field is defined as DOUBLE

MYSQLI_TYPE_NULL

Field is defined as DEFAULT NULL

MYSQLI_TYPE_TIMESTAMP

Field is defined as TIMESTAMP

MYSQLI_TYPE_LONGLONG

Field is defined as BIGINT

MYSQLI_TYPE_INT24

Field is defined as MEDIUMINT

MYSQLI_TYPE_DATE

Field is defined as DATE

MYSQLI_TYPE_TIME

Field is defined as TIME

MYSQLI_TYPE_DATETIME

Field is defined as DATETIME

MYSQLI_TYPE_YEAR

Field is defined as YEAR

MYSQLI_TYPE_NEWDATE

Field is defined as DATE

MYSQLI_TYPE_INTERVAL

Field is defined as INTERVAL

MYSQLI_TYPE_ENUM

Field is defined as ENUM

MYSQLI_TYPE_SET

Field is defined as SET

MYSQLI_TYPE_TINY_BLOB

Field is defined as TINYBLOB

MYSQLI_TYPE_MEDIUM_BLOB

Field is defined as MEDIUMBLOB

MYSQLI_TYPE_LONG_BLOB

Field is defined as LONGBLOB

MYSQLI_TYPE_BLOB

Field is defined as BLOB

MYSQLI_TYPE_VAR_STRING

Field is defined as VARCHAR

MYSQLI_TYPE_STRING

Field is defined as STRING

MYSQLI_TYPE_CHAR

Field is defined as CHAR

MYSQLI_TYPE_GEOMETRY

Field is defined as GEOMETRY

MYSQLI_NEED_DATA

More data available for bind variable

MYSQLI_NO_DATA

No more data available for bind variable

MYSQLI_DATA_TRUNCATED

Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5.

MYSQLI_ENUM_FLAG

Field is defined as ENUM. Available since PHP 5.3.0.

MYSQLI_CURSOR_TYPE_FOR_UPDATE

MYSQLI_CURSOR_TYPE_NO_CURSOR

MYSQLI_CURSOR_TYPE_READ_ONLY

MYSQLI_CURSOR_TYPE_SCROLLABLE

MYSQLI_STMT_ATTR_CURSOR_TYPE

MYSQLI_STMT_ATTR_PREFETCH_ROWS

MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH

MYSQLI_SET_CHARSET_NAME

The mysqli Extension and Persistent Connections
The MySQLi Extension Function Summary
Mysqli


Performs debugging operations

mysqli::__construct
mysqli::dump_debug_info
MySQLi
PHP Manual

mysqli::debug

mysqli_debug

(PHP 5)

mysqli::debug -- mysqli_debug — Performs debugging operations

Description

Object oriented style (method):

bool mysqli::debug ( string $message )

Procedural style:

bool mysqli_debug ( string $message )

Performs debugging operations using the Fred Fish debugging library.

Parameters

message

A string representing the debugging operation to perform

Return Values

Returns TRUE.

Notes

Note: To use the mysqli_debug() function you must compile the MySQL client library to support debugging.

Examples

Example #1 Generating a Trace File

<?php

/* Create a trace file in '/tmp/client.trace' on the local (client) machine: */
mysqli_debug("d:t:o,/tmp/client.trace");

?>

See Also

  • mysqli_dump_debug_info() - Dump debugging information into the log
  • mysqli_report() - Enables or disables internal report functions

mysqli::__construct
mysqli::dump_debug_info
MySQLi


Dump debugging information into the log

mysqli::debug
mysqli->errno
MySQLi
PHP Manual

mysqli::dump_debug_info

mysqli_dump_debug_info

(PHP 5)

mysqli::dump_debug_info -- mysqli_dump_debug_info — Dump debugging information into the log

Description

Object oriented style (method):

bool mysqli::dump_debug_info ( void )

Procedural style:

bool mysqli_dump_debug_info ( mysqli $link )

This function is designed to be executed by an user with the SUPER privilege and is used to dump debugging information into the log for the MySQL Server relating to the connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_debug() - Performs debugging operations

mysqli::debug
mysqli->errno
MySQLi


Returns the error code for the most recent function call

mysqli::dump_debug_info
mysqli->error
MySQLi
PHP Manual

mysqli->errno

mysqli_errno

(PHP 5)

mysqli->errno -- mysqli_errno — Returns the error code for the most recent function call

Description

Object oriented style (property):

mysqli
int $errno;

Procedural style:

int mysqli_errno ( mysqli $link )

Returns the last error code for the most recent MySQLi function call that can succeed or fail.

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

An error code value for the last call, if it failed. zero means no error occurred.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Errorcode: %d\n", $mysqli->errno);
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errorcode: %d\n", mysqli_errno($link));
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Errorcode: 1193

See Also

  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

mysqli::dump_debug_info
mysqli->error
MySQLi


Returns a string description of the last error

mysqli->errno
mysqli->field_count
MySQLi
PHP Manual

mysqli->error

mysqli_error

(PHP 5)

mysqli->error -- mysqli_error — Returns a string description of the last error

Description

Object oriented style (property):

mysqli
string $error;

Procedural style:

string mysqli_error ( mysqli $link )

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Errormessage: %s\n", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errormessage: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Errormessage: Unknown system variable 'a'

See Also

  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

mysqli->errno
mysqli->field_count
MySQLi


Returns the number of columns for the most recent query

mysqli->error
mysqli::get_charset
MySQLi
PHP Manual

mysqli->field_count

mysqli_field_count

(PHP 5)

mysqli->field_count -- mysqli_field_count — Returns the number of columns for the most recent query

Description

Object oriented style (property):

mysqli_result
int $field_count;

Procedural style:

int mysqli_field_count ( mysqli $link )

Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the mysqli_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

An integer representing the number of fields in a result set.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query( "DROP TABLE IF EXISTS friends");
$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$mysqli->real_query("SELECT * FROM friends");

if ($mysqli->field_count) {
    /* this was a select/show or describe query */
    $result = $mysqli->store_result();

    /* process resultset */
    $row = $result->fetch_row();

    /* free resultset */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

mysqli_real_query($link, "SELECT * FROM friends");

if (mysqli_field_count($link)) {
    /* this was a select/show or describe query */
    $result = mysqli_store_result($link);

    /* process resultset */
    $row = mysqli_fetch_row($result);

    /* free resultset */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

mysqli->error
mysqli::get_charset
MySQLi


Returns client Zval cache statistics

mysqli_fetch
mysqli_get_client_stats
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_get_cache_stats

(PHP 5 >= 5.3.0)

mysqli_get_cache_stats — Returns client Zval cache statistics

Description

array mysqli_get_cache_stats ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns client Zval cache statistics. Available only with mysqlnd.

Parameters

Return Values

Returns an array with client Zval cache stats if success, FALSE otherwise.

Examples

Example #1 A mysqli_get_cache_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_cache_stats());
?>

The above example will output something similar to:

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

mysqli_fetch
mysqli_get_client_stats
Aliases and deprecated Mysqli Functions


Returns a character set object

mysqli->field_count
mysqli->get_client_info
MySQLi
PHP Manual

mysqli::get_charset

mysqli_get_charset

(PHP 5 >= 5.1.0)

mysqli::get_charset -- mysqli_get_charset — Returns a character set object

Description

object mysqli::get_charset ( void )
object mysqli_get_charset ( mysqli $link )

Returns a character set object providing several properties of the current active character set.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

The function returns a character set object with the following properties:

charset

Character set name

collation

Collation name

dir

Directory the charset description was fetched from (?) or "" for built-in character sets

min_length

Minimum character length in bytes

max_length

Maximum character length in bytes

number

Internal character set number

state

Character set status (?)

Examples

Example #1 Object oriented style

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");
  var_dump($db->get_charset());
?>

Example #2 Procedural style

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");
  var_dump($db->get_charset());
?>

The above example will output:

object(stdClass)#2 (7) {
  ["charset"]=>
  string(6) "latin1"
  ["collation"]=>
  string(17) "latin1_swedish_ci"
  ["dir"]=>
  string(0) ""
  ["min_length"]=>
  int(1)
  ["max_length"]=>
  int(1)
  ["number"]=>
  int(8)
  ["state"]=>
  int(801)
}

See Also

  • mysqli_character_set_name() - Returns the default character set for the database connection
  • mysqli_set_charset() - Sets the default client character set

mysqli->field_count
mysqli->get_client_info
MySQLi


Returns the MySQL client version as a string

mysqli::get_charset
mysqli->client_version
MySQLi
PHP Manual

mysqli->get_client_info

mysqli_get_client_info

(PHP 5)

mysqli->get_client_info -- mysqli_get_client_info — Returns the MySQL client version as a string

Description

Object oriented style (method):

string mysqli::get_client_info ( void )

Procedural style:

string mysqli_get_client_info ( mysqli $link )

Returns a string that represents the MySQL client library version.

Return Values

A string that represents the MySQL client library version

Examples

Example #1 mysqli_get_client_info

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %s\n", mysqli_get_client_info());
?>

See Also

  • mysqli_get_client_version() - Get MySQL client info
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

mysqli::get_charset
mysqli->client_version
MySQLi


Returns client per-process statistics

mysqli_get_cache_stats
mysqli_get_metadata
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_get_client_stats

(PHP 5 >= 5.3.0)

mysqli_get_client_stats — Returns client per-process statistics

Description

array mysqli_get_client_stats ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns client per-process statistics. Available only with mysqlnd.

Parameters

Return Values

Returns an array with client stats if success, FALSE otherwise.

Examples

Example #1 A mysqli_get_client_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_client_stats());
?>

The above example will output something similar to:

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

mysqli_get_cache_stats
mysqli_get_metadata
Aliases and deprecated Mysqli Functions


Get MySQL client info

mysqli->get_client_info
mysqli::get_connection_stats
MySQLi
PHP Manual

mysqli->client_version

mysqli_get_client_version

(PHP 5)

mysqli->client_version -- mysqli_get_client_version — Get MySQL client info

Description

Object oriented style (property):

mysqli
int $client_version;

Procedural style:

int mysqli_get_client_version ( mysqli $link )

Returns client version number as an integer.

Return Values

A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100.

This is useful to quickly determine the version of the client library to know if some capability exits.

Examples

Example #1 mysqli_get_client_version

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %d\n", mysqli_get_client_version());
?>

See Also

  • mysqli_get_client_info() - Returns the MySQL client version as a string
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

mysqli->get_client_info
mysqli::get_connection_stats
MySQLi


Returns statistics about the client connection

mysqli->client_version
mysqli->host_info
MySQLi
PHP Manual

mysqli::get_connection_stats

mysqli_get_connection_stats

(PHP 5 >= 5.3.0)

mysqli::get_connection_stats -- mysqli_get_connection_stats — Returns statistics about the client connection

Description

Object oriented style (method):

bool mysqli::get_connection_stats ( void )

Procedural style:

array mysqli_get_connection_stats ( mysqli $link )
Warning

This function is currently not documented; only its argument list is available.

Returns statistics about the client connection. Available only with mysqlnd.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns an array with connection stats if success, FALSE otherwise.

Examples

Example #1 A mysqli_get_connection_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_connection_stats($link));
?>

The above example will output something similar to:

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

mysqli->client_version
mysqli->host_info
MySQLi


Returns a string representing the type of connection used

mysqli::get_connection_stats
mysqli->protocol_version
MySQLi
PHP Manual

mysqli->host_info

mysqli_get_host_info

(PHP 5)

mysqli->host_info -- mysqli_get_host_info — Returns a string representing the type of connection used

Description

Object oriented style (property):

mysqli
string $host_info;

Procedural style:

string mysqli_get_host_info ( mysqli $link )

Returns a string describing the connection represented by the link parameter (including the server host name).

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

A character string representing the server hostname and the connection type.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", $mysqli->host_info);

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", mysqli_get_host_info($link));

/* close connection */
mysqli_close($link);
?>

The above example will output:

Host info: Localhost via UNIX socket

See Also

  • mysqli_get_proto_info() - Returns the version of the MySQL protocol used

mysqli::get_connection_stats
mysqli->protocol_version
MySQLi


Returns the version of the MySQL protocol used

mysqli->host_info
mysqli->server_info
MySQLi
PHP Manual

mysqli->protocol_version

mysqli_get_proto_info

(PHP 5)

mysqli->protocol_version -- mysqli_get_proto_info — Returns the version of the MySQL protocol used

Description

Object oriented style (property):

mysqli
string $protocol_version;

Procedural style:

int mysqli_get_proto_info ( mysqli $link )

Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns an integer representing the protocol version.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $mysqli->protocol_version);

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", mysqli_get_proto_info($link));

/* close connection */
mysqli_close($link);
?>

The above example will output:

Protocol version: 10

See Also

  • mysqli_get_host_info() - Returns a string representing the type of connection used

mysqli->host_info
mysqli->server_info
MySQLi


Returns the version of the MySQL server

mysqli->protocol_version
mysqli->server_version
MySQLi
PHP Manual

mysqli->server_info

mysqli_get_server_info

(PHP 5)

mysqli->server_info -- mysqli_get_server_info — Returns the version of the MySQL server

Description

Object oriented style (property):

mysqli
string $server_info;

Procedural style:

string mysqli_get_server_info ( mysqli $link )

Returns a string representing the version of the MySQL server that the MySQLi extension is connected to.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

A character string representing the server version.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", $mysqli->server_info);

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", mysqli_get_server_info($link));

/* close connection */
mysqli_close($link);
?>

The above example will output:

Server version: 4.1.2-alpha-debug

See Also

  • mysqli_get_client_info() - Returns the MySQL client version as a string
  • mysqli_get_client_version() - Get MySQL client info
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

mysqli->protocol_version
mysqli->server_version
MySQLi


Returns the version of the MySQL server as an integer

mysqli->server_info
mysqli::get_warnings
MySQLi
PHP Manual

mysqli->server_version

mysqli_get_server_version

(PHP 5)

mysqli->server_version -- mysqli_get_server_version — Returns the version of the MySQL server as an integer

Description

Object oriented style (property):

mysqli
int $server_version;

Procedural style:

int mysqli_get_server_version ( mysqli $link )

The mysqli_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

An integer representing the server version.

The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 4.1.0 is 40100).

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", $mysqli->server_version);

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", mysqli_get_server_version($link));

/* close connection */
mysqli_close($link);
?>

The above example will output:

Server version: 40102

See Also

  • mysqli_get_client_info() - Returns the MySQL client version as a string
  • mysqli_get_client_version() - Get MySQL client info
  • mysqli_get_server_info() - Returns the version of the MySQL server

mysqli->server_info
mysqli::get_warnings
MySQLi


Get result of SHOW WARNINGS

mysqli->server_version
mysqli->info
MySQLi
PHP Manual

mysqli::get_warnings

mysqli_get_warnings

(PHP 5 >= 5.1.0)

mysqli::get_warnings -- mysqli_get_warnings — Get result of SHOW WARNINGS

Description

mysqli_warnings mysqli::get_warnings ( void )
mysqli_warnings mysqli_get_warnings ( mysqli $link )
Warning

This function is currently not documented; only its argument list is available.

mysqli->server_version
mysqli->info
MySQLi


Retrieves information about the most recently executed query

mysqli::get_warnings
mysqli::init
MySQLi
PHP Manual

mysqli->info

mysqli_info

(PHP 5)

mysqli->info -- mysqli_info — Retrieves information about the most recently executed query

Description

Object oriented style (property)

mysqli
string $info;

Procedural style:

string mysqli_info ( mysqli $link )

The mysqli_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

Possible mysqli_info return values
Query type | Example result string
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0

Note: Queries which do not fall into one of the above formats are not supported. In these situations, mysqli_info() will return an empty string.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

A character string representing additional information about the most recently executed query.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
$mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", $mysqli->info);

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
mysqli_query($link, "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", mysqli_info($link));

/* close connection */
mysqli_close($link);
?>

The above example will output:

Records: 150  Duplicates: 0  Warnings: 0

See Also

  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysqli_warning_count() - Returns the number of warnings from the last query for the given link
  • mysqli_num_rows() - Gets the number of rows in a result

mysqli::get_warnings
mysqli::init
MySQLi


Initializes MySQLi and returns a resource for use with mysqli_real_connect()

mysqli->info
mysqli->insert_id
MySQLi
PHP Manual

mysqli::init

mysqli_init

(PHP 5)

mysqli::init -- mysqli_init — Initializes MySQLi and returns a resource for use with mysqli_real_connect()

Description

Object oriented style (method):

mysqli mysqli::init ( void )

Procedural style:

mysqli mysqli_init ( void )

Allocates or initializes a MYSQL object suitable for mysqli_options() and mysqli_real_connect().

Note: Any subsequent calls to any mysqli function (except mysqli_options()) will fail until mysqli_real_connect() was called.

Return Values

Returns an object.

Examples

See mysqli_real_connect().

See Also

  • mysqli_options() - Set options
  • mysqli_close() - Closes a previously opened database connection
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_connect() - Open a new connection to the MySQL server

mysqli->info
mysqli->insert_id
MySQLi


Returns the auto generated id used in the last query

mysqli::init
mysqli::kill
MySQLi
PHP Manual

mysqli->insert_id

mysqli_insert_id

(PHP 5)

mysqli->insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query

Description

Object oriented style (property):

mysqli
mixed $insert_id;

Procedural style:

mixed mysqli_insert_id ( mysqli $link )

The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

Note: Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.

Note: If the number is greater than maximal int value, mysqli_insert_id() will return a string.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* drop table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
mysqli_query($link, $query);

printf ("New Record has id %d.\n", mysqli_insert_id($link));

/* drop table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */
mysqli_close($link);
?>

The above example will output:

New Record has id 1.
mysqli::init
mysqli::kill
MySQLi


Installation

As of PHP 5.0, MySQL support is no longer enabled by default with the standard PHP distributions. This means PHP needs to be explicitly configured to take advantage of the MySQL extensions.

The common Unix distributions include binary versions of PHP that can be installed. Although these binary versions are typically built with support for MySQL extensions enabled, the extension libraries themselves may need to be installed using an additional package. Check the package manager than comes with your chosen distribution for availability.

Unless your Unix distribution comes with a binary package of PHP with the mysqli extension available, you will need to build PHP from source code. Building PHP from source allows you to specify the MySQL extensions you want to use, as well as your choice of client library for each extension.

To ensure that the mysqli extension for PHP is enabled, you will need to configure the PHP source code to use mysqli. This is achieved by running the configure script with the option --with-mysqli=mysql_config_path/mysql_config, prior to building PHP. This will enable mysqli and it will use the MySQL Client Library (libmysql) to communicate with the MySQL Server.

Note: The mysql_config_path represents the location of the mysql_config program that comes with MySQL Server.

With versions of PHP 5.3 and newer, you can alternatively use the new MySQL Native Driver with mysqli. This gives a number of benefits over using libmysql.

To use MySQL Native Driver with mysqli you need to configure the PHP source code using the --with-mysqli=mysqlnd option, prior to building PHP.

This is the recommended option, as using the MySQL Native Driver results in improved performance and gives access to features not available when using the MySQL Client Library. Refer to What is PHP's MySQL Native Driver? for a brief overview of the advantages of MySQL Native Driver.

Note that it is possible to freely mix MySQL extensions and client libraries. For example, it is possible to enable the MySQL extension to use the MySQL Client Library (libmysql), while configuring the mysqli extension to use the MySQL Native Driver. However, all permutations of extension and client library are possible.

The following example builds the MySQL extension to use the MySQL Client Library, and the mysqli and PDO MYSQL extensions to use the MySQL Native Driver:

./configure --with-mysql=/usr/bin/mysql_config \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd
[other options]

Installation on Windows Systems

On Windows, PHP is most commonly installed using the binary installer. Once PHP has been installed, some configuration is required to enable mysqli and specify the client library you want it to use.

As mentioned earlier, the mysqli extension is not enabled by default, so the php_mysqli.dll DLL must be enabled inside of php.ini. In order to do this you need to find the php.ini file (typically located in c:\php), and make sure you remove the comment (semi-colon) from the start of the line extension=php_mysqli.dll, in the section marked [PHP_MYSQLI].

Also, if you want to use the MySQL Client Library with mysqli, you need to make sure PHP can access the client library file. The MySQL Client Library is included as a file named libmysql.dll in the Windows PHP distribution. This file needs to be available in the Windows system's PATH environment variable, so that it can be successfully loaded. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Copying libmysql.dll to the Windows system directory (typically c:\Windows\system) also works, as the system directory is by default in the system's PATH. However, this practice is strongly discouraged.

On Windows, for PHP versions 5.3 and newer, the mysqli extension uses the MySQL Native Driver by default. This means you don't need to worry about configuring access to libmysql.dll, you just need to make sure the extension is enabled in the php.ini file.

As with enabling any PHP extension (such as php_mysqli.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located. See also the Manual Windows Installation Instructions. An example extension_dir value for PHP 5 is c:\php\ext.

Note: If when starting the web server an error similar to the following occurs: "Unable to load dynamic library './php_mysqli.dll'", this is because php_mysqli.dll and/or libmysql.dll cannot be found by the system.

Requirements
Runtime Configuration
Installing/Configuring


Asks the server to kill a MySQL thread

mysqli->insert_id
mysqli::more_results
MySQLi
PHP Manual

mysqli::kill

mysqli_kill

(PHP 5)

mysqli::kill -- mysqli_kill — Asks the server to kill a MySQL thread

Description

Object oriented style (method)

bool mysqli::kill ( int $processid )

Procedural style:

bool mysqli_kill ( mysqli $link , int $processid )

This function is used to ask the server to kill a MySQL thread specified by the processid parameter. This value must be retrieved by calling the mysqli_thread_id() function.

To stop a running query you should use the SQL command KILL QUERY processid.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = $mysqli->thread_id;

/* Kill connection */
$mysqli->kill($thread_id);

/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli->error);
    exit;
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = mysqli_thread_id($link);

/* Kill connection */
mysqli_kill($link, $thread_id);

/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", mysqli_error($link));
    exit;
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Error: MySQL server has gone away

See Also

  • mysqli_thread_id() - Returns the thread ID for the current connection

mysqli->insert_id
mysqli::more_results
MySQLi


Check if there are any more query results from a multi query

mysqli::kill
mysqli::multi_query
MySQLi
PHP Manual

mysqli::more_results

mysqli_more_results

(PHP 5)

mysqli::more_results -- mysqli_more_results — Check if there are any more query results from a multi query

Description

bool mysqli::more_results ( void )
bool mysqli_more_results ( mysqli $link )

Indicates if one or more result sets are available from a previous call to mysqli_multi_query().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See mysqli_multi_query().

See Also

  • mysqli_multi_query() - Performs a query on the database
  • mysqli_next_result() - Prepare next result from multi_query
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

mysqli::kill
mysqli::multi_query
MySQLi


Performs a query on the database

mysqli::more_results
mysqli::next_result
MySQLi
PHP Manual

mysqli::multi_query

mysqli_multi_query

(PHP 5)

mysqli::multi_query -- mysqli_multi_query — Performs a query on the database

Description

Object oriented style (method):

bool mysqli::multi_query ( string $query )

Procedural style:

bool mysqli_multi_query ( mysqli $link , string $query )

Executes one or multiple queries which are concatenated by a semicolon.

To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query, as a string.

Data inside the query should be properly escaped.

Return Values

Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_store_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

The above example will output something similar to:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

See Also

  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_next_result() - Prepare next result from multi_query
  • mysqli_more_results() - Check if there are any more query results from a multi query

mysqli::more_results
mysqli::next_result
MySQLi


Prepare next result from multi_query

mysqli::multi_query
mysqli::options
MySQLi
PHP Manual

mysqli::next_result

mysqli_next_result

(PHP 5)

mysqli::next_result -- mysqli_next_result — Prepare next result from multi_query

Description

bool mysqli::next_result ( void )
bool mysqli_next_result ( mysqli $link )

Prepares next result set from a previous call to
mysqli_multi_query() which can be retrieved by
mysqli_store_result() or
mysqli_use_result().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See mysqli_multi_query().

See Also

  • mysqli_multi_query() - Performs a query on the database
  • mysqli_more_results() - Check if there are any more query results from a multi query
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

mysqli::multi_query
mysqli::options
MySQLi


Set options

mysqli::next_result
mysqli::ping
MySQLi
PHP Manual

mysqli::options

mysqli_options

(PHP 5)

mysqli::options -- mysqli_options — Set options

Description

Object oriented style (method)

bool mysqli::options ( int $option , mixed $value )

Procedural style:

bool mysqli_options ( mysqli $link , int $option , mixed $value )

Used to set extra connect options and affect behavior for a connection.

This function may be called multiple times to set several options.

mysqli_options() should be called after
mysqli_init() and before
mysqli_real_connect().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

option

The option that you want to set. It can be one of the following values:

Valid options
Name | Description
MYSQLI_OPT_CONNECT_TIMEOUT | connection timeout in seconds (supported on Windows with TCP/IP since PHP 5.3.1)
MYSQLI_OPT_LOCAL_INFILE | enable/disable use of LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND | command to execute after when connecting to MySQL server
MYSQLI_READ_DEFAULT_FILE | Read options from named option file instead of my.cnf
MYSQLI_READ_DEFAULT_GROUP | Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE.

value

The value for the option.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See mysqli_real_connect().

See Also

  • mysqli_init() - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli_real_connect() - Opens a connection to a mysql server

mysqli::next_result
mysqli::ping
MySQLi


Overview

This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database.

What is an API?

An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.

APIs can be procedural or object-oriented. With a procedural API you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two the latter is usually the preferred interface, as it is more modern and leads to better organised code.

When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application.

What is a Connector?

In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP.

If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server.

What is a Driver?

A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server.

By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server.

Sometimes people use the terms connector and driver interchangeably, this can be confusing. In the MySQL-related documentation the term "driver" is reserved for software that provides the database-specific part of a connector package.

What is an Extension?

In the PHP documentation you will come across another term - extension. The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extensions, such as the mysqli extension, and the mysql extension, are implemented using the PHP extension framework.

An extension typically exposes an API to the PHP programmer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP programmer.

The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.

The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer.

What are the main PHP API offerings for using MySQL?

There are three main API options when considering connecting to a MySQL database server:

  • PHP's MySQL Extension

  • PHP's mysqli Extension

  • PHP Data Objects (PDO)

Each has its own advantages and disadvantages. The following discussion aims to give a brief introduction to the key aspects of each API.

What is PHP's MySQL Extension?

This is the original extension designed to allow you to develop PHP applications that interact with a MySQL database. The mysql extension provides a procedural interface and is intended for use only with MySQL versions older than 4.1.3. This extension can be used with versions of MySQL 4.1.3 or newer, but not all of the latest MySQL server features will be available.

Note: If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use the mysqli extension instead.

The mysql extension source code is located in the PHP extension directory ext/mysql.

For further information on the mysql extension, see MySQL.

What is PHP's mysqli Extension?

The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.

The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

  • Object-oriented interface

  • Support for Prepared Statements

  • Support for Multiple Statements

  • Support for Transactions

  • Enhanced debugging capabilities

  • Embedded server support

Note: If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use this extension.

As well as the object-oriented interface the extension also provides a procedural interface.

The mysqli extension is built using the PHP extension framework, its source code is located in the directory ext/mysqli.

For further information on the mysqli extension, see Mysqli.

What is PDO?

PHP Data Objects, or PDO, is a database abstraction layer specifically for PHP applications. PDO provides a consistent API for your PHP application regardless of the type of database server your application will connect to. In theory, if you are using the PDO API, you could switch the database server you used, from say Firebird to MySQL, and only need to make minor changes to your PHP code.

Other examples of database abstraction layers include JDBC for Java applications and DBI for Perl.

While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is that it doesn't allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL's support for Multiple Statements.

PDO is implemented using the PHP extension framework, its source code is located in the directory ext/pdo.

For further information on PDO, see the PDO.

What is the PDO MYSQL driver?

The PDO MYSQL driver is not an API as such, at least from the PHP programmer's perspective. In fact the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL-specific functionality. The programmer still calls the PDO API, but PDO uses the PDO MYSQL driver to carry out communication with the MySQL server.

The PDO MYSQL driver is one of several available PDO drivers. Other PDO drivers available include those for the Firebird and PostgreSQL database servers.

The PDO MYSQL driver is implemented using the PHP extension framework. Its source code is located in the directory ext/pdo_mysql. It does not expose an API to the PHP programmer.

For further information on the PDO MYSQL driver, see MySQL (PDO).

What is PHP's MySQL Native Driver?

In order to communicate with the MySQL database server the mysql extension, mysqli and the PDO MYSQL driver each use a low-level library that implements the required protocol. In the past, the only available library was the MySQL Client Library, otherwise known as libmysql.

However, the interface presented by libmysql was not optimized for communication with PHP applications, as libmysql was originally designed with C applications in mind. For this reason the MySQL Native Driver, mysqlnd, was developed as an alternative to libmysql for PHP applications.

The mysql extension, the mysqli extension and the PDO MySQL driver can each be individually configured to use either libmysql or mysqlnd. As mysqlnd is designed specifically to be utilised in the PHP system it has numerous memory and speed enhancements over libmysql. You are strongly encouraged to take advantage of these improvements.

Note: The MySQL Native Driver can only be used with MySQL server versions 4.1.3 and later.

The MySQL Native Driver is implemented using the PHP extension framework. The source code is located in ext/mysqlnd. It does not expose an API to the PHP programmer.

Comparison of Features

The following table compares the functionality of the three main methods of connecting to MySQL from PHP:

 | PHP's mysqli Extension | PDO (Using PDO MySQL Driver and MySQL Native Driver) | PHP's MySQL Extension
PHP version introduced | 5.0 | 5.0 | Prior to 3.0
Included with PHP 5.x | yes | yes | Yes
Comes with PHP 6.0 | Yes | Yes | Yes
MySQL development status | Active development | Active development as of PHP 5.3 | Maintenance only
Recommended by MySQL for new projects | Yes - preferred option | Yes | No
API supports Charsets | Yes | Yes | No
API supports server-side Prepared Statements | Yes | Yes | No
API supports client-side Prepared Statements | No | Yes | No
API supports Stored Procedures | Yes | Yes | No
API supports Multiple Statements | Yes | Most | No
Supports all MySQL 4.1+ functionality | Yes | Most | No
Introduction
Installing/Configuring
Mysqli


The mysqli Extension and Persistent Connections

Persistent connection support was introduced in PHP 5.3 for the mysqli extension. Support was already present in PDO MYSQL and ext/mysql. The idea behind persistent connections is that a connection between a client process and a database can be reused by a client process, rather than being created and destroyed multiple times. This reduces the overhead of creating fresh connections every time one is required, as unused connections are cached and ready to be reused.

Unlike the mysql extension, mysqli does not provide a separate function for opening persistent connections. To open a persistent connection you must prepend p: to the hostname when connecting.

The problem with persistent connections is that they can be left in unpredictable states by clients. For example, a table lock might be activated before a client terminates unexpectedly. A new client process reusing this persistent connection will get the connection "as is". Any cleanup would need to be done by the new client process before it could make good use of the persistent connection, increasing the burden on the programmer.

The persistent connection of the mysqli extension however provides built-in cleanup handling code. The cleanup carried out by mysqli includes:

  • Rollback active transactions

  • Close and drop temporary tables

  • Unlock tables

  • Reset session variables

  • Close prepared statements (always happens with PHP)

  • Close handler

  • Release locks acquired with GET_LOCK()

This ensures that persistent connections are in a clean state on return from the connection pool, before the client process uses them.

The mysqli extension does this cleanup by automatically calling the C-API function mysql_change_user().

The automatic cleanup feature has advantages and disadvantages though. The advantage is that the programmer no longer needs to worry about adding cleanup code, as it is called automatically. However, the disadvantage is that the code could potentially be a little slower, as the code to perform the cleanup needs to run each time a connection is returned from the connection pool.

It is possible to switch off the automatic cleanup code, by compiling PHP with MYSQLI_NO_CHANGE_USER_ON_PCONNECT defined.

Note: The mysqli extension supports persistent connections when using either MySQL Native Driver or MySQL Client Library.

Resource Types
Predefined Constants
Mysqli


Pings a server connection, or tries to reconnect if the connection has gone down

mysqli::options
mysqli::poll
MySQLi
PHP Manual

mysqli::ping

mysqli_ping

(PHP 5)

mysqli::ping -- mysqli_ping — Pings a server connection, or tries to reconnect if the connection has gone down

Description

Object oriented style (method):

bool mysqli::ping ( void )

Procedural style:

bool mysqli_ping ( mysqli $link )

Checks whether the connection to the server is working. If it has gone down, and global option mysqli.reconnect is enabled an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* check if server is alive */
if ($mysqli->ping()) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* check if server is alive */
if (mysqli_ping($link)) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Our connection is ok!
mysqli::options
mysqli::poll
MySQLi


Poll connections

mysqli::ping
mysqli::prepare
MySQLi
PHP Manual

mysqli::poll

mysqli_poll

(PHP 5 >= 5.3.0)

mysqli::poll -- mysqli_poll — Poll connections

Description

public int mysqli::poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )
int mysqli_poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )
Warning

This function is currently not documented; only its argument list is available.

Poll connections. Available only with mysqlnd.

Parameters

read

error

reject

sec

Number of seconds to wait, must be non-negative.

usec

Number of microseconds to wait, must be non-negative.

Return Values

Returns number of ready connections in success, FALSE otherwise.

Examples

Example #1 A mysqli_poll() example

<?php
$link1 = mysqli_connect();
$link1->query("SELECT 'test'", MYSQLI_ASYNC);
$all_links = array($link1);
$processed = 0;
do {
    $links = $errors = $reject = array();
    foreach ($all_links as $link) {
        $links[] = $errors[] = $reject[] = $link;
    }
    if (!mysqli_poll($links, $errors, $reject, 1)) {
        continue;
    }
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            print_r($result->fetch_row());
            mysqli_free_result($result);
            $processed++;
        }
    }
} while ($processed < count($all_links));
?>

The above example will output:

Array
(
    [0] => test
)

See Also

mysqli::ping
mysqli::prepare
MySQLi


Prepare a SQL statement for execution

mysqli::poll
mysqli::query
MySQLi
PHP Manual

mysqli::prepare

mysqli_prepare

(PHP 5)

mysqli::prepare -- mysqli_prepare — Prepare a SQL statement for execution

Description

Object oriented style (method)

mysqli_stmt mysqli::prepare ( string $query )

Procedure style:

mysqli_stmt mysqli_prepare ( mysqli $link , string $query )

Prepares the SQL query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.

The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query, as a string.

Note: You should not add a terminating semicolon or \g to the statement.

This parameter can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

Return Values

mysqli_prepare() returns a statement object or FALSE if an error occurred.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Amersfoort is in district Utrecht

See Also

  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_close() - Closes a prepared statement

mysqli::poll
mysqli::query
MySQLi


Performs a query on the database

mysqli::prepare
mysqli::real_connect
MySQLi
PHP Manual

mysqli::query

mysqli_query

(PHP 5)

mysqli::query -- mysqli_query — Performs a query on the database

Description

Object oriented style (method):

mixed mysqli::query ( string $query [, int $resultmode ] )

Procedural style:

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode ] )

Performs a query against the database.

Functionally, using this function is identical to calling
mysqli_real_query() followed either by
mysqli_use_result() or
mysqli_store_result().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query string.

Data inside the query should be properly escaped.

resultmode

Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result()

With MYSQLI_ASYNC (available with mysqlnd), it is possible to perform query asynchronously. mysqli_poll() is then used to get results from such queries.

Return Values

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a result object. For other successful queries mysqli_query() will return TRUE.

Changelog

Version | Description
5.3.0 | Added the ability of async queries.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", mysqli_num_rows($result));

    /* free result set */
    mysqli_free_result($result);
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!mysqli_query($link, "SET @a:='this will not work'")) {
        printf("Error: %s\n", mysqli_error($link));
    }
    mysqli_free_result($result);
}

mysqli_close($link);
?>

The above example will output:

Table myCity successfully created.
Select returned 10 rows.
Error: Commands out of sync;  You can't run this command now

See Also

  • mysqli_real_query() - Execute an SQL query
  • mysqli_multi_query() - Performs a query on the database
  • mysqli_free_result() - Frees the memory associated with a result

mysqli::prepare
mysqli::real_connect
MySQLi


Opens a connection to a mysql server

mysqli::query
mysqli::real_escape_string
MySQLi
PHP Manual

mysqli::real_connect

mysqli_real_connect

(PHP 5)

mysqli::real_connect -- mysqli_real_connect — Opens a connection to a mysql server

Description

Object oriented style (method)

bool mysqli::real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )

Procedural style

bool mysqli_real_connect ( mysqli $link [, string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )

Establish a connection to a MySQL database engine.

This function differs from mysqli_connect():

  • mysqli_real_connect() needs a valid object which has to be created by function mysqli_init().

  • With the mysqli_options() function you can set various options for connection.

  • There is a flags parameter.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

username

The MySQL user name.

passwd

If provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

dbname

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used.

Note: Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.

flags

With the parameter flags you can set different connection options:

Supported flags
Name | Description
MYSQLI_CLIENT_COMPRESS | Use compression protocol
MYSQLI_CLIENT_FOUND_ROWS | return number of matched rows, not the number of affected rows
MYSQLI_CLIENT_IGNORE_SPACE | Allow spaces after function names. Makes all function names reserved words.
MYSQLI_CLIENT_INTERACTIVE | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection
MYSQLI_CLIENT_SSL | Use SSL (encryption)

Note: For security reasons the MULTI_STATEMENT flag is not supported in PHP. If you want to execute multiple queries use the mysqli_multi_query() function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php

$mysqli = mysqli_init();
if (!$mysqli) {
    die('mysqli_init failed');
}

if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db')) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

Example #2 Object oriented style when extending mysqli class

<?php

class foo_mysqli extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::init();

        if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
            die('Setting MYSQLI_INIT_COMMAND failed');
        }

        if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
            die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
        }

        if (!parent::real_connect($host, $user, $pass, $db)) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

Example #3 Procedural style

<?php

$link = mysqli_init();
if (!$link) {
    die('mysqli_init failed');
}

if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'my_db')) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

The above example will output:

Success... MySQL host info: localhost via TCP/IP

See Also

  • mysqli_connect() - Open a new connection to the MySQL server
  • mysqli_init() - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli_options() - Set options
  • mysqli_ssl_set() - Used for establishing secure connections using SSL
  • mysqli_close() - Closes a previously opened database connection

mysqli::query
mysqli::real_escape_string
MySQLi


Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

mysqli::real_connect
mysqli::real_query
MySQLi
PHP Manual

mysqli::real_escape_string

mysqli_real_escape_string

(PHP 5)

mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

Description

Object oriented style (both methods are equivalent):

string mysqli::escape_string ( string $escapestr )
string mysqli::real_escape_string ( string $escapestr )

Procedural style:

string mysqli_real_escape_string ( mysqli $link , string $escapestr )

This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string, taking into account the current character set of the connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

escapestr

The string to be escaped.

Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Return Values

Returns an escaped string.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", $mysqli->sqlstate);
}

$city = $mysqli->real_escape_string($city);

/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

mysqli_close($link);
?>

The above example will output:

Error: 42000
1 Row inserted.

See Also

  • mysqli_character_set_name() - Returns the default character set for the database connection

mysqli::real_connect
mysqli::real_query
MySQLi


Execute an SQL query

mysqli::real_escape_string
mysqli::reap_async_query
MySQLi
PHP Manual

mysqli::real_query

mysqli_real_query

(PHP 5)

mysqli::real_query -- mysqli_real_query — Execute an SQL query

Description

Object oriented style (method):

bool mysqli::real_query ( string $query )

Procedural style

bool mysqli_real_query ( mysqli $link , string $query )

Executes a single query against the database whose result can then be retrieved or stored using the mysqli_store_result() or mysqli_use_result() functions.

In order to determine if a given query should return a result set or not, see mysqli_field_count().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query, as a string.

Data inside the query should be properly escaped.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_query() - Performs a query on the database
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

mysqli::real_escape_string
mysqli::reap_async_query
MySQLi


Get result from async query

mysqli::real_query
mysqli::rollback
MySQLi
PHP Manual

mysqli::reap_async_query

mysqli_reap_async_query

(PHP 5 >= 5.3.0)

mysqli::reap_async_query -- mysqli_reap_async_query — Get result from async query

Description

public mysqli_result mysqli::reap_async_query ( void )
mysqli_result mysqli_reap_async_query ( mysql $link )
Warning

This function is currently not documented; only its argument list is available.

Get result from async query. Available only with mysqlnd.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns mysqli_result in success, FALSE otherwise.

See Also

  • mysqli_poll() - Poll connections

mysqli::real_query
mysqli::rollback
MySQLi


Requirements

In order to have these functions available, you must compile PHP with support for the mysqli extension.

Note: The mysqli extension is designed to work with MySQL version 4.1.13 or newer, or 5.0.7 or newer. For previous versions, please see the MySQL extension documentation.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension has no resource types defined.

Runtime Configuration
The mysqli Extension and Persistent Connections
Installing/Configuring


Rolls back current transaction

mysqli::reap_async_query
mysqli::select_db
MySQLi
PHP Manual

mysqli::rollback

mysqli_rollback

(PHP 5)

mysqli::rollback -- mysqli_rollback — Rolls back current transaction

Description

Object oriented style (method):

bool mysqli::rollback ( void )

Procedural style:

bool mysqli_rollback ( mysqli $link )

Rollbacks the current transaction for the database.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
$mysqli->autocommit(FALSE);

$mysqli->query("CREATE TABLE myCity LIKE City");
$mysqli->query("ALTER TABLE myCity Type=InnoDB");
$mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
$mysqli->commit();

/* delete all rows */
$mysqli->query("DELETE FROM myCity");

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Rollback */
$mysqli->rollback();

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Drop table myCity */
$mysqli->query("DROP TABLE myCity");

$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE myCity LIKE City");
mysqli_query($link, "ALTER TABLE myCity Type=InnoDB");
mysqli_query($link, "INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
mysqli_commit($link);

/* delete all rows */
mysqli_query($link, "DELETE FROM myCity");

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Rollback */
mysqli_rollback($link);

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Drop table myCity */
mysqli_query($link, "DROP TABLE myCity");

mysqli_close($link);
?>

The above example will output:

0 rows in table myCity.
50 rows in table myCity (after rollback).

See Also

  • mysqli_commit() - Commits the current transaction
  • mysqli_autocommit() - Turns on or off auto-commiting database modifications

mysqli::reap_async_query
mysqli::select_db
MySQLi


Selects the default database for database queries

mysqli::rollback
mysqli::set_charset
MySQLi
PHP Manual

mysqli::select_db

mysqli_select_db

(PHP 5)

mysqli::select_db -- mysqli_select_db — Selects the default database for database queries

Description

Object oriented style (method):

bool mysqli::select_db ( string $dbname )

Procedural style:

bool mysqli_select_db ( mysqli $link , string $dbname )

Selects the default database to be used when performing queries against the database connection.

Note: This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

dbname

The database name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

/* change db to world db */
$mysqli->select_db("world");

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

/* change db to world db */
mysqli_select_db($link, "world");

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

mysqli_close($link);
?>

The above example will output:

Default database is test.
Default database is world.

See Also

  • mysqli_connect() - Open a new connection to the MySQL server
  • mysqli_real_connect() - Opens a connection to a mysql server

mysqli::rollback
mysqli::set_charset
MySQLi


Sets the default client character set

mysqli::select_db
mysqli::set_local_infile_default
MySQLi
PHP Manual

mysqli::set_charset

mysqli_set_charset

(PHP 5 >= 5.0.5)

mysqli::set_charset -- mysqli_set_charset — Sets the default client character set

Description

Object oriented style (method):

bool mysqli::set_charset ( string $charset )

Procedural style:

bool mysqli_set_charset ( mysqli $link , string $charset )

Sets the default character set to be used when sending data from and to the database server.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

charset

The charset to be set as default.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: To use this function on a Windows platform you need MySQL client library version 4.1.11 or above (for MySQL 5.0 you need 5.0.6 or above).

Note: This is the preferred way to change the charset. Using mysqli::query() to execute SET NAMES .. is not recommended.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
    printf("Current character set: %s\n", $mysqli->character_set_name());
}

$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!mysqli_set_charset($link, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($link));
} else {
    printf("Current character set: %s\n", mysqli_character_set_name($link));
}

mysqli_close($link);
?>

The above example will output:

Current character set: utf8

See Also

  • mysqli_character_set_name() - Returns the default character set for the database connection
  • mysqli_real_escape_string() - Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
  • » List of character sets that MySQL supports

mysqli::select_db
mysqli::set_local_infile_default
MySQLi


Unsets user defined handler for load local infile command

mysqli::set_charset
mysqli::set_local_infile_handler
MySQLi
PHP Manual

mysqli::set_local_infile_default

mysqli_set_local_infile_default

(PHP 5)

mysqli::set_local_infile_default -- mysqli_set_local_infile_default — Unsets user defined handler for load local infile command

Description

void mysqli_set_local_infile_default ( mysqli $link )

Deactivates a LOAD DATA INFILE LOCAL handler previously set with mysqli_set_local_infile_handler().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

No value is returned.

Examples

See mysqli_set_local_infile_handler() examples

See Also

  • mysqli_set_local_infile_handler() - Set callback function for LOAD DATA LOCAL INFILE command

mysqli::set_charset
mysqli::set_local_infile_handler
MySQLi


Set callback function for LOAD DATA LOCAL INFILE command

mysqli::set_local_infile_default
mysqli->sqlstate
MySQLi
PHP Manual

mysqli::set_local_infile_handler

mysqli_set_local_infile_handler

(PHP 5)

mysqli::set_local_infile_handler -- mysqli_set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command

Description

bool mysqli_set_local_infile_handler ( mysqli $link , callback $read_func )

Object oriented style (method)

mysqli
bool set_local_infile_handler ( mysqli $link , callback $read_func )

Set callback function for LOAD DATA LOCAL INFILE command

The callbacks task is to read input from the file specified in the LOAD DATA LOCAL INFILE and to reformat it into the format understood by LOAD DATA INFILE.

The returned data needs to match the format specified in the LOAD DATA

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

read_func

A callback function or object method taking the following parameters:

stream

A PHP stream associated with the SQL commands INFILE

&buffer

A string buffer to store the rewritten input into

buflen

The maximum number of characters to be stored in the buffer

&errormsg

If an error occurs you can store an error message in here

The callback function should return the number of characters stored in the buffer or a negative value if an error occurred.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");

  function callme($stream, &$buffer, $buflen, &$errmsg)
  {
    $buffer = fgets($stream);

    echo $buffer;

    // convert to upper case and replace "," delimiter with [TAB]
    $buffer = strtoupper(str_replace(",", "\t", $buffer));

    return strlen($buffer);
  }

  echo "Input:\n";

  $db->set_local_infile_handler("callme");
  $db->query("LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
  $db->set_local_infile_default();

  $res = $db->query("SELECT * FROM t1");

  echo "\nResult:\n";
  while ($row = $res->fetch_assoc()) {
    echo join(",", $row)."\n";
  }
?>

Example #2 Procedural style

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");

  function callme($stream, &$buffer, $buflen, &$errmsg)
  {
    $buffer = fgets($stream);

    echo $buffer;

    // convert to upper case and replace "," delimiter with [TAB]
    $buffer = strtoupper(str_replace(",", "\t", $buffer));

    return strlen($buffer);
  }

  echo "Input:\n";

  mysqli_set_local_infile_handler($db, "callme");
  mysqli_query($db, "LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
  mysqli_set_local_infile_default($db);

  $res = mysqli_query($db, "SELECT * FROM t1");

  echo "\nResult:\n";
  while ($row = mysqli_fetch_assoc($res)) {
    echo join(",", $row)."\n";
  }
?>

The above example will output:

Input:
23,foo
42,bar

Output:
23,FOO
42,BAR

See Also

  • mysqli_set_local_infile_default() - Unsets user defined handler for load local infile command

mysqli::set_local_infile_default
mysqli->sqlstate
MySQLi


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Overview
Requirements
Mysqli


Returns the SQLSTATE error from previous MySQL operation

mysqli::set_local_infile_handler
mysqli::ssl_set
MySQLi
PHP Manual

mysqli->sqlstate

mysqli_sqlstate

(PHP 5)

mysqli->sqlstate -- mysqli_sqlstate — Returns the SQLSTATE error from previous MySQL operation

Description

Object oriented style (property):

mysqli
string $sqlstate;

Procedural style:

string mysqli_sqlstate ( mysqli $link )

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see » http://dev.mysql.com/doc/mysql/en/error-handling.html.

Note: Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Table City already exists, so we should get an error */
if (!$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}

$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Table City already exists, so we should get an error */
if (!mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));
}

mysqli_close($link);
?>

The above example will output:

Error - SQLSTATE 42S01.

See Also

  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error

mysqli::set_local_infile_handler
mysqli::ssl_set
MySQLi


Used for establishing secure connections using SSL

mysqli->sqlstate
mysqli::stat
MySQLi
PHP Manual

mysqli::ssl_set

mysqli_ssl_set

(PHP 5)

mysqli::ssl_set -- mysqli_ssl_set — Used for establishing secure connections using SSL

Description

Object oriented style (method):

bool mysqli::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )

Procedural style:

bool mysqli_ssl_set ( mysqli $link , string $key , string $cert , string $ca , string $capath , string $cipher )

Used for establishing secure connections using SSL. It must be called before mysqli_real_connect(). This function does nothing unless OpenSSL support is enabled.

Note that MySQL Native Driver does not support SSL, so calling this function when using MySQL Native Driver will result in an error. MySQL Native Driver is enabled by default on Microsoft Windows from PHP version 5.3 onwards.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

key

The path name to the key file.

cert

The path name to the certificate file.

ca

The path name to the certificate authority file.

capath

The pathname to a directory that contains trusted SSL CA certificates in PEM format.

cipher

A list of allowable ciphers to use for SSL encryption.

Any unused SSL parameters may be given as NULL

Return Values

This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.

See Also

  • mysqli_options() - Set options
  • mysqli_real_connect() - Opens a connection to a mysql server

mysqli->sqlstate
mysqli::stat
MySQLi


Gets the current system status

mysqli::ssl_set
mysqli::stmt_init
MySQLi
PHP Manual

mysqli::stat

mysqli_stat

(PHP 5)

mysqli::stat -- mysqli_stat — Gets the current system status

Description

Object oriented style (method):

string mysqli::stat ( void )

Procedural style:

string mysqli_stat ( mysqli $link )

mysqli_stat() returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

A string describing the server status. FALSE if an error occurred.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf ("System status: %s\n", $mysqli->stat());

$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("System status: %s\n", mysqli_stat($link));

mysqli_close($link);
?>

The above example will output:

System status: Uptime: 272  Threads: 1  Questions: 5340  Slow queries: 0
Opens: 13  Flush tables: 1  Open tables: 0  Queries per second avg: 19.632
Memory in use: 8496K  Max memory used: 8560K

See Also

  • mysqli_get_server_info() - Returns the version of the MySQL server

mysqli::ssl_set
mysqli::stmt_init
MySQLi


Initializes a statement and returns an object for use with mysqli_stmt_prepare

mysqli::stat
mysqli::store_result
MySQLi
PHP Manual

mysqli::stmt_init

mysqli_stmt_init

(PHP 5)

mysqli::stmt_init -- mysqli_stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare

Description

Object oriented style (property):

mysqli
mysqli_stmt stmt_init ( void )

Procedural style :

mysqli_stmt mysqli_stmt_init ( mysqli $link )

Allocates and initializes a statement object suitable for mysqli_stmt_prepare().

Note: Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare() was called.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns an object.

See Also

  • mysqli_stmt_prepare() - Prepare a SQL statement for execution

mysqli::stat
mysqli::store_result
MySQLi


Transfers a result set from the last query

mysqli::stmt_init
mysqli::thread_id
MySQLi
PHP Manual

mysqli::store_result

mysqli_store_result

(PHP 5)

mysqli::store_result -- mysqli_store_result — Transfers a result set from the last query

Description

Object oriented style (method):

mysqli_result mysqli::store_result ( void )

Procedural style:

mysqli_result mysqli_store_result ( mysqli $link )

Transfers the result set from the last query on the database connection represented by the link parameter to be used with the mysqli_data_seek() function.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns a buffered result object or FALSE if an error occurred.

Note: mysqli_store_result() returns FALSE in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns FALSE if the reading of the result set failed. You can check if you have got an error by checking if mysqli_error() doesn't return an empty string, if mysqli_errno() returns a non zero value, or if mysqli_field_count() returns a non zero value. Also possible reason for this function returning FALSE after successful call to mysqli_query() can be too large result set (memory for it cannot be allocated). If mysqli_field_count() returns a non-zero value, the statement should have produced a non-empty result set.

Notes

Note: Although it is always good practice to free the memory used by the result of a query using the mysqli_free_result() function, when transferring large result sets using the mysqli_store_result() this becomes particularly important.

Examples

See mysqli_multi_query().

See Also

  • mysqli_real_query() - Execute an SQL query
  • mysqli_use_result() - Initiate a result set retrieval

mysqli::stmt_init
mysqli::thread_id
MySQLi


The MySQLi Extension Function Summary

MySQLi Class
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
$mysqli->affected_rows | mysqli_affected_rows() | N/A | Gets the number of affected rows in a previous MySQL operation
$mysqli->client_info | mysqli_get_client_info() | N/A | Returns the MySQL client version as a string
$mysqli->client_version | mysqli_get_client_version() | N/A | Returns MySQL client version info as an integer
$mysqli->connect_errno | mysqli_connect_errno() | N/A | Returns the error code from last connect call
$mysqli->connect_error | mysqli_connect_error() | N/A | Returns a string description of the last connect error
$mysqli->errno | mysqli_errno() | N/A | Returns the error code for the most recent function call
$mysqli->error | mysqli_error() | N/A | Returns a string description of the last error
$mysqli->field_count | mysqli_field_count() | N/A | Returns the number of columns for the most recent query
$mysqli->host_info | mysqli_get_host_info() | N/A | Returns a string representing the type of connection used
$mysqli->protocol_version | mysqli_get_proto_info() | N/A | Returns the version of the MySQL protocol used
$mysqli->server_info | mysqli_get_server_info() | N/A | Returns the version of the MySQL server
$mysqli->server_version | mysqli_get_server_version() | N/A | Returns the version of the MySQL server as an integer
$mysqli->info | mysqli_info() | N/A | Retrieves information about the most recently executed query
$mysqli->insert_id | mysqli_insert_id() | N/A | Returns the auto generated id used in the last query
$mysqli->sqlstate | mysqli_sqlstate() | N/A | Returns the SQLSTATE error from previous MySQL operation
$mysqli->warning_count | mysqli_warning_count() | N/A | Returns the number of warnings from the last query for the given link
Methods
mysqli->autocommit | mysqli_autocommit() | N/A | Turns on or off auto-commiting database modifications
mysqli->change_user | mysqli_change_user() | N/A | Changes the user of the specified database connection
mysqli->character_set_name, mysqli->client_encoding | mysqli_character_set_name() | mysqli_client_encoding() | Returns the default character set for the database connection
mysqli->close | mysqli_close() | N/A | Closes a previously opened database connection
mysqli->commit | mysqli_commit() | N/A | Commits the current transaction
mysqli::__construct | mysqli_connect() | N/A | Open a new connection to the MySQL server [Note: static (i.e. class) method]
mysqli->debug | mysqli_debug() | N/A | Performs debugging operations
mysqli->dump_debug_info | mysqli_dump_debug_info() | N/A | Dump debugging information into the log
mysqli->get_charset | mysqli_get_charset() | N/A | Returns a character set object
mysqli->get_connection_stats | mysqli_get_connection_stats() | N/A | Returns client connection statistics. Available only with mysqlnd.
mysqli->get_client_info | mysqli_get_client_info() | N/A | Returns the MySQL client version as a string
mysqli->get_client_stats | mysqli_get_client_stats() | N/A | Returns client per-process statistics. Available only with mysqlnd.
mysqli->get_cache_stats | mysqli_get_cache_stats() | N/A | Returns client Zval cache statistics. Available only with mysqlnd.
mysqli->get_server_info | mysqli_get_server_info() | N/A | NOT DOCUMENTED
mysqli->get_warnings | mysqli_get_warnings() | N/A | NOT DOCUMENTED
mysqli_init | mysqli_init() | N/A | Initializes MySQLi and returns a resource for use with mysqli_real_connect. [Not called on an object, as it returns a $mysqli object.]
mysqli->kill | mysqli_kill() | N/A | Asks the server to kill a MySQL thread
mysqli->more_results | mysqli_more_results() | N/A | Check if there are any more query results from a multi query
mysqli->multi_query | mysqli_multi_query() | N/A | Performs a query on the database
mysqli->next_result | mysqli_next_result() | N/A | Prepare next result from multi_query
mysqli->options | mysqli_options() | mysqli_set_opt() | Set options
mysqli->ping | mysqli_ping() | N/A | Pings a server connection, or tries to reconnect if the connection has gone down
mysqli->prepare | mysqli_prepare() | N/A | Prepare a SQL statement for execution
mysqli->query | mysqli_query() | N/A | Performs a query on the database
mysqli->real_connect | mysqli_real_connect() | N/A | Opens a connection to a mysql server
mysqli->real_escape_string, mysqli->escape_string | mysqli_real_escape_string() | mysqli_escape_string() | Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
mysqli->real_query | mysqli_real_query() | N/A | Execute an SQL query
mysqli->rollback | mysqli_rollback() | N/A | Rolls back current transaction
mysqli->select_db | mysqli_select_db() | N/A | Selects the default database for database queries
mysqli->set_charset | mysqli_set_charset() | N/A | Sets the default client character set
mysqli->set_local_infile_default | mysqli_set_local_infile_default() | N/A | Unsets user defined handler for load local infile command
mysqli->set_local_infile_handler | mysqli_set_local_infile_handler() | N/A | Set callback function for LOAD DATA LOCAL INFILE command
mysqli->ssl_set | mysqli_ssl_set() | N/A | Used for establishing secure connections using SSL
mysqli->stat | mysqli_stat() | N/A | Gets the current system status
mysqli->stmt_init | mysqli_stmt_init() | N/A | Initializes a statement and returns an object for use with mysqli_stmt_prepare
mysqli->store_result | mysqli_store_result() | N/A | Transfers a result set from the last query
mysqli->thread_id | mysqli_thread_id() | N/A | Returns the thread ID for the current connection
mysqli->thread_safe | mysqli_thread_safe() | N/A | Returns whether thread safety is given or not
mysqli->use_result | mysqli_use_result() | N/A | Initiate a result set retrieval
MySQL_STMT
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
$mysqli_stmt->affected_rows | mysqli_stmt_affected_rows() | N/A | Returns the total number of rows changed, deleted, or inserted by the last executed statement
$mysqli_stmt->errno | mysqli_stmt_errno() | N/A | Returns the error code for the most recent statement call
$mysqli_stmt->error | mysqli_stmt_error() | N/A | Returns a string description for last statement error
$mysqli_stmt->field_count | mysqli_stmt_field_count() | N/A | Returns the number of field in the given statement - not documented
$mysqli_stmt->insert_id | mysqli_stmt_insert_id() | N/A | Get the ID generated from the previous INSERT operation
$mysqli_stmt->num_rows | mysqli_stmt_num_rows() | N/A | Return the number of rows in statements result set
$mysqli_stmt->param_count | mysqli_stmt_param_count() | mysqli_param_count() | Returns the number of parameter for the given statement
$mysqli_stmt->sqlstate | mysqli_stmt_sqlstate() | N/A | Returns SQLSTATE error from previous statement operation
Methods
mysqli_stmt->attr_get | mysqli_stmt_attr_get() | N/A | Used to get the current value of a statement attribute
mysqli_stmt->attr_set | mysqli_stmt_attr_set() | N/A | Used to modify the behavior of a prepared statement
mysqli_stmt->bind_param | mysqli_stmt_bind_param() | mysqli_bind_param() | Binds variables to a prepared statement as parameters
mysqli_stmt->bind_result | mysqli_stmt_bind_result() | mysqli_bind_result() | Binds variables to a prepared statement for result storage
mysqli_stmt->close | mysqli_stmt_close() | N/A | Closes a prepared statement
mysqli_stmt->data_seek | mysqli_stmt_data_seek() | N/A | Seeks to an arbitrary row in statement result set
mysqli_stmt->execute | mysqli_stmt_execute() | mysqli_execute() | Executes a prepared Query
mysqli_stmt->fetch | mysqli_stmt_fetch() | mysqli_fetch() | Fetch results from a prepared statement into the bound variables
mysqli_stmt->free_result | mysqli_stmt_free_result() | N/A | Frees stored result memory for the given statement handle
$mysqli_stmt->get_result() | mysqli_stmt_get_result | N/A | NOT DOCUMENTED Available only with mysqlnd.
mysqli_stmt->get_warnings | mysqli_stmt_get_warnings() | N/A | NOT DOCUMENTED
$mysqli_stmt->more_results() | mysqli_stmt_more_results() | N/A | NOT DOCUMENTED Available only with mysqlnd.
$mysqli_stmt->next_result() | mysqli_stmt_next_result() | N/A | NOT DOCUMENTED Available only with mysqlnd.
mysqli_stmt->num_rows | mysqli_stmt_num_rows() | N/A | See also property $mysqli_stmt->num_rows
mysqli_stmt->prepare | mysqli_stmt_prepare() | N/A | Prepare a SQL statement for execution
mysqli_stmt->reset | mysqli_stmt_reset() | N/A | Resets a prepared statement
mysqli_stmt->result_metadata | mysqli_stmt_result_metadata() | mysqli_get_metadata() | Returns result set metadata from a prepared statement
mysqli_stmt->send_long_data | mysqli_stmt_send_long_data() | mysqli_send_long_data() | Send data in blocks
mysqli_stmt->store_result | mysqli_stmt_store_result() | N/A | Transfers a result set from a prepared statement
MySQLi_RESULT
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
$mysqli_result->current_field | mysqli_field_tell() | N/A | Get current field offset of a result pointer
$mysqli_result->field_count | mysqli_num_fields() | N/A | Get the number of fields in a result
$mysqli_result->lengths | mysqli_fetch_lengths() | N/A | Returns the lengths of the columns of the current row in the result set
$mysqli_result->num_rows | mysqli_num_rows() | N/A | Gets the number of rows in a result
Methods
mysqli_result->data_seek | mysqli_data_seek() | N/A | Adjusts the result pointer to an arbitary row in the result
mysqli_result->fetch_all | mysqli_fetch_all() | N/A | Fetches all result rows and returns the result set as an associative array, a numeric array, or both. Available only with mysqlnd.
mysqli_result->fetch_array | mysqli_fetch_array() | N/A | Fetch a result row as an associative, a numeric array, or both
mysqli_result->fetch_assoc | mysqli_fetch_assoc() | N/A | Fetch a result row as an associative array
mysqli_result->fetch_field_direct | mysqli_fetch_field_direct() | N/A | Fetch meta-data for a single field
mysqli_result->fetch_field | mysqli_fetch_field() | N/A | Returns the next field in the result set
mysqli_result->fetch_fields | mysqli_fetch_fields() | N/A | Returns an array of objects representing the fields in a result set
mysqli_result->fetch_object | mysqli_fetch_object() | N/A | Returns the current row of a result set as an object
mysqli_result->fetch_row | mysqli_fetch_row() | N/A | Get a result row as an enumerated array
mysqli_result->field_seek | mysqli_field_seek() | N/A | Set result pointer to a specified field offset
mysqli_result->free, mysqli_result->close, mysqli_result->free_result | mysqli_free_result() | N/A | Frees the memory associated with a result
MySQL_Driver
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
N/A
Methods
mysqli_driver->embedded_server_end | mysqli_embedded_server_end() | N/A | NOT DOCUMENTED
mysqli_driver->embedded_server_start | mysqli_embedded_server_start() | N/A | NOT DOCUMENTED

Note: Alias functions are provided for backward compatibility purposes only. Do not use them in new projects.

Predefined Constants
MySQLi
Mysqli


Returns the thread ID for the current connection

mysqli::store_result
mysqli::thread_safe
MySQLi
PHP Manual

mysqli::thread_id

mysqli_thread_id

(PHP 5)

mysqli::thread_id -- mysqli_thread_id — Returns the thread ID for the current connection

Description

Object oriented style (property):

mysqli
int $thread_id;

Procedural style:

int mysqli_thread_id ( mysqli $link )

The mysqli_thread_id() function returns the thread ID for the current connection which can then be killed using the mysqli_kill() function. If the connection is lost and you reconnect with mysqli_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.

Note: The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.
To kill a running query you can use the SQL command KILL QUERY processid.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns the Thread ID for the current connection.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = $mysqli->thread_id;

/* Kill connection */
$mysqli->kill($thread_id);

/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli->error);
    exit;
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = mysqli_thread_id($link);

/* Kill connection */
mysqli_kill($link, $thread_id);

/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", mysqli_error($link));
    exit;
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Error: MySQL server has gone away

See Also

  • mysqli_kill() - Asks the server to kill a MySQL thread

mysqli::store_result
mysqli::thread_safe
MySQLi


Returns whether thread safety is given or not

mysqli::thread_id
mysqli::use_result
MySQLi
PHP Manual

mysqli::thread_safe

mysqli_thread_safe

(PHP 5)

mysqli::thread_safe -- mysqli_thread_safe — Returns whether thread safety is given or not

Description

Procedural style:

bool mysqli_thread_safe ( void )

Tells whether the client library is compiled as thread-safe.

Return Values

TRUE if the client library is thread-safe, otherwise FALSE.

mysqli::thread_id
mysqli::use_result
MySQLi


Initiate a result set retrieval

mysqli::thread_safe
mysqli::warning_count
MySQLi
PHP Manual

mysqli::use_result

mysqli_use_result

(PHP 5)

mysqli::use_result -- mysqli_use_result — Initiate a result set retrieval

Description

Object oriented style (method):

mysqli_result mysqli::use_result ( void )

Procedural style:

mysqli_result mysqli_use_result ( mysqli $link )

Used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query() function on the database connection.

Either this or the mysqli_store_result() function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.

Note: The mysqli_use_result() function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek() to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result(). One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.

Return Values

Returns an unbuffered result object or FALSE if an error occurred.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->use_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->close();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_use_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

See Also

  • mysqli_real_query() - Execute an SQL query
  • mysqli_store_result() - Transfers a result set from the last query

mysqli::thread_safe
mysqli::warning_count
MySQLi


Returns the number of warnings from the last query for the given link

mysqli::use_result
MySQLi_STMT
MySQLi
PHP Manual

mysqli::warning_count

mysqli_warning_count

(PHP 5)

mysqli::warning_count -- mysqli_warning_count — Returns the number of warnings from the last query for the given link

Description

Object oriented style (property):

mysqli
int $warning_count;

Procedural style:

int mysqli_warning_count ( mysqli $link )

Returns the number of warnings from the last query in the connection.

Note: For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Number of warnings or zero if there are no warnings.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* a remarkable city in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$mysqli->query($query);

if ($mysqli->warning_count) {
    if ($result = $mysqli->query("SHOW WARNINGS")) {
        $row = $result->fetch_row();
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        $result->close();
    }
}

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* a remarkable long city name in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

mysqli_query($link, $query);

if (mysqli_warning_count($link)) {
    if ($result = mysqli_query($link, "SHOW WARNINGS")) {
        $row = mysqli_fetch_row($result);
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        mysqli_free_result($result);
    }
}

/* close connection */
mysqli_close($link);
?>

The above example will output:

Warning (1264): Data truncated for column 'Name' at row 1

See Also

  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

mysqli::use_result
MySQLi_STMT
MySQLi


Configuration

Configuration File (php.ini) Settings

In PHP 5.3 the following php.ini settings are available for the MySQL Native Driver:

mysqlnd.collect_statistics

type:boolean, default:"1", changeable:PHP_INI_SYSTEM

Available since 5.3.0

Enables the collection of various client statistics which can be
accessed through mysqli_get_client_stats(),
mysqli_get_connection_stats(),
mysqli_get_cache_stats() and are shown in
mysqlnd section of the output of the
phpinfo() function as well.

When enabled the following statistics will be collected:

bytes_sent, bytes_received, packets_sent, packets_received, protocol_overhead_in, protocol_overhead_out, bytes_received_ok_packet, bytes_received_eof_packet, bytes_received_rset_header_packet, bytes_received_rset_field_meta_packet, bytes_received_rset_row_packet, bytes_received_prepare_response_packet, bytes_received_change_user_packet, packets_sent_command, packets_received_ok, packets_received_eof, packets_received_rset_header, packets_received_rset_field_meta, packets_received_rset_row, packets_received_prepare_response, packets_received_change_user, result_set_queries, non_result_set_queries, no_index_used, bad_index_used, slow_queries, buffered_sets, unbuffered_sets, ps_buffered_sets, ps_unbuffered_sets, flushed_normal_sets, flushed_ps_sets, ps_prepared_never_executed, ps_prepared_once_executed, rows_fetched_from_server_normal, rows_fetched_from_server_ps, rows_buffered_from_client_normal, rows_buffered_from_client_ps, rows_fetched_from_client_normal_buffered, rows_fetched_from_client_normal_unbuffered, rows_fetched_from_client_ps_buffered, rows_fetched_from_client_ps_unbuffered, rows_fetched_from_client_ps_cursor, rows_skipped_normal, rows_skipped_ps, copy_on_write_saved, copy_on_write_performed, command_buffer_too_small, connect_success, connect_failure

mysqlnd.collect_memory_statistics

type:boolean, default:"0", changeable:PHP_INI_SYSTEM

Available since 5.3.0

Enable the collection of various memory statistics which can be
accessed through mysqli_get_client_stats(),
mysqli_get_connection_stats(),
mysqli_get_cache_stats() and are shown in
mysqlnd section of the output of the
phpinfo() function as well.

When enabled the following statistics will be collected:

TBD

Installation
Persistent Connections
Mysqlnd


Installation

Installation on Unix

By default the MySQL database extensions are configured to use MySQL Client Library. In order to use the MySQL Native Driver, PHP needs to be built specifying that the MySQL database extensions are compiled with MySQL Native Driver support. This is done through configuration options prior to building the PHP source code.

For example, to build the MySQL extension, mysqli and PDO MYSQL using the MySQL Native Driver, the following command would be given:

./configure --with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
[other options]

Installation on Windows

In the official PHP distributions from 5.3 onwards, MySQL Native Driver is enabled by default, so no additional configuration is required to use it. All MySQL database extensions will use MySQL Native Driver in this case.

Overview
Configuration
Mysqlnd


Notes

This section provides a collection of miscellaneous notes on MySQL Native Driver usage.

  • In the case where you pass a statement to mysqli_query() that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysql). The behavior is as follows:

    • mysqlnd on Linux returns an error code of 1153. The error message means "got a packet bigger than max_allowed_packet bytes".

    • mysqlnd on Windows returns an error code 2006. This error message means "server has gone away".

    • libmysql on all platforms returns an error code 2006. This error message means "server has gone away".

    The same thing happens with mysqli_stmt_prepare().

Statistics
OCI8
Mysqlnd


Overview

MySQL Native Driver is a replacement for the MySQL Client Library (libmysql). MySQL Native Driver is part of the official PHP 5.3 and PHP 6 branches.

The MySQL database extensions MySQL extension, mysqli and PDO MYSQL all communicate with the MySQL server. In the past, this was done by the extension using the services provided by the MySQL Client Library. The extensions were compiled against the MySQL Client Library in order to use its client-server protocol.

With MySQL Native Driver there is now an alternative, as the MySQL database extensions can be compiled to use MySQL Native Driver instead of the MySQL Client Library.

MySQL Native Driver is written in C as a PHP extension.

What it is not

Although MySQL Native Driver is written as a PHP extension, it is important to note that it does not provide a new API to the PHP programmer. The programmer APIs for MySQL database connectivity are provided by the MySQL extension, mysqli and PDO MYSQL. These extensions can now use the services of MySQL Native Driver to communicate with the MySQL Server. Therefore, you should not think of MySQL Native Driver as an API.

Why use it?

Using the MySQL Native Driver offers a number of advantages over using the MySQL Client Library.

The older MySQL Client Library was written by MySQL AB (now Sun Microsystems, Inc.) and so was released under the MySQL license. This ultimately led to MySQL support being disabled by default in PHP. However, the MySQL Native Driver has been developed as part of the PHP project, and is therefore released under the PHP license. This removes licensing issues that have been problematic in the past.

Also, in the past, you needed to build the MySQL database extensions against a copy of the MySQL Client Library. This typically meant you needed to have MySQL installed on a machine where you were building the PHP source code. Also, when your PHP application was running, the MySQL database extensions would call down to the MySQL Client library file at run time, so the file needed to be installed on your system. With MySQL Native Driver that is no longer the case as it is included as part of the standard distribution. So you do not need MySQL installed in order to build PHP or run PHP database applications.

Because MySQL Native Driver is written as a PHP extension, it is tightly coupled to the workings of PHP. This leads to gains in efficiency, especially when it comes to memory usage, as the driver uses the PHP memory management system. It also supports the PHP memory limit. Using MySQL Native Driver leads to comparable or better performance than using MySQL Client Library, it always ensures the most efficient use of memory. One example of the memory efficiency is the fact that when using the MySQL Client Library, each row is stored in memory twice, whereas with the MySQL Native Driver each row is only stored once in memory.

Special features

MySQL Native Driver also provides some special features not available when the MySQL database extensions use MySQL Client Library. These special features are listed below:

  • Improved persistent connections

  • The special function mysqli_fetch_all()

  • Performance statistics calls:
mysqli_get_cache_stats(),
mysqli_get_client_stats(),
mysqli_get_connection_stats()

The performance statistics facility can prove to be very useful in identifying performance bottlenecks.

MySQL Native Driver also allows for persistent connections when used with the mysqli extension.

SSL Support

Currently, MySQL Native Driver does not support SSL. This means that mysqli_ssl_set() will generate an error if called while using MySQL Native Driver.

Compressed Protocol Support

As of PHP 5.3.2 MySQL Native Driver supports the compressed client server protocol. MySQL Native Driver did not support this in 5.3.0 and 5.3.1. Extensions such as ext/mysql, ext/mysqli, PDO_MYSQL, that are configured to use MySQL Native Driver, can also take advantage of this feature.

Introduction
Installation
Mysqlnd


Persistent Connections

Using Persistent Connections

The MySQL database extensions do not support persistent connections when used with the MySQL Client Library. However, they do when using MySQL Native Driver. When creating a connection the hostname is prepended with "p:". This is demonstrated by the following code snippet, which creates a new connection using mysqli:

$host="p:localhost";
$port=3306;
$socket="/tmp/mysql.sock";
$user="root";
$password="password";
$dbname="test";

$conn = new mysqli($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());
Configuration
Statistics
Mysqlnd


Statistics

Using Statistical Data

MySQL Native Driver contains support for gathering statistics on the communication between the client and the server. The statistics gathered are of three main types:

  • Client statistics

  • Connection statistics

  • Zval cache statistics

If you are using the mysqli extension, these statistics can be obtained through three API calls:

  • mysqli_get_client_stats()

  • mysqli_get_connection_stats()

  • mysqli_get_cache_stats()

Note: Statistics are aggregated among all extensions that use MySQL Native Driver. For example, when compiling both ext/mysql and ext/mysqli against MySQL Native Driver, both function calls of ext/mysql and ext/mysqli will change the statistics. There is no way to find out how much a certain API call of any extension that has been compiled against MySQL Native Driver has impacted a certain statistic. You can configure the PDO MySQL Driver, ext/mysql and ext/mysqli to optionally use the MySQL Native Driver. When doing so, all three extensions will change the statistics.

Accessing Client Statistics

To access client statistics, you need to call mysqli_get_client_stats(). The function call does not require any parameters.

The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.

Client statistics can also be accessed by calling the phpinfo() function.

Accessing Connection Statistics

To access connection statistics call mysqli_get_connection_stats(). This takes the database connection handle as the parameter.

The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.

Accessing Zval Cache Statistics

The MySQL Native Driver also collects statistics from its internal Zval cache. These statistics can be accessed by calling mysqli_get_cache_stats().

The Zval cache statistics obtained may lead to a tweaking of php.ini settings related to the Zval cache, resulting in better performance.

Buffered and Unbuffered Result Sets

Result sets can be buffered or unbuffered. Using default settings, ext/mysql and ext/mysqli work with buffered result sets for normal (non prepared statement) queries. Buffered result sets are cached on the client. After the query execution all results are fetched from the MySQL Server and stored in a cache on the client. The big advantage of buffered result sets is that they allow the server to free all resources allocated to a result set, once the results have been fetched by the client.

Unbuffered result sets on the other hand are kept much longer on the server. If you want to reduce memory consumption on the client, but increase load on the server, use unbuffered results. If you experience a high server load and the figures for unbuffered result sets are high, you should consider moving the load to the clients. Clients typically scale better than servers. "Load" does not only refer to memory buffers - the server also needs to keep other resources open, for example file handles and threads, before a result set can be freed.

Prepared Statements use unbuffered result sets by default. However, you can use mysqli_stmt_store_result() to enable buffered result sets.

Statistics returned by MySQL Native Driver

The following tables show a list of statistics returned by the
mysqli_get_client_stats(),
mysqli_get_connection_stats() and
mysqli_get_cache_stats() functions.

Network

Statistic | Scope | Description | Notes
bytes_sent | Connection | Number of bytes sent from PHP to the MySQL server | Can be used to check the efficiency of the compression protocol
bytes_received | Connection | Number of bytes received from MySQL server | Can be used to check the efficiency of the compression protocol
packets_sent | Connection | Number of MySQL Client Server protocol packets sent | Used for debugging Client Server protocol implementation
packets_received | Connection | Number of MySQL Client Server protocol packets received | Used for debugging Client Server protocol implementation
protocol_overhead_in | Connection | MySQL Client Server protocol overhead in bytes for incoming traffic. Currently only the Packet Header (4 bytes) is considered as overhead. protocol_overhead_in = packets_received * 4 | Used for debugging Client Server protocol implementation
protocol_overhead_out | Connection | MySQL Client Server protocol overhead in bytes for outgoing traffic. Currently only the Packet Header (4 bytes) is considered as overhead. protocol_overhead_out = packets_sent * 4 | Used for debugging Client Server protocol implementation
bytes_received_ok_packet | Connection | Total size of bytes of MySQL Client Server protocol OK packets received. OK packets can contain a status message. The length of the status message can vary and thus the size of an OK packet is not fixed. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_ok | Connection | Number of MySQL Client Server protocol OK packets received. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_eof_packet | Connection | Total size in bytes of MySQL Client Server protocol EOF packets received. EOF can vary in size depending on the server version. Also, EOF can transport an error message. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_eof | Connection | Number of MySQL Client Server protocol EOF packets. Like with other packet statistics the number of packets will be increased even if PHP does not receive the expected packet but, for example, an error message. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_header_packet | Connection | Total size in bytes of MySQL Client Server protocol result set header packets. The size of the packets varies depending on the payload (LOAD LOCAL INFILE, INSERT, UPDATE, SELECT, error message). | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_header | Connection | Number of MySQL Client Server protocol result set header packets. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_field_meta_packet | Connection | Total size in bytes of MySQL Client Server protocol result set meta data (field information) packets. Of course the size varies with the fields in the result set. The packet may also transport an error or an EOF packet in case of COM_LIST_FIELDS. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_field_meta | Connection | Number of MySQL Client Server protocol result set meta data (field information) packets. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_row_packet | Connection | Total size in bytes of MySQL Client Server protocol result set row data packets. The packet may also transport an error or an EOF packet. You can reverse engineer the number of error and EOF packets by substracting rows_fetched_from_server_normal and rows_fetched_from_server_ps from bytes_received_rset_row_packet. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_row | Connection | Number of MySQL Client Server protocol result set row data packets and their total size in bytes. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_prepare_response_packet | Connection | Total size in bytes of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). The packet may also transport an error. The packet size depends on the MySQL version: 9 bytes with MySQL 4.1 and 12 bytes from MySQL 5.0 on. There is no safe way to know how many errors happened. You may be able to guess that an error has occured if, for example, you always connect to MySQL 5.0 or newer and, bytes_received_prepare_response_packet != packets_received_prepare_response * 12. See also ps_prepared_never_executed, ps_prepared_once_executed. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_prepare_response | Connection | Number of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_change_user_packet | Connection | Total size in bytes of MySQL Client Server protocol COM_CHANGE_USER packets. The packet may also transport an error or EOF. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_change_user | Connection | Number of MySQL Client Server protocol COM_CHANGE_USER packets | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_sent_command | Connection | Number of MySQL Client Server protocol commands sent from PHP to MySQL. There is no way to know which specific commands and how many of them have been sent. At its best you can use it to check if PHP has sent any commands to MySQL to know if you can consider to disable MySQL support in your PHP binary. There is also no way to reverse engineer the number of errors that may have occured while sending data to MySQL. The only error recoded is command_buffer_too_small (see below). | Only useful for debugging CS protocol implementation.

Result Set

Statistic | Scope | Description | Notes
result_set_queries | Connection | Number of queries that have generated a result set. Examples of queries that generate a result set: SELECT, SHOW. The statistic will not be incremented if there is an error reading the result set header packet from the line. | You may use it an an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
non_result_set_queries | Connection | Number of queries that did not generate a result set. Examples of queries that do not generate a result set: INSERT, UPDATE, LOAD DATA, SHOW. The statistic will not be incremented if there is an error reading the result set header packet from the line. | You may use it an an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
no_index_used | Connection | Number of queries that have generated a result set but did not use an index (see also mysqld start option –log-queries-not-using-indexes). If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT).
bad_index_used | Connection | Number of queries that have generated a result set and did not use a good index (see also mysqld start option –log-slow-queries). | If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT)
slow_queries | Connection | SQL statements that took more than long_query_time seconds to execute and required at least min_examined_row_limit rows to be examined. | Not reported through mysqli_report()
buffered_sets | Connection | Number of buffered result sets returned by "normal" queries. "Normal" means "not prepared statement" in the following notes. | Examples of API calls that will buffer result sets on the client: mysql_query(), mysqli_query(), mysqli_store_result(), mysqli_stmt_get_result(). Buffering result sets on the client ensures that server resources are freed as soon as possible and it makes result set scrolling easier. The downside is the additional memory consumption on the client for buffering data. Note that mysqlnd (unlike the MySQL Client Library) respects the PHP memory limit because it uses PHP internal memory management functions to allocate memory. This is also the reason why memory_get_usage() reports a higer memory consumption when using mysqlnd instead of the MySQL Client Library. memory_get_usage() does not measure the memory consumption of the MySQL Client Library at all because the MySQL Client Library does not use PHP internal memory management functions monitored by the function!
unbuffered_sets | Connection | Number of unbuffered result sets returned by normal (non prepared statement) queries. | Examples of API calls that will not buffer result sets on the client: mysqli_use_result()
ps_buffered_sets | Connection | Number of buffered result sets returned by prepared statements. By default prepared statements are unbuffered. | Examples of API calls that will not buffer result sets on the client: mysqli_stmt_store_result
ps_unbuffered_sets | Connection | Number of unbuffered result sets returned by prepared statements. | By default prepared statements are unbuffered.
flushed_normal_sets Connection Number of result sets from normal (non prepared statement) queries with unread data which have been flushed silently for you. Flushing happens only with unbuffered result sets. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also rows_skipped_normal, rows_skipped_ps. Some possible causes for an implicit flush:

  • Faulty client application

  • Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed

  • Client application has stopped unexpectedly

flushed_ps_sets Connection Number of result sets from prepared statements with unread data which have been flushed silently for you. Flushing happens only with unbuffered result sets. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also rows_skipped_normal, rows_skipped_ps. Some possible causes for an implicit flush:

  • Faulty client application

  • Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed

  • Client application has stopped unexpectedly

ps_prepared_never_executed | Connection | Number of statements prepared but never executed. | Prepared statements occupy server resources. You should not prepare a statement if you do not plan to execute it.
ps_prepared_once_executed | Connection | Number of prepared statements executed only one. | One of the ideas behind prepared statements is that the same query gets executed over and over again (with different parameters) and some parsing and other preparation work can be saved, if statement execution is split up in separate prepare and execute stages. The idea is to prepare once and "cache" results, for example, the parse tree to be reused during multiple statement executions. If you execute a prepared statement only once the two stage processing can be inefficient compared to "normal" queries because all the caching means extra work and it takes (limited) server resources to hold the cached information. Consequently, prepared statements that are executed only once may cause performance hurts.
rows_fetched_from_server_normal, rows_fetched_from_server_ps | Connection | Total number of result set rows successfully fetched from MySQL regardless if the client application has consumed them or not. Some of the rows may not have been fetched by the client application but have been flushed implicitly. | See also packets_received_rset_row
rows_buffered_from_client_normal, rows_buffered_from_client_ps | Connection | Total number of succesfully buffered rows originating from a "normal" query or a prepared statement. This is the number of rows that have been fetched from MySQL and buffered on client. Note that there are two distinct statistics on rows that have been buffered (MySQL to mysqlnd internal buffer) and buffered rows that have been fetched by the client application (mysqlnd internal buffer to client application). If the number of buffered rows is higher than the number of fetched buffered rows it can mean that the client application runs queries that cause larger result sets than needed resulting in rows not read by the client. | Examples of queries that will buffer results: mysqli_query(), mysqli_store_result()
rows_fetched_from_client_normal_buffered, rows_fetched_from_client_ps_buffered | Connection | Total number of rows fetched by the client from a buffered result set created by a normal query or a prepared statement.
rows_fetched_from_client_normal_unbuffered, rows_fetched_from_client_ps_unbuffered | Connection | Total number of rows fetched by the client from a unbuffered result set created by a "normal" query or a prepared statement.
rows_fetched_from_client_ps_cursor | Connection | Total number of rows fetch by the client from a cursor created by a prepared statement.
rows_skipped_normal, rows_skipped_ps | Connection | Reserved for future use (currently not supported)
copy_on_write_saved, copy_on_write_performed | Process | With mysqlnd, variables returned by the extensions point into mysqlnd internal network result buffers. If you do not change the variables, fetched data will be kept only once in memory. If you change the variables, mysqlnd has to perform a copy-on-write to protect the internal network result buffers from being changed. With the MySQL Client Library you always hold fetched data twice in memory. Once in the internal MySQL Client Library buffers and once in the variables returned by the extensions. In theory mysqlnd can save up to 40% memory. However, note that the memory saving cannot be measured using memory_get_usage().
explicit_free_result, implicit_free_result | Connection, Process (only during prepared statement cleanup) | Total number of freed result sets. | The free is always considered explicit but for result sets created by an init command, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...)
proto_text_fetched_null, proto_text_fetched_bit, proto_text_fetched_tinyint proto_text_fetched_short, proto_text_fetched_int24, proto_text_fetched_int proto_text_fetched_bigint, proto_text_fetched_decimal, proto_text_fetched_float proto_text_fetched_double, proto_text_fetched_date, proto_text_fetched_year proto_text_fetched_time, proto_text_fetched_datetime, proto_text_fetched_timestamp proto_text_fetched_string, proto_text_fetched_blob, proto_text_fetched_enum proto_text_fetched_set, proto_text_fetched_geometry, proto_text_fetched_other Connection Total number of columns of a certain type fetched from a normal query (MySQL text protocol). Mapping from C API / MySQL meta data type to statistics name:

  • MYSQL_TYPE_NULL - proto_text_fetched_null

  • MYSQL_TYPE_BIT - proto_text_fetched_bit

  • MYSQL_TYPE_TINY - proto_text_fetched_tinyint

  • MYSQL_TYPE_SHORT - proto_text_fetched_short

  • MYSQL_TYPE_INT24 - proto_text_fetched_int24

  • MYSQL_TYPE_LONG - proto_text_fetched_int

  • MYSQL_TYPE_LONGLONG - proto_text_fetched_bigint

  • MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NEWDECIMAL - proto_text_fetched_decimal

  • MYSQL_TYPE_FLOAT - proto_text_fetched_float

  • MYSQL_TYPE_DOUBLE - proto_text_fetched_double

  • MYSQL_TYPE_DATE, MYSQL_TYPE_NEWDATE - proto_text_fetched_date

  • MYSQL_TYPE_YEAR - proto_text_fetched_year

  • MYSQL_TYPE_TIME - proto_text_fetched_time

  • MYSQL_TYPE_DATETIME - proto_text_fetched_datetime

  • MYSQL_TYPE_TIMESTAMP - proto_text_fetched_timestamp

  • MYSQL_TYPE_STRING, MYSQL_TYPE_VARSTRING, MYSQL_TYPE_VARCHAR - proto_text_fetched_string

  • MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_BLOB - proto_text_fetched_blob

  • MYSQL_TYPE_ENUM - proto_text_fetched_enum

  • MYSQL_TYPE_SET - proto_text_fetched_set

  • MYSQL_TYPE_GEOMETRY - proto_text_fetched_geometry

  • Any MYSQL_TYPE_* not listed before (there should be none) - proto_text_fetched_other

Note that the MYSQL_*-type constants may not be associated with the very same SQL column types in every version of MySQL.

proto_binary_fetched_null, proto_binary_fetched_bit, proto_binary_fetched_tinyint proto_binary_fetched_short, proto_binary_fetched_int24, proto_binary_fetched_int, proto_binary_fetched_bigint, proto_binary_fetched_decimal, proto_binary_fetched_float, proto_binary_fetched_double, proto_binary_fetched_date, proto_binary_fetched_year, proto_binary_fetched_time, proto_binary_fetched_datetime, proto_binary_fetched_timestamp, proto_binary_fetched_string, proto_binary_fetched_blob, proto_binary_fetched_enum, proto_binary_fetched_set, proto_binary_fetched_geometry, proto_binary_fetched_other | Connection | Total number of columns of a certain type fetched from a prepared statement (MySQL binary protocol). | For type mapping see proto_text_* above.

Connection

Statistic | Scope | Description | Notes
connect_success, connect_failure | Connection | Total number of successful / failed connection attempt. | Reused connections and all other kinds of connections are included.
reconnect | Process | Total number of (real_)connect attempts made on an already opened connection handle. | The code sequence $link = new mysqli(...); $link->real_connect(...) will cause a reconnect. But $link = new mysqli(...); $link->connect(...) will not because $link->connect(...) will explicitly close the existing connection before a new connection is established.
pconnect_success | Connection | Total number of successful persistent connection attempts. | Note that connect_success holds the sum of successful persistent and non-persistent connection attempts. The number of successful non-persistent connection attempts is connect_success - pconnect_success.
active_connections | Connection | Total number of active persistent and non-persistent connections.
active_persistent_connections | Connection | Total number of active persistent connections. | The total number of active non-persistent connections is active_connections - active_persistent_connections.
explicit_close Connection Total number of explicitly closed connections (ext/mysqli only). Examples of code snippets that cause an explicit close :
$link = new mysqli(...); $link->close(...)
$link = new mysqli(...); $link->connect(...)
implicit_close Connection Total number of implicitly closed connections (ext/mysqli only). Examples of code snippets that cause an implicit close :

  • $link = new mysqli(...); $link->real_connect(...)

  • unset($link)

  • Persistent connection: pooled connection has been created with real_connect and there may be unknown options set - close implicitly to avoid returning a connection with unknown options

  • Persistent connection: ping/change_user fails and ext/mysqli closes the connection

  • end of script execution: close connections that have not been closed by the user

disconnect_close | Connection | Connection failures indicated by the C API call mysql_real_connect() during an attempt to establish a connection. | It is called disconnect_close because the connection handle passed to the C API call will be closed.
in_middle_of_command_close | Process | A connection has been closed in the middle of a command execution (outstanding result sets not fetched, after sending a query and before retrieving an answer, while fetching data, while transferring data with LOAD DATA). | Unless you use asynchronous queries this should only happen if your script stops unexpectedly and PHP shuts down the connections for you.
init_command_executed_count | Connection | Total number of init command executions, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...). | The number of successful executions is init_command_executed_count - init_command_failed_count.
init_command_failed_count | Connection | Total number of failed init commands.

COM_* Commands

Statistic Scope Description Notes
com_quit, com_init_db, com_query, com_field_list, com_create_db, com_drop_db, com_refresh, com_shutdown, com_statistics, com_process_info, com_connect, com_process_kill, com_debug, com_ping, com_time, com_delayed_insert, com_change_user, com_binlog_dump, com_table_dump, com_connect_out, com_register_slave, com_stmt_prepare, com_stmt_execute, com_stmt_send_long_data, com_stmt_close, com_stmt_reset, com_stmt_set_option, com_stmt_fetch, com_daemon Connection Total number of attempts to send a certain COM_* command from PHP to MySQL.

The statistics are incremented after checking the line and immediately before sending the corresponding MySQL client server protocol packet. If mysqlnd fails to send the packet over the wire the statistics will not be decremented. In case of a failure mysqlnd emits a PHP warning "Error while sending %s packet. PID=%d."

Usage examples:

  • Check if PHP sends certain commands to MySQL, for example, check if a client sends COM_PROCESS_KILL

  • Calculate the average number of prepared statement executions by comparing COM_EXECUTE with COM_PREPARE

  • Check if PHP has run any non-prepared SQL statements by checking if COM_QUERY is zero

  • Identify PHP scripts that run an excessive number of SQL statements by checking COM_QUERY and COM_EXECUTE

Miscellaneous

Statistic | Scope | Description | Notes
explicit_stmt_close, implicit_stmt_close | Process | Total number of close prepared statements. | A close is always considered explicit but for a failed prepare.
mem_emalloc_count, mem_emalloc_ammount, mem_ecalloc_count, mem_ecalloc_ammount, mem_erealloc_count, mem_erealloc_ammount, mem_efree_count, mem_malloc_count, mem_malloc_ammount, mem_calloc_count, mem_calloc_ammount, mem_realloc_count, mem_realloc_ammount, mem_free_count | Process | Memory management calls. | Development only.
command_buffer_too_small Connection Number of network command buffer extensions while sending commands from PHP to MySQL.

mysqlnd allocates an internal command/network buffer of mysqlnd.net_cmd_buffer_size (php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY (normal query), does not fit into the buffer, mysqlnd will grow the buffer to what is needed for sending the command. Whenever the buffer gets extended for one connection command_buffer_too_small will be incremented by one.

If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size (php.ini) bytes for almost every connection, you should consider to increase the default size to avoid re-allocations.

The default buffer size is 2048 bytes in PHP 5.3.0. In future versions the default will be 4kB or larger. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size).

It is recommended to set the buffer size to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence mysqlnd is unable to decode the packet and the client application will get an error. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer_size in PHP 5.3.0: the packet transports a very long error message or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields()) and the meta data comes from a string column with a very long default value (>1900 bytes). No bug report on this exists - it should happen rarely.

As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes.

connection_reused
Persistent Connections
Notes
Mysqlnd


Colors

ncurses color constants
constant | meaning
NCURSES_COLOR_BLACK | no color (black)
NCURSES_COLOR_WHITE | white
NCURSES_COLOR_RED | red - supported when terminal is in color mode
NCURSES_COLOR_GREEN | green - supported when terminal is in color mode
NCURSES_COLOR_YELLOW | yellow - supported when terminal is in color mode
NCURSES_COLOR_BLUE | blue - supported when terminal is in color mode
NCURSES_COLOR_CYAN | cyan - supported when terminal is in color mode
NCURSES_COLOR_MAGENTA | magenta - supported when terminal is in color mode
Error codes
Keys
Predefined Constants


Predefined Constants

Table of Contents

  • Error codes
  • Colors
  • Keys
  • Mouse

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Resource Types
Error codes
Ncurses


Error codes

On error ncurses functions return -1. Some functions return 0 on success. See the relevant pages in the documentation for actual return values.

Predefined Constants
Colors
Predefined Constants


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/ncurses.

Wide character CRT screen handling (ncursesw) support was added in version 1.0.1 of this PECL extension.

Requirements
Runtime Configuration
Installing/Configuring


Keys

ncurses key constants
constant | meaning
NCURSES_KEY_F0 - NCURSES_KEY_F64 | function keys F1 - F64
NCURSES_KEY_DOWN | down arrow
NCURSES_KEY_UP | up arrow
NCURSES_KEY_LEFT | left arrow
NCURSES_KEY_RIGHT | right arrow
NCURSES_KEY_HOME | home key (upward+left arrow)
NCURSES_KEY_BACKSPACE | backspace
NCURSES_KEY_DL | delete line
NCURSES_KEY_IL | insert line
NCURSES_KEY_DC | delete character
NCURSES_KEY_IC | insert char or enter insert mode
NCURSES_KEY_EIC | exit insert char mode
NCURSES_KEY_CLEAR | clear screen
NCURSES_KEY_EOS | clear to end of screen
NCURSES_KEY_EOL | clear to end of line
NCURSES_KEY_SF | scroll one line forward
NCURSES_KEY_SR | scroll one line backward
NCURSES_KEY_NPAGE | next page
NCURSES_KEY_PPAGE | previous page
NCURSES_KEY_STAB | set tab
NCURSES_KEY_CTAB | clear tab
NCURSES_KEY_CATAB | clear all tabs
NCURSES_KEY_SRESET | soft (partial) reset
NCURSES_KEY_RESET | reset or hard reset
NCURSES_KEY_PRINT | print
NCURSES_KEY_LL | lower left
NCURSES_KEY_A1 | upper left of keypad
NCURSES_KEY_A3 | upper right of keypad
NCURSES_KEY_B2 | center of keypad
NCURSES_KEY_C1 | lower left of keypad
NCURSES_KEY_C3 | lower right of keypad
NCURSES_KEY_BTAB | back tab
NCURSES_KEY_BEG | beginning
NCURSES_KEY_CANCEL | cancel
NCURSES_KEY_CLOSE | close
NCURSES_KEY_COMMAND | cmd (command)
NCURSES_KEY_COPY | copy
NCURSES_KEY_CREATE | create
NCURSES_KEY_END | end
NCURSES_KEY_EXIT | exit
NCURSES_KEY_FIND | find
NCURSES_KEY_HELP | help
NCURSES_KEY_MARK | mark
NCURSES_KEY_MESSAGE | message
NCURSES_KEY_MOVE | move
NCURSES_KEY_NEXT | next
NCURSES_KEY_OPEN | open
NCURSES_KEY_OPTIONS | options
NCURSES_KEY_PREVIOUS | previous
NCURSES_KEY_REDO | redo
NCURSES_KEY_REFERENCE | ref (reference)
NCURSES_KEY_REFRESH | refresh
NCURSES_KEY_REPLACE | replace
NCURSES_KEY_RESTART | restart
NCURSES_KEY_RESUME | resume
NCURSES_KEY_SAVE | save
NCURSES_KEY_SBEG | shiftet beg (beginning)
NCURSES_KEY_SCANCEL | shifted cancel
NCURSES_KEY_SCOMMAND | shifted command
NCURSES_KEY_SCOPY | shifted copy
NCURSES_KEY_SCREATE | shifted create
NCURSES_KEY_SDC | shifted delete char
NCURSES_KEY_SDL | shifted delete line
NCURSES_KEY_SELECT | select
NCURSES_KEY_SEND | shifted end
NCURSES_KEY_SEOL | shifted end of line
NCURSES_KEY_SEXIT | shifted exit
NCURSES_KEY_SFIND | shifted find
NCURSES_KEY_SHELP | shifted help
NCURSES_KEY_SHOME | shifted home
NCURSES_KEY_SIC | shifted input
NCURSES_KEY_SLEFT | shifted left arrow
NCURSES_KEY_SMESSAGE | shifted message
NCURSES_KEY_SMOVE | shifted move
NCURSES_KEY_SNEXT | shifted next
NCURSES_KEY_SOPTIONS | shifted options
NCURSES_KEY_SPREVIOUS | shifted previous
NCURSES_KEY_SPRINT | shifted print
NCURSES_KEY_SREDO | shifted redo
NCURSES_KEY_SREPLACE | shifted replace
NCURSES_KEY_SRIGHT | shifted right arrow
NCURSES_KEY_SRSUME | shifted resume
NCURSES_KEY_SSAVE | shifted save
NCURSES_KEY_SSUSPEND | shifted suspend
NCURSES_KEY_UNDO | undo
NCURSES_KEY_MOUSE | mouse event has occurred
NCURSES_KEY_MAX | maximum key value
Colors
Mouse
Predefined Constants


Mouse

mouse constants
Constant | meaning
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED | button (1-4) released
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED | button (1-4) pressed
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED | button (1-4) clicked
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED | button (1-4) double clicked
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED | button (1-4) triple clicked
NCURSES_BUTTON_CTRL | ctrl pressed during click
NCURSES_BUTTON_SHIFT | shift pressed during click
NCURSES_BUTTON_ALT | alt pressed during click
NCURSES_ALL_MOUSE_EVENTS | report all mouse events
NCURSES_REPORT_MOUSE_POSITION | report mouse position
Keys
Ncurses Functions
Predefined Constants


Requirements

You need the ncurses libraries and headerfiles. Download the latest version from the » ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension defines window, panel and pad resources.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Ncurses


Predefined Constants

Table of Contents

  • Newt form exit reasons
  • Newt colorsets
  • Newt argument flags
  • Newt Flags Sense
  • Newt Components Flags
  • File Descriptor Flags
  • Checkbox Tree Flags
  • Entry Flags
  • Listbox Flags
  • Textbox Flags
  • Form Flags
  • Newt Keys
  • Newt Anchors
  • Grid Flags

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Resource Types
Newt form exit reasons
Newt


Examples

Table of Contents

  • Basic usage
Grid Flags
Basic usage
Newt


Basic usage

This example is a PHP port of RedHat 'setup' utility dialog, executed in text mode.

Example #1 Newt Usage Example

<?php
newt_init ();
newt_cls ();

newt_draw_root_text (0, 0, "Test Mode Setup Utility 1.12");
newt_push_help_line (null);
newt_draw_root_text (-30, 0, "(c) 1999-2002 RedHat, Inc");

newt_get_screen_size ($rows, $cols);

newt_open_window ($rows/2-17, $cols/2-10, 34, 17, "Choose a Tool");

$form = newt_form ();

$list = newt_listbox (3, 2, 10);

foreach (array (
    "Authentication configuration",
    "Firewall configuration",
    "Mouse configuration",
    "Network configuration",
    "Printer configuration",
    "System services") as $l_item)
{
    newt_listbox_add_entry ($list, $l_item, $l_item);
}

$b1 = newt_button (5, 12, "Run Tool");
$b2 = newt_button (21, 12, "Quit");

newt_form_add_component ($form, $list);
newt_form_add_components ($form, array($b1, $b2));

newt_refresh ();
newt_run_form ($form);

newt_pop_window ();
newt_pop_help_line ();
newt_finished ();
newt_form_destroy ($form);
?>
Examples
Newt Functions
Examples


Installation

This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/newt.

In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile CGI or CLI PHP with newt support by using the --with-newt[=DIR] configure option.

Note: This extension is not available for Windows platform.
You may need also curses and slang libraries, in order to compile this extension. To specify locations of these libraries, use the following configuration options: --with-curses-dir=/path/to/libcurses --with-slang-dir=/path/to/libslang

Requirements
Runtime Configuration
Installing/Configuring


Requirements

This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension uses two resource types: "newt component" and "newt grid".

Resource type "newt component" is returned by functions, which create common newt widgets (for example: newt_button())

Resource type "newt grid" is a special link identifier for components, returned by newt grid factory functions (for example: newt_create_grid())

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Newt


Checks if the provided string is already in the specified normalization form.

Normalizer
Normalizer::normalize
Normalizer
PHP Manual

Normalizer::isNormalized

normalizer_is_normalized

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Normalizer::isNormalized -- normalizer_is_normalized — Checks if the provided string is already in the specified normalization form.

Description

Object oriented style

static bool Normalizer::isNormalized ( string $input [, string $form = Normalizer::FORM_C ] )

Procedural style

bool normalizer_is_normalized ( string $input [, string $form = Normalizer::FORM_C ] )

Checks if the provided string is already in the specified normalization form.

Parameters

input

The input string to normalize

form

One of the normalization forms.

Return Values

TRUE if normalized, FALSE otherwise or if there an error

Examples

Example #1 normalizer_is_normalized() example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_orig = 'A' . $char_combining_ring_above;
$char_norm = normalizer_normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo ( normalizer_is_normalized($char_orig, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
echo '; ';
echo ( normalizer_is_normalized($char_norm, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
?>

Example #2 OO example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_orig = 'A' . $char_combining_ring_above;
$char_norm = Normalizer::normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo ( Normalizer::isNormalized($char_orig, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
echo '; ';
echo ( Normalizer::isNormalized($char_norm, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
?>

The above example will output:

not normalized; normalized

See Also

  • normalizer_normalize() - Normalizes the input provided and returns the normalized string

Normalizer
Normalizer::normalize
Normalizer


Normalizes the input provided and returns the normalized string

Normalizer::isNormalized
MessageFormatter
Normalizer
PHP Manual

Normalizer::normalize

normalizer_normalize

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Normalizer::normalize -- normalizer_normalize — Normalizes the input provided and returns the normalized string

Description

Object oriented style

static string Normalizer::normalize ( string $input [, string $form = Normalizer::FORM_C ] )

Procedural style

string normalizer_normalize ( string $input [, string $form = Normalizer::FORM_C ] )

Normalizes the input provided and returns the normalized string

Parameters

input

The input string to normalize

form

One of the normalization forms.

Return Values

The normalized string or NULL if an error occurred.

Examples

Example #1 normalizer_normalize() example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_1 = normalizer_normalize( $char_A_ring, Normalizer::FORM_C );
$char_2 = normalizer_normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo urlencode($char_1);
echo ' ';
echo urlencode($char_2);
?>

Example #2 OO example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_1 = Normalizer::normalize( $char_A_ring, Normalizer::FORM_C );
$char_2 = Normalizer::normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo urlencode($char_1);
echo ' ';
echo urlencode($char_2);
?>

The above example will output:

%C3%85 %C3%85

See Also

  • normalizer_is_normalized() - Checks if the provided string is already in the specified normalization form.

Normalizer::isNormalized
MessageFormatter
Normalizer


Create a number formatter

NumberFormatter
NumberFormatter::formatCurrency
NumberFormatter
PHP Manual

NumberFormatter::create

numfmt_create

NumberFormatter::__construct

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::create -- numfmt_create -- NumberFormatter::__construct — Create a number formatter

Description

Object oriented style (method)

static NumberFormatter NumberFormatter::create ( string $locale , int $style [, string $pattern ] )

Procedural style

NumberFormatter numfmt_create ( string $locale , int $style [, string $pattern ] )

Object oriented style (constructor):

NumberFormatter::__construct ( string $locale , int $style [, string $pattern ] )

Creates a number formatter.

Parameters

locale

Locale in which the number would be formatted (locale name, e.g. en_CA).

style

Style of the formatting, one of the format style constants. If NumberFormatter::PATTERN_DECIMAL or NumberFormatter::PATTERN_RULEBASED is passed then the number format is opened using the given pattern, which must conform to the syntax described in » ICU DecimalFormat documentation or » ICU RuleBasedNumberFormat documentation, respectively.

pattern

Pattern string in case chosen style requires pattern.

Return Values

Returns NumberFormatter object or FALSE on error.

Examples

Example #1 numfmt_create() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
$fmt = numfmt_create( 'it', NumberFormatter::SPELLOUT );
echo numfmt_format($fmt, 1142)."\n";
?>

Example #2 NumberFormatter::create() example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo $fmt->format(1234567.891234567890000)."\n";
$fmt = new NumberFormatter( 'it', NumberFormatter::SPELLOUT );
echo $fmt->format(1142)."\n";
?>

The above example will output:

1.234.567,891
millicentoquarantadue

See Also

  • numfmt_format() - Format a number
  • numfmt_parse() - Parse a number

NumberFormatter
NumberFormatter::formatCurrency
NumberFormatter


Format a number

NumberFormatter::formatCurrency
NumberFormatter::getAttribute
NumberFormatter
PHP Manual

NumberFormatter::format

numfmt_format

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::format -- numfmt_format — Format a number

Description

Object oriented style

string NumberFormatter::format ( number $value [, int $type ] )

Procedural style

string numfmt_format ( NumberFormatter $fmt , number $value [, int $type ] )

Format a numeric value according to the formatter rules.

Parameters

fmt

NumberFormatter object.

value

The value to format. Can be integer or double, other values will be converted to a numeric value.

type

The formatting type to use.

Return Values

Returns the string containing formatted value, or FALSE on error.

Examples

Example #1 numfmt_format() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_format($fmt))) {
    report_error("Formatter error");
}
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("Formatter error");
}
?>

The above example will output:

1.234.567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_format_currency() - Format a currency value
  • numfmt_parse() - Parse a number

NumberFormatter::formatCurrency
NumberFormatter::getAttribute
NumberFormatter


Format a currency value

NumberFormatter::create
NumberFormatter::format
NumberFormatter
PHP Manual

NumberFormatter::formatCurrency

numfmt_format_currency

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::formatCurrency -- numfmt_format_currency — Format a currency value

Description

Object oriented style

string NumberFormatter::formatCurrency ( float $value , string $currency )

Procedural style

string numfmt_format_currency ( NumberFormatter $fmt , float $value , string $currency )

Format the currency value according to the formatter rules.

Parameters

fmt

NumberFormatter object.

value

The numeric currency value.

currency

The 3-letter ISO 4217 currency code indicating the currency to use.

Return Values

String representing the formatted currency value.

Examples

Example #1 numfmt_format_currency() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";
echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n";
$fmt = numfmt_create( 'ru_RU', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";
echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
$fmt = new NumberFormatter( 'ru_RU', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
?>

The above example will output:

1.234.567,89 €
1.234.567,89 RUR
1 234 567,89€
1 234 567,89р.

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_format() - Format a number
  • numfmt_parse_currency() - Parse a currency number

NumberFormatter::create
NumberFormatter::format
NumberFormatter


Get an attribute

NumberFormatter::format
NumberFormatter::getErrorCode
NumberFormatter
PHP Manual

NumberFormatter::getAttribute

numfmt_get_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getAttribute -- numfmt_get_attribute — Get an attribute

Description

Object oriented style

int NumberFormatter::getAttribute ( int $attr )

Procedural style

int numfmt_get_attribute ( NumberFormatter $fmt , int $attr )

Get a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce.

Parameters

fmt

NumberFormatter object.

attr

Attribute specifier - one of the numeric attribute constants.

Return Values

Return attribute value on success, or FALSE on error.

Examples

Example #1 numfmt_get_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Digits: 3
1.234.567,891
Digits: 2
1.234.567,89

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_text_attribute() - Get a text attribute
  • numfmt_set_attribute() - Set an attribute

NumberFormatter::format
NumberFormatter::getErrorCode
NumberFormatter


Get formatter's last error code.

NumberFormatter::getAttribute
NumberFormatter::getErrorMessage
NumberFormatter
PHP Manual

NumberFormatter::getErrorCode

numfmt_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getErrorCode -- numfmt_get_error_code — Get formatter's last error code.

Description

Object oriented style

int NumberFormatter::getErrorCode ( void )

Procedural style

int numfmt_get_error_code ( NumberFormatter $fmt )

Get error code from the last function performed by the formatter.

Parameters

fmt

NumberFormatter object.

Return Values

Returns error code from last formatter call.

Examples

Example #1 numfmt_get_error_code() example

<?php
$fmt  = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_get_error_code($fmt))) {
    report_error("Formatter error");
}
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("Formatter error");
}
?>

See Also

  • numfmt_get_error_message() - Get formatter's last error message.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

NumberFormatter::getAttribute
NumberFormatter::getErrorMessage
NumberFormatter


Get formatter's last error message.

NumberFormatter::getErrorCode
NumberFormatter::getLocale
NumberFormatter
PHP Manual

NumberFormatter::getErrorMessage

numfmt_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getErrorMessage -- numfmt_get_error_message — Get formatter's last error message.

Description

Object oriented style

string NumberFormatter::getErrorMessage ( void )

Procedural style

string numfmt_get_error_message ( NumberFormatter $fmt )

Get error message from the last function performed by the formatter.

Parameters

fmt

NumberFormatter object.

Return Values

Returns error message from last formatter call.

Examples

Example #1 numfmt_get_error_message() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_get_error_code($fmt))) {
    report_error("Formatter error");
}
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("Formatter error");
}
?>

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

NumberFormatter::getErrorCode
NumberFormatter::getLocale
NumberFormatter


Get formatter locale

NumberFormatter::getErrorMessage
NumberFormatter::getPattern
NumberFormatter
PHP Manual

NumberFormatter::getLocale

numfmt_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getLocale -- numfmt_get_locale — Get formatter locale

Description

Object oriented style

string NumberFormatter::getLocale ([ int $type ] )

Procedural style

string numfmt_get_locale ( NumberFormatter $fmt [, int $type ] )

Get formatter locale name.

Parameters

fmt

NumberFormatter object.

type

You can choose between valid and actual locale ( Locale::VALID_LOCALE, Locale::ACTUAL_LOCALE, respectively). The default is the actual locale.

Return Values

The locale name used to create the formatter.

Examples

Example #1 numfmt_get_locale() example

<?php
$req     = 'fr_FR_PARIS';
$fmt     = numfmt_create( $req,  NumberFormatter::DECIMAL);
$res_val = numfmt_get_locale( $fmt, Locale::VALID_LOCALE );
$res_act = numfmt_get_locale( $fmt, Locale::ACTUAL_LOCALE );
printf( "Requested locale name: %s\nValid locale name: %s\nActual locale name: %s\n",
         $req, $res_val, $res_act );
?>

The above example will output:

Requested locale name: fr_FR_PARIS
Valid locale name: fr_FR
Actual locale name: fr

See Also

  • numfmt_create() - Create a number formatter
  • numfmt_get_error_code() - Get formatter's last error code.

NumberFormatter::getErrorMessage
NumberFormatter::getPattern
NumberFormatter


Get formatter pattern

NumberFormatter::getLocale
NumberFormatter::getSymbol
NumberFormatter
PHP Manual

NumberFormatter::getPattern

numfmt_get_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getPattern -- numfmt_get_pattern — Get formatter pattern

Description

Object oriented style

string NumberFormatter::getPattern ( void )

Procedural style

string numfmt_get_pattern ( NumberFormatter $fmt )

Extract pattern used by the formatter.

Parameters

fmt

NumberFormatter object.

Return Values

Pattern string that is used by the formatter, or FALSE if an error happens.

Examples

Example #1 numfmt_get_pattern() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_pattern($fmt, "#0.# kg");
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setPattern("#0.# kg");
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Pattern: #,##0.###
1.234.567,891
Pattern: #0.# kg
1234567,9 kg

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_set_pattern() - Set formatter pattern
  • numfmt_create() - Create a number formatter

NumberFormatter::getLocale
NumberFormatter::getSymbol
NumberFormatter


Get a symbol value

NumberFormatter::getPattern
NumberFormatter::getTextAttribute
NumberFormatter
PHP Manual

NumberFormatter::getSymbol

numfmt_get_symbol

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getSymbol -- numfmt_get_symbol — Get a symbol value

Description

Object oriented style

string NumberFormatter::getSymbol ( int $attr )

Procedural style

string numfmt_get_symbol ( NumberFormatter $fmt , int $attr )

Get a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.

Parameters

fmt

NumberFormatter object.

attr

Symbol specifier, one of the format symbol constants.

Return Values

The symbol string or FALSE on error.

Examples

Example #1 numfmt_get_symbol() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Sep: .
1.234.567,891
Sep: *
1*234*567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_set_symbol() - Set a symbol value

NumberFormatter::getPattern
NumberFormatter::getTextAttribute
NumberFormatter


Get a text attribute

NumberFormatter::getSymbol
NumberFormatter::parseCurrency
NumberFormatter
PHP Manual

NumberFormatter::getTextAttribute

numfmt_get_text_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getTextAttribute -- numfmt_get_text_attribute — Get a text attribute

Description

Object oriented style

string NumberFormatter::getTextAttribute ( int $attr )

Procedural style

string numfmt_get_text_attribute ( NumberFormatter $fmt , int $attr )

Get a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, U_UNSUPPORTED_ERROR error is produced. Rule-based formatters only understand NumberFormatter::DEFAULT_RULESET and NumberFormatter::PUBLIC_RULESETS.

Parameters

fmt

NumberFormatter object.

attr

Attribute specifier - one of the text attribute constants.

Return Values

Return attribute value on success, or FALSE on error.

Examples

Example #1 numfmt_get_text_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
$fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
?>

The above example will output:

Prefix: -
-1.234.567,891
Prefix: MINUS
MINUS1.234.567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_attribute() - Get an attribute
  • numfmt_set_text_attribute() - Set a text attribute

NumberFormatter::getSymbol
NumberFormatter::parseCurrency
NumberFormatter


Parse a number

NumberFormatter::parseCurrency
NumberFormatter::setAttribute
NumberFormatter
PHP Manual

NumberFormatter::parse

numfmt_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::parse -- numfmt_parse — Parse a number

Description

Object oriented style

mixed NumberFormatter::parse ( string $value [, int $type [, int &$position ]] )

Procedural style

mixed numfmt_parse ( NumberFormatter $fmt , string $value [, int $type [, int &$position ]] )

Parse a string into a number using the current formatter rules.

Parameters

fmt

NumberFormatter object.

type

The formatting type to use. By default, NumberFormatter::TYPE_DOUBLE is used.

position

Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended.

Return Values

The value of the parsed number or FALSE on error.

Examples

Example #1 numfmt_parse() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo numfmt_parse($fmt, $num)."\n";
echo numfmt_parse($fmt, $num, NumberFormatter::TYPE_INT32)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo $fmt->parse($num)."\n";
echo $fmt->parse($num, NumberFormatter::TYPE_INT32)."\n";
?>

The above example will output:

1234567.891
1234567

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_format() - Format a number
  • numfmt_parse_currency() - Parse a currency number

NumberFormatter::parseCurrency
NumberFormatter::setAttribute
NumberFormatter


Parse a currency number

NumberFormatter::getTextAttribute
NumberFormatter::parse
NumberFormatter
PHP Manual

NumberFormatter::parseCurrency

numfmt_parse_currency

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::parseCurrency -- numfmt_parse_currency — Parse a currency number

Description

Object oriented style

float NumberFormatter::parseCurrency ( string $value , string &$currency [, int &$position ] )

Procedural style

float numfmt_parse_currency ( NumberFormatter $fmt , string $value , string &$currency [, int &$position ] )

Parse a string into a double and a currency using the current formatter.

Parameters

fmt

NumberFormatter object.

currency

Parameter to receive the currency name (3-letter ISO 4217 currency code).

position

Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended.

Return Values

The parsed numeric value or FALSE on error.

Examples

Example #1 numfmt_parse_currency() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89 $";
echo "We have ".numfmt_parse_currency($fmt, $num, $curr)." in $curr\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89 $";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
?>

The above example will output:

We have 1234567.89 in USD

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_parse() - Parse a number
  • numfmt_format_currency() - Format a currency value

NumberFormatter::getTextAttribute
NumberFormatter::parse
NumberFormatter


Set an attribute

NumberFormatter::parse
NumberFormatter::setPattern
NumberFormatter
PHP Manual

NumberFormatter::setAttribute

numfmt_set_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setAttribute -- numfmt_set_attribute — Set an attribute

Description

Object oriented style

bool NumberFormatter::setAttribute ( int $attr , int $value )

Procedural style

bool numfmt_set_attribute ( NumberFormatter $fmt , int $attr , int $value )

Set a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce.

Parameters

fmt

NumberFormatter object.

attr

Attribute specifier - one of the numeric attribute constants.

value

The attribute value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 numfmt_set_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Digits: 3
1.234.567,891
Digits: 2
1.234.567,89

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_attribute() - Get an attribute
  • numfmt_set_text_attribute() - Set a text attribute

NumberFormatter::parse
NumberFormatter::setPattern
NumberFormatter


Set formatter pattern

NumberFormatter::setAttribute
NumberFormatter::setSymbol
NumberFormatter
PHP Manual

NumberFormatter::setPattern

numfmt_set_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setPattern -- numfmt_set_pattern — Set formatter pattern

Description

Object oriented style

bool NumberFormatter::setPattern ( string $pattern )

Procedural style

bool numfmt_set_pattern ( NumberFormatter $fmt , string $pattern )

Set the pattern used by the formatter. Can not be used on a rule-based formatter.

Parameters

fmt

NumberFormatter object.

pattern

Pattern in syntax described in » ICU DecimalFormat documentation.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 numfmt_set_pattern() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_pattern($fmt, "#0.# kg");
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setPattern("#0.# kg");
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Pattern: #,##0.###
1.234.567,891
Pattern: #0.# kg
1234567,9 kg

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_create() - Create a number formatter
  • numfmt_get_pattern() - Get formatter pattern

NumberFormatter::setAttribute
NumberFormatter::setSymbol
NumberFormatter


Set a symbol value

NumberFormatter::setPattern
NumberFormatter::setTextAttribute
NumberFormatter
PHP Manual

NumberFormatter::setSymbol

numfmt_set_symbol

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setSymbol -- numfmt_set_symbol — Set a symbol value

Description

Object oriented style

bool NumberFormatter::setSymbol ( int $attr , string $value )

Procedural style

bool numfmt_set_symbol ( NumberFormatter $fmt , int $attr , string $value )

Set a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.

Parameters

fmt

NumberFormatter object.

attr

Symbol specifier, one of the format symbol constants.

value

Text for the symbol.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 numfmt_set_symbol() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

The above example will output:

Sep: .
1.234.567,891
Sep: *
1*234*567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_symbol() - Get a symbol value

NumberFormatter::setPattern
NumberFormatter::setTextAttribute
NumberFormatter


Set a text attribute

NumberFormatter::setSymbol
Locale
NumberFormatter
PHP Manual

NumberFormatter::setTextAttribute

numfmt_set_text_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setTextAttribute -- numfmt_set_text_attribute — Set a text attribute

Description

Object oriented style

bool NumberFormatter::setTextAttribute ( int $attr , string $value )

Procedural style

bool numfmt_set_text_attribute ( NumberFormatter $fmt , int $attr , string $value )

Set a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, U_UNSUPPORTED_ERROR error is produced. Rule-based formatters only understand NumberFormatter::DEFAULT_RULESET and NumberFormatter::PUBLIC_RULESETS.

Parameters

fmt

NumberFormatter object.

attr

Attribute specifier - one of the text attribute constants.

value

Text for the attribute value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 numfmt_set_text_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
$fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
?>

The above example will output:

Prefix: -
-1.234.567,891
Prefix: MINUS
MINUS1.234.567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_text_attribute() - Get a text attribute
  • numfmt_set_attribute() - Set an attribute

NumberFormatter::setSymbol
Locale
NumberFormatter


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

OCI8 Configuration Options
Name | Default | Changeable | Changelog
oci8.connection_class | "" | PHP_INI_ALL | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.default_prefetch | "100" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.events | Off | PHP_INI_SYSTEM | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.privileged_connect | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).

Here's a short explanation of the configuration directives.

oci8.connection_class string

This user defined text is used by Oracle 11g Database Resident Connection Pooling (DRCP) connections to sub-partition the connection pool. It allows OCI8 persistent connections from an application to reuse database sessions from a previous PHP script, giving better scalability. When an application uses a database pooled process previously used with a different connection class, the session settings such as the default Oracle date format are reset. This prevents accidental sharing of information between different applications.

The value can be set at runtime with ini_set() prior to connecting.

To use DRCP, OCI8 must be linked with Oracle 11g libraries and the database must be Oracle 11g. The connection pool must be enabled in the database, the oci8.connection_class should be set to the same string for all web servers running the same application, and the OCI8 connection string must specify to use a pooled server.

oci8.default_prefetch int

This option sets the default number of extra rows that will be fetched and cached automatically whenever a low-level request for data from the database is made. Setting a value of 0 turns off prefetching.

The prefetch value does not alter the number of rows that functions like oci_fetch_array() return to the user; the prefetching and caching of rows is handled internally in OCI8.

The value can be set per-statement with oci_set_prefetch() prior to statement execution.

In PHP 5.3 (PECL OCI8 1.3.4) the default value was increased from 10 to 100.

In PHP 5.3.2 (PECL OCI8 1.4) the minimum value settable was reduced from 1 to 0, allowing prefetching to be turned off.

Note: A larger prefetch can result in improved performance, at the cost of some increased memory usage. For queries that return large amounts of data, the performance benefit can be significant.

oci8.events boolean

Using On allows PHP to be notified of database Fast Application Notification (FAN) events.

Without FAN, when a database instance or machine node fails unexpectedly, PHP applications may be blocked waiting for a database response until a TCP timeout expires. With FAN events, PHP applications are quickly notified of failures that affect their established database connections. The OCI8 extension will clean up unusable connections in the persistent connection cache.

When using On, the database must also be configured to post FAN events.

FAN support is available when OCI8 is linked with Oracle 10gR2 (or later) libraries and connected to Oracle Database 10gR2 (or later).

oci8.max_persistent int

The maximum number of persistent OCI8 connections per PHP process. Setting this option to -1 means that there is no limit.

oci8.old_oci_close_semantics boolean

This option controls oci_close() behaviour. Enabling it means that oci_close() will do nothing; the connection will not be closed until the end of the script. This is for backward compatibility only. If you find that you need to enable this setting, you are strongly encouraged to adjust the oci_close() calls in your application instead of enabling this option.

oci8.persistent_timeout int

The maximum number of seconds that a PHP process is allowed to keep an idle persistent connection open. Setting this option to -1 means that idle persistent connections will be retained until the PHP process terminates or the connection is explicitly closed with oci_close().

Note: In PHP, the expiry of idle resources is not alarm-based. It occurs when PHP finishes processing a script and checks the last-used timestamp of resources. Hence there is a paradox that idle connections can only be closed when there is some activity (though not necessarily OCI8 related) in the PHP process. The introduction of Database Resident Connection Pooling (DRCP) in Oracle 11g resolves the memory and resource issues that oci8.max_persistent and oci8.persistent_timeout previously attempted to overcome.

Note: In PHP 5.3 (PECL OCI8 1.3), persistent connections can be closed with oci_close().

oci8.ping_interval int

The number of seconds that must pass before issuing a ping during oci_pconnect(). A ping ensures that the database connection is valid. When set to 0, persistent connections will be pinged every time oci_pconnect() is called. To disable pings completely, set this option to -1.

Note: Disabling pings allows oci_pconnect() to operate at the highest efficiency, but PHP may not be able to detect unusable connections, such as caused by network dropout, or if the Oracle database has gone down since PHP connected, until the connection is used later in the script. Consult the oci_pconnect() documentation for more information.

oci8.privileged_connect boolean

This option allows connections to use the privileged external credentials OCI_SYSOPER or OCI_SYSDBA.

Note: Seting this On can allow scripts on web servers running with the appropriate OS user privileges to connect as privileged database users without requiring a database password. This can be a security risk.

oci8.statement_cache_size int

This option enables statement caching, and specifies how many statements to cache. To disable statement caching just set this option to 0.

Statement caching removes the need to transmit the statement text to the database and removes the need to transmit any meta data about the statement back to PHP. This can significantly improve overall system performance in applications which reuse statements during the lifetime of a connection. Some extra database "cursors" may be held open under the assumption that statements will be reused.

Set this value to the size of the working set of statements used by your application. Setting too small a value can cause statements to be flushed from the cache before they are reused.

This option is of most use with persistent connections.

Testing
Predefined Constants
Installing/Configuring


Connection Handling

Connection Functions

The OCI8 extension provides three different functions for connecting to Oracle. The standard connection function is oci_connect(). This creates a connection to an Oracle database and returns a resource used by subsequent database calls.

Connecting to an Oracle server is a reasonably expensive operation in terms of the time that it takes to complete. The oci_pconnect() function uses a persistent cache of connections that can be re-used across different script requests. This means that the connection overhead will typically only occur once per PHP process (or Apache child).

If the application connects to Oracle using a different set of credentials for each web user, the persistent cache employed by oci_pconnect() will become less useful as the number of concurrent users increases, to the point where it may start to adversely affect the overall performance of the Oracle server due to maintaining too many idle connections. If the application is structured in this way, it is recommended to either tune the application using the oci8.max_persistent and oci8.persistent_timeout configuration settings (these will give control over the persistent connection cache size and lifetime), use Oracle 11g Database Resident Connection Pooling, or use oci_connect() instead.

Both oci_connect() and oci_pconnect() employ a connection cache; if multiple calls to oci_connect() use the same parameters in a given script, the second and subsequent calls return the existing connection handle. The cache used by oci_connect() is cleaned up at the end of the script run, or when the connection handle is explicitly closed. The function oci_pconnect() has similar behavior, although its cache is maintained separately and survives between HTTP requests.

This caching feature means the two handles are not transactionally isolated (they are in fact the same connection handle, so there is no isolation of any kind). If the application needs two separate, transactionally isolated connections, then use oci_new_connect().

The oci_pconnect() cache is cleared and any database connections closed when the PHP process terminates, so effective use of persistent connections requires that PHP be an Apache module or used with FGCI, or similar. Persistent connections will not have any benefits over oci_connect() when PHP is used with CGI or via the command-line.

The function oci_new_connect() always creates a new connection to the Oracle server, regardless of what other connections might already exist. High traffic web applications should avoid using oci_new_connect(), especially in the busiest sections of the application.

DRCP Connection Pooling

PHP 5.3 (PECL OCI8 1.3) supports Oracle 11g Database Resident Connection Pooling (DRCP). DRCP allows more efficient use of database machine memory and provides high scalability. No, or minimal, application changes are needed to use DRCP.

DRCP is suited for applications that connect using few database schemas and hold database connections open for a short period of time. Other applications should use Oracle's default Dedicated database server processes, or use Shared servers.

DRCP benefits all three connection functions, but gives the highest scalability when connections are created with oci_pconnect().

For DRCP to be available in OCI8, Oracle client libraries used by PHP and the version of the Oracle Database must both be 11g.

Documentation on DRCP is found in several Oracle manuals. For example, see » Configuring Database Resident Connection Pooling in the Oracle documentation for usage information. A » DRCP white paper contains background information on DRCP.

To use DRCP, build PHP with the OCI8 1.3 extension and Oracle 11g libraries and then follow these steps:

  • As a privileged database administrator, use a program like SQL*Plus to start the connection pool in the database:

        SQL> execute dbms_connection_pool.start_pool;

  • Optionally use dbms_connection_pool.alter_param() to configure DRCP settings. The current pool settings can be queried from the DBA_CPOOL_INFO view.

  • Update the connection strings used. For PHP applications that currently connect using a Network Connect Name like MYDB:

        $c = oci_pconnect("myuser", "mypassword", "MYDB");

    modify the tnsnames.ora file and add a (SERVER=POOLED) clause, for example:

        MYDB = (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=myhost.dom.com)
           (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)
           (SERVER=POOLED)))

    Alternatively, modify the Easy Connect syntax in PHP and add :POOLED after the service name:

        $c = oci_pconnect("myuser", "mypassword", "myhost.dom.com:1521/sales:POOLED");

  • Edit php.ini and choose a connection class name. This name indicates a logical division of the connection pool and can be used to isolate pooling for separate applications. Any PHP applications with the same user name and connection class value will be able to share connections in the pool, giving greater scalability.

        oci8.connection_class = "MY_APPLICATION_NAME"

  • Run the application, connecting to the 11g database.

Note: Applications using Oracle 10g that require the performance of persistent connections can reduce the amount of database server memory needed by using Oracle Shared servers (previously known as Multi Threaded Servers). Refer to Oracle documentation for information.

DRCP Recommendations and Known Limitations

Changing a password over DRCP connections will fail with the error ORA-56609: Usage not supported with DRCP. This is a documented restriction of Oracle Database 11g.

With the OCI8 1.3 extension, persistent connections can now be closed by the user, allowing greater control over connection resource usage. Persistent connections will now also be closed automatically when there is no PHP variable referencing them, such as at the end of scope of a PHP user function. This will rollback any uncommitted transaction. These changes to persistent connections make them behave similarly to non-persistent connections, simplifying the interface, allowing for greater application consistency and predictability. Use oci8.old_oci_close_semantics set to On to retain the historical behavior.

If the Oracle Database is version 11.1.0.6, then the Oracle database patch for Oracle bug 6474441 must be applied to use DRCP. Without this patch, errors such as ORA-01000: maximum open cursors exceeded, ORA-01001 invalid cursor or ORA-01002 fetch out of sequence may occur. This bug was fixed in Oracle 11.1.0.7 onwards.

If the Oracle 11.1.0.6 database patch cannot be applied, one of the following three workarounds can be used instead:

  • Connect using Oracle Dedicated or Shared servers instead of DRCP.
  • Set PHP's oci8.statement_cache_size to 0.
  • Set an event in the database initialization parameter file: event="56699 trace name context forever, level 128".

Oracle Database 11.1.0.7 and the Oracle Database 11.1.0.6 patch for Oracle bug 6474441 allow PHP applications with DRCP connection to use a database LOGON trigger to set session properties at the time of session creation. Examples of such settings are the NLS language and the date format.

If the Oracle 11.1.0.6 database patch cannot be applied, one of the following workarounds can be used instead of using LOGON triggers:

  • After logon, explicitly set the session properties using PHP application code.
  • Connect using Oracle Dedicated or Shared servers instead of DRCP.

The automatic re-establishment of PHP persistent connections after an Apache or FGCI process respawns means LOGON triggers in PHP are only recommended for setting session attributes and not for per-application user connection requests. This is even more so with DRCP due to the automatic pool sizing and with the way LOGON triggers fire with DRCP authentication.

Fast Application Notification (FAN) Support

FAN support gives fast connection failover, a high availability feature. This allows PHP OCI8 scripts to be notified when a database machine or database instance becomes unavailable. Without FAN, OCI8 can hang until a TCP timeout occurs and an error is returned, which might be several minutes. Enabling FAN in OCI8 can allow applications to detect errors and re-connect to an available database instance without the web user being aware of an outage.

FAN support is available when the Oracle client libraries that PHP links with and the Oracle Database are either version 10gR2 or 11g.

FAN benefits users of Oracle's clustering technology (RAC) because connections to surviving database instances can be immediately made. Users of Oracle's Data Guard with a broker will see the FAN events generated when the standby database goes online. Standalone databases will send FAN events when the database restarts.

For active connections, when a machine or database instance becomes unavailable, a connection failure error will be returned by the OCI8 extension function currently being called. On a subsequent PHP script re-connect, a connection to a surviving database instance will be established. The OCI8 extension also transparently cleans up any idle connections affected by a database machine or instance failure so PHP connect calls will establish a fresh connection without the script being aware of any service disruption.

When oci8.events is On, it is suggested to set oci8.ping_interval to -1 to disable pinging, since enabling FAN events provide pro-active connection management of idle connections made invalid by a service disruption.

To enable FAN support in PHP, build PHP with Oracle 10gR2 or 11g libraries and then follow these steps:

  • As a privileged database administrator, use a program like SQL*Plus to enable the database service to post FAN events, for example:

        SQL> execute dbms_service.modify_service(
                   SERVICE_NAME        => 'sales',
                   AQ_HA_NOTIFICATIONS => TRUE);

  • Edit php.ini and add

        oci8.events = On

  • If the application does not already handle OCI8 error conditions, modify it to detect failures and take appropriate action. This may include re-connecting and re-executing statements.
  • Run the application, connecting to an Oracle 10gR2 or 11g database.

Examples
Supported Datatypes
OCI8


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

OCI8 Function and Method Modes
Constant | Description
OCI_ASSOC | Used with oci_fetch_all() and oci_fetch_array() to get results as an associative array.
OCI_BOTH | Used with oci_fetch_all() and oci_fetch_array() to get results as an array with both associative and number indices.
OCI_COMMIT_ON_SUCCESS | Statement execution mode for oci_execute() call. Automatically commit changes when the statement has succeeded.
OCI_CRED_EXT | Used with oci_connect() for using Oracles' External or OS authentication. Introduced in PHP 5.3 and PECL OCI8 1.3.4.
OCI_DEFAULT | Statement execution mode for oci_execute(). The transaction is not automatically committed when using this mode. From PHP 5.3.2 (PECL OCI8 1.4) onwards, OCI_NO_AUTO_COMMIT is preferred instead of OCI_DEFAULT.
OCI_DESCRIBE_ONLY | Statement execution mode for oci_execute(). Use this mode if you want meta data such as the column names but don't want to fetch rows from the query.
OCI_EXACT_FETCH | Obsolete. Statement fetch mode. Used when the application knows in advance exactly how many rows it will be fetching. This mode turns prefetching off for Oracle release 8 or later mode. The cursor is canceled after the desired rows are fetched which may result in reduced server-side resource usage.
OCI_FETCHSTATEMENT_BY_COLUMN | Default mode of oci_fetch_all().
OCI_FETCHSTATEMENT_BY_ROW | Alternative mode of oci_fetch_all().
OCI_LOB_BUFFER_FREE | Used with OCI-Lob->flush to free buffers used.
OCI_NO_AUTO_COMMIT | Statement execution mode for oci_execute(). The statement is not committed automatically when using this mode. For readability in new code, use this value instead of the obsolete OCI_DEFAULT constant. Introduced in PHP 5.3.2 (PECL OCI8 1.4).
OCI_NUM | Used with oci_fetch_all() and oci_fetch_array() to get results as an enumerated array.
OCI_RETURN_LOBS | Used with oci_fetch_array() to get the data value of the LOB instead of the descriptor.
OCI_RETURN_NULLS | Used with oci_fetch_array() to get empty array elements if the row items value is NULL.
OCI_SEEK_CUR | Used with OCI-Lob->seek to set the seek position.
OCI_SEEK_END | Used with OCI-Lob->seek to set the seek position.
OCI_SEEK_SET | Used with OCI-Lob->seek to set the seek position.
OCI_SYSDATE | Obsolete.
OCI_SYSDBA | Used with oci_connect() to connect with the SYSDBA privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
OCI_SYSOPER | Used with oci_connect() to connect with the SYSOPER privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
OCI_TEMP_BLOB | Used with OCI-Lob->writeTemporary to indicate that a temporary BLOB should be created.
OCI_TEMP_CLOB | Used with OCI-Lob->writeTemporary to indicate that a temporary CLOB should be created.
OCI8 Bind and Define Types
Constant | Description
OCI_B_BFILE | Used with oci_bind_by_name() when binding BFILEs.
OCI_B_BIN |
OCI_B_BLOB | Used with oci_bind_by_name() when binding BLOBs.
OCI_B_CFILEE | Used with oci_bind_by_name() when binding CFILEs.
OCI_B_CLOB | Used with oci_bind_by_name() when binding CLOBs.
OCI_B_CURSOR | Used with oci_bind_by_name() when binding cursors, previously allocated with oci_new_descriptor().
OCI_B_INT | Used with oci_bind_array_by_name() to bind arrays of INTEGER.
OCI_B_NTY | Used with oci_bind_by_name() when binding named data types. Note: in PHP < 5.0 it was called OCI_B_SQLT_NTY.
OCI_B_NUM | Used with oci_bind_array_by_name() to bind arrays of NUMBER.
OCI_B_ROWID | Used with oci_bind_by_name() when binding ROWIDs.
SQLT_AFC | Used with oci_bind_array_by_name() to bind arrays of CHAR.
SQLT_AVC | Used with oci_bind_array_by_name() to bind arrays of VARCHAR2.
SQLT_BDOUBLE |
SQLT_BFILEE | The same as OCI_B_BFILE.
SQLT_BFLOAT |
SQLT_BIN | Used with oci_bind_by_name() to bind RAW values.
SQLT_BLOB | The same as OCI_B_BLOB.
SQLT_CFILEE | The same as OCI_B_CFILEE.
SQLT_CHR | Used with oci_bind_array_by_name() to bind arrays of VARCHAR2. Also used with oci_bind_by_name().
SQLT_CLOB | The same as OCI_B_CLOB.
SQLT_FLT | Used with oci_bind_array_by_name() to bind arrays of FLOAT.
SQLT_INT | The same as OCI_B_INT.
SQLT_LBI | Used with oci_bind_by_name() to bind LONG RAW values.
SQLT_LNG | Used with oci_bind_by_name() to bind LONG values.
SQLT_LVC | Used with oci_bind_array_by_name() to bind arrays of LONG VARCHAR.
SQLT_NTY | The same as OCI_B_NTY.
SQLT_NUM | The same as OCI_B_NUM.
SQLT_ODT | Used with oci_bind_array_by_name() to bind arrays of LONG.
SQLT_RDD | The same as OCI_B_ROWID.
SQLT_RSET | The same as OCI_B_CURSOR.
SQLT_STR | Used with oci_bind_array_by_name() to bind arrays of STRING.
SQLT_UIN |
SQLT_VCS | Used with oci_bind_array_by_name() to bind arrays of VARCHAR.
OCI8 Descriptor Types
Constant | Description
OCI_DTYPE_FILE | This flag tells oci_new_descriptor() to initialize a new FILE descriptor.
OCI_DTYPE_LOB | This flag tells oci_new_descriptor() to initialize a new LOB descriptor.
OCI_DTYPE_ROWID | This flag tells oci_new_descriptor() to initialize a new ROWID descriptor.
OCI_D_FILE | The same as OCI_DTYPE_FILE.
OCI_D_LOB | The same as OCI_DTYPE_LOB.
OCI_D_ROWID | The same as OCI_DTYPE_ROWID.
Runtime Configuration
Examples
OCI8


Supported Datatypes

The driver supports the following types when binding parameters using oci_bind_by_name() function:
Type | Mapping
SQLT_NTY | Maps a native collection type from a PHP collection object, such as those created by oci_new_collection().
SQLT_BFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_BLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_RDD | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_NUM | Converts the PHP parameter to a 'C' long type, and binds to that value.
SQLT_RSET | Maps a native statement handle, such as those created by oci_parse() or those retrieved from other OCI queries.
SQLT_CHR and any other type | Converts the PHP parameter to a string type and binds as a string.
The following types are supported when retrieving columns from a result set:
Type | Mapping
SQLT_RSET | Creates an oci statement resource to represent the cursor.
SQLT_RDD | Creates a ROWID object.
SQLT_BLOB | Creates a LOB object.
SQLT_CLOB | Creates a LOB object.
SQLT_BFILE | Creates a LOB object.
SQLT_LNG | Bound as SQLT_CHR, returned as a string
SQLT_LBI | Bound as SQLT_BIN, returned as a string
Any other type | Bound as SQLT_CHR, returned as a string
Connection Handling
OCI8 Functions
OCI8


Examples

These examples connect as the HR user, which is the sample "Human Resources" schema supplied with the Oracle database. The account may need to be unlocked and the password reset before you can use it.

The examples connect to the XE database on your machine. Change the connect string to your database before running the examples.

Example #1 Basic query

This shows querying and displaying results. Statements in OCI8 use a prepare-execute-fetch sequence of steps.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Prepare the statement
$stid = oci_parse($conn, 'SELECT * FROM departments');
if (!$stid) {
    $e = oci_error($conn);
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Perform the logic of the query
$r = oci_execute($stid);
if (!$r) {
    $e = oci_error($stid);
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Fetch the results of the query
print "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    print "<tr>\n";
    foreach ($row as $item) {
        print "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    print "</tr>\n";
}
print "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Inserting with bind variables

Bind variables improve performance by allowing reuse of execution contexts and caches. Bind variables improve security by preventing some kinds of SQL Injection problems.

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (mid NUMBER, myd VARCHAR2(20));

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO MYTABLE (mid, myd) VALUES(:myid, :mydata)');

$id = 60;
$data = 'Some data';

oci_bind_by_name($stid, ':myid', $id);
oci_bind_by_name($stid, ':mydata', $data);

$r = oci_execute($stid);  // executes and commits

if ($r) {
    print "One row inserted";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Inserting data into a CLOB column

For large data use binary long object (BLOB) or character long object (CLOB) types. This example uses CLOB.

<?php

// Before running, create the table:
//     CREATE TABLE MYTABLE (mykey NUMBER, myclob CLOB);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$mykey = 12343;  // arbitrary key for this example;

$sql = "INSERT INTO mytable (mykey, myclob)
        VALUES (:mykey, EMPTY_CLOB())
        RETURNING myclob INTO :myclob";

$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_NO_AUTO_COMMIT); // use OCI_DEFAULT for PHP <= 5.3.1
$clob->save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query = 'SELECT myclob FROM mytable WHERE mykey = :mykey';

$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);

print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC)) {
    $result = $row['MYCLOB']->load();
    print '<tr><td>'.$result.'</td></tr>';
}
print '</table>';

?>

Example #4 Using a PL/SQL stored function

You must bind a variable for the return value and optionally for any PL/SQL function arguments.

<?php

/*
  Before running the PHP program, create a stored function in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
  BEGIN
      RETURN p * 3;
  END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p = 8;

$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);
oci_bind_by_name($stid, ':r', $r, 40);

oci_execute($stid);

print "$r\n";   // prints 24

oci_free_statement($stid);
oci_close($conn);

?>

Example #5 Using a PL/SQL stored procedure

With stored procedures, you should bind variables for any arguments.

<?php

/*
  Before running the PHP program, create a stored procedure in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
  BEGIN
      p2 := p1 * 2;
  END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p1 = 8;

$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 Calling a PL/SQL function that returns a REF CURSOR

Each returned value from the query is a REF CURSOR that can be fetched from.

<?php
/*
  Create the PL/SQL stored function as:

  CREATE OR REPLACE FUNCTION myfunc(p1 IN NUMBER) RETURN SYS_REFCURSOR AS
      rc SYS_REFCURSOR;
  BEGIN
      OPEN rc FOR SELECT city FROM locations WHERE ROWNUM < p1;
      RETURN rc;
  END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT myfunc(5) AS mfrc FROM dual');
oci_execute($stid);

echo "<table border='1'>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
    echo "<tr>\n";
    $rc = $row['MFRC'];
    oci_execute($rc);  // returned column value from the query is a ref cursor
    while (($rc_row = oci_fetch_array($rc, OCI_ASSOC))) {
        echo "    <td>" . $rc_row['CITY'] . "</td>\n";
    }
    oci_free_statement($rc);
    echo "</tr>\n";
}
echo "</table>\n";

// Output is:
//   Beijing
//   Bern
//   Bombay
//   Geneva

oci_free_statement($stid);
oci_close($conn);

?>
Predefined Constants
Connection Handling
OCI8


Installation

Configuring PHP with OCI8

Review the previous Requirements section before configuring OCI8.

To enable the OCI8 extension, configure PHP with the option --with-oci8.

Before starting the web server, OCI8 typically requires several Oracle environment variables (see below) to locate libraries, point to configuration files, and set some basic properties such as the character set used by Oracle libraries. The variables should be set before any PHP process starts.

PHP should be run with the same, or more recent, major version of Oracle libraries as it was configured with. For example, if you build OCI8 with Oracle 11.2 libraries, then PHP should also be deployed and run with Oracle 11.2 libraries.

Installing OCI8 as a Shared Extension

The configuration shared option builds OCI8 as a shared library that can be dynamically loaded into PHP. Building a shared extension allows OCI8 to be upgraded easily without impacting the rest of PHP.

Configure OCI8 using one of the the following configure options.

  • If using Oracle Instant Client, then do:

    ./configure --with-oci8=shared,instantclient,/path/to/instant/client/lib

    If Instant Client is installed from ZIP files, make sure to create the library symbolic link, for example ln -s libclntsh.so.11.1 libclntsh.so.

    If using an RPM-based installation of Oracle Instant Client, the configure line will look like this:

    ./configure --with-oci8=shared,instantclient,/usr/lib/oracle/<version>/client/lib

    For example, --with-oci8=shared,instantclient,/usr/lib/oracle/11.2/client/lib.

    Note that Oracle Instant Client support first appeared in PHP 4.3.11 and 5.0.4 and originally used the option --with-oci8-instant-client to configure PHP.

  • If using an Oracle database or full Oracle Client installation then do:

    ./configure --with-oci8=shared,$ORACLE_HOME

    Make sure the web server user (nobody, www) has access to the libraries, initialization files and tnsnames.ora (if used) under the $ORACLE_HOME directory. With Oracle 10gR2, you may need to run the $ORACLE_HOME/install/changePerm.sh utility to give directory access.

After configuration, follow the usual PHP building procedure, e.g. make install. The OCI8 shared extension oci8.so library will be created. It may need to be manually moved to the PHP extension directory, specified by the extension_dir option in your php.ini file.

To complete installation of OCI8, edit php.ini and add the line:

extension=oci8.so

Installing OCI8 as a Statically Compiled Extension

Configure OCI8 using one of the the following configure options.

  • If using Oracle Instant Client, then do:

    ./configure --with-oci8=instantclient,/path/to/instant/client/lib

  • If using an Oracle database or full Oracle Client installation then do:

    ./configure --with-oci8=$ORACLE_HOME

After configuration, follow the usual PHP building procedure, e.g. make install. After successful compilation, you do not need to add oci8.so to php.ini. No additional build steps are required.

Installing OCI8 from PECL

The OCI8 extension can be added to an existing PHP installation either automatically or manually from » http://pecl.php.net/.

For an automated install follow these steps:

  • If you are behind a firewall, set PEAR's proxy, for example:

    pear config-set http_proxy http://my-proxy.example.com:80/

  • Run

    pecl install oci8

    When prompted, enter either the value of $ORACLE_HOME, or instantclient,/path/to/instant/client/lib.

    Note: Do not enter the variable $ORACLE_HOME because it will not be expanded. Instead, enter the actual path of the Oracle home directory.

For a manual install, download the PECL OCI8 package, e.g. oci8-1.3.5.tgz.

  • Extract the package:

    tar -zxf oci8-1.3.5.tgz
cd oci8-1.3.5

  • Prepare the package:

    phpize

  • Configure the package, either using $ORACLE_HOME or Instant Client

    ./configure -with-oci8=shared,$ORACLE_HOME

    or

    ./configure -with-oci8=shared,instantclient,/path/to/instant/client/lib

  • Install the package:

    make install

After either an automatic or manual install, edit your php.ini file and add the line:

extension=oci8.so

Make sure the php.ini directive extension_dir is set to the directory that oci8.so was installed in.

Installing OCI8 on Windows

On Windows, uncomment the php.ini line extension=php_oci8.dll when using Oracle 10gR2 client libraries. Uncomment extension=php_oci8_11g.dll when using Oracle 11g client libraries. These two DLLs contain equivalent functionality and only one may be enabled at a time. Make sure extension_dir is set to the directory containing the PHP extension DLLs.

If using Instant Client, set the system PATH environment variable to the Oracle library directory.

Setting the Oracle Environment

Before using this extension, make sure that the Oracle environment variables are properly set for the web daemon user. If your web server is automatically started at boot time then make sure that the boot-time environment is also configured correctly.

Note: Do not set Oracle environment variables using putenv() in a PHP script because Oracle libraries may be loaded and initialized before your script runs. Variables set with putenv() may then cause conflicts, crashes, or unpredictable behavior. Some functions may work but others might give subtle errors. The variables should be set up before the web server is started.

On Red Hat Linux and variants, export variables at the end of /etc/sysconfig/httpd. Other systems with Apache 2 may use an envvars script in the Apache bin directory. A third option, the Apache SetEnv directive in httpd.conf, may work in some systems but is known to be insufficient in others.

To check that environment variables are set correctly, use phpinfo() and check the Environment (not the Apache Environment) section contains the expected variables.

The variables that might be needed are included in the following table. Refer to the Oracle documentation for more information on all the variables.

Common Oracle Environment Variables
Name | Purpose
ORACLE_HOME | Contains the directory of the full Oracle Database software. Do not set this when using Oracle Instant Client as it is unnecessary and may cause installation problems.
ORACLE_SID | Contains the name of the database on the local machine to be connected to. There is no need to set this if you using Oracle Instant Client, or always pass the connection parameter to oci_connect().
LD_LIBRARY_PATH | Set this (or its platform equivalent, such as DYLD_LIBRARY_PATH, LIBPATH, or SHLIB_PATH) to the location of the Oracle libraries, for example $ORACLE_HOME/lib or /usr/lib/oracle/11.1/client/lib. This variable is not needed if the libraries are located by a different search mechanism, such as with ldconfig or with LD_PRELOAD.
NLS_LANG | This is the primary variable for setting the character set and globalization information used by the Oracle libraries.
ORA_SDTZ | Sets the Oracle session timezone.
TNS_ADMIN | Contains the directory where the Oracle Net Services configuration files such as tnsnames.ora and sqlnet.ora are kept. Not needed if the oci_connect() connection string uses the Easy Connect naming syntax such as localhost/XE. Not needed if the network configuration files are in one of the default locations such as $ORACLE_HOME/network/admin or /etc.

Less frequently used Oracle environment variables include TWO_TASK, ORA_TZFILE, and the various Oracle globalization settings like NLS* and the ORA_NLS_* variables.

Troubleshooting

The most common problem with installing OCI8 is not having the Oracle environment correctly set. This typically appears as a problem using oci_connect() or oci_pconnect(). The error may be a PHP error such as Call to undefined function oci_connect(), an Oracle error such as ORA-12705, or even an Apache crash. Check the Apache log files for startup errors and see the sections above to resolve this problem.

While network errors like ORA-12154 or ORA-12514 indicate an Oracle network naming or configuration issue, the root cause may be because the PHP environment is incorrectly set up and Oracle libraries are unable to locate the tnsnames.ora configuration file.

On Windows, having multiple versions of Oracle on the one machine can easily cause library clashes unless care is taken to make sure PHP only uses the correct version of Oracle.

A utility to examine what libraries are being looked for and loaded can help resolve missing or clashing library issues, particularly on Windows.

Note: If the web server doesn't start or crashes at startup
Check that Apache is linked with the pthread library:

# ldd /www/apache/bin/httpd
  libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000)
  libm.so.6 => /lib/libm.so.6 (0x4002f000)
  libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000)
  libdl.so.2 => /lib/libdl.so.2 (0x4007a000)
  libc.so.6 => /lib/libc.so.6 (0x4007e000)
  /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

If the libpthread is not listed, then reinstall Apache:

# cd /usr/src/apache_1.3.xx
# make clean
# LIBS=-lpthread ./config.status
# make
# make install

Please note that on some systems like UnixWare, it is libthread instead of libpthread. PHP and Apache have to be configured with EXTRA_LIBS=-lthread.

Requirements
Testing
Installing/Configuring


Requirements

The OCI8 extension requires Oracle 9iR2, 10g or 11g Client libraries. If the Oracle Database is on the same machine as PHP, the database software already contains the necessary libraries. When PHP is on a different machine, use the free » Oracle Instant Client libraries.

To use Oracle Instant Client, install the basic or basiclite Oracle Instant Client ZIP file or RPM package. When building PHP from source code, also install the sdk ZIP file or devel RPM package.

On Windows, OCI8 needs client libraries from version 10gR2 or greater. With some versions of Instant Client you may additionally need mfc71.dll and msvcr71.dll libraries.

You should run PHP with the same, or more recent, version of the Oracle libraries that OCI8 was built with.

Note: If OCI8 uses 9iR2 or 10g client libraries, then PHP can connect to Oracle Database 8i, 9iR2, 10g or 11g. If OCI8 uses 11g client libraries, the database can be 9iR2, 10g or 11g.

Note: Full OCI8 feature support is only available when using the most recent versions of the client libraries and database.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Testing
  • Runtime Configuration
Introduction
Requirements
OCI8


Testing

The OCI8 test suite is in ext/oci8/tests. After OCI8 tests are run this directory will also contain logs of any failures.

Before running PHP's tests, edit details.inc and set $user, $password and the $dbase connection string. The OCI8 test suite has been developed using the SYSTEM account. Some tests will fail if the test user does not have equivalent permissions.

If the database is on the same machine as PHP, set $oracle_on_localhost to TRUE.

If Oracle 11g Database Resident Connection Pooling is being tested, set $test_drcp to TRUE and ensure the connection string uses an appropriate DRCP pooled server.

An alternative to editing details.inc is the set environment variables, for example:

    $ export PHP_OCI8_TEST_USER=system
    $ export PHP_OCI8_TEST_PASS=oracle
    $ export PHP_OCI8_TEST_DB=localhost/XE
    $ export PHP_OCI8_TEST_DB_ON_LOCALHOST=TRUE
    $ export PHP_OCI8_TEST_DRCP=FALSE

Note in some shells these variables are not propagated correctly to the PHP process and tests will fail to connect if this method is used.

Next, set any necessary environment for the Oracle database. With Oracle 10g XE do:

    $ . /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/oracle_env.sh

For other versions of the Oracle database do:

    $ . /usr/local/bin/oraenv

Some shells require that php.ini has E in the variables_order parameter, for example:

    variables_order = "EGPCS"

Run all the PHP tests with:

    $ cd your_php_src_directory
    $ make test

or run only the OCI8 tests with

    $ cd your_php_src_directory
    $ make test TESTS=ext/oci8

When the tests have completed, review any test failures. On slow systems, some tests may take longer than the default test timeout in run-tests.php. To correct this, set the environment variable TEST_TIMEOUT to a larger number of seconds.

On fast machines with a local database configured for light load (e.g. Oracle 10g XE) some tests might fail with ORA-12516 or ORA-12520 errors. To prevent this, increase the database PROCESSES parameter using the following steps:

Connect as the oracle software owner:

    $ su - oracle

Set the necessary Oracle environment with oracle_env.sh or oraenv, as described above.

Start the SQL*Plus command line tool and increase PROCESSES

    $ sqlplus / as sysdba
    SQL> alter system set processes=100 scope=spfile

Restart the database:

    SQL> startup force

Installation
Runtime Configuration
Installing/Configuring


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Unified ODBC Configuration Options
Name | Default | Changeable | Changelog
odbc.default_db * | NULL | PHP_INI_ALL |
odbc.default_user * | NULL | PHP_INI_ALL |
odbc.default_pw * | NULL | PHP_INI_ALL |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.default_cursortype | "3" | PHP_INI_ALL | Available as of PHP 5.3.0

Note: Entries marked with * are not implemented yet.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

odbc.default_db string

ODBC data source to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.default_user string

User name to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.default_pw string

Password to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.allow_persistent boolean

Whether to allow persistent ODBC connections.

odbc.check_persistent boolean

Check that a connection is still valid before reuse.

odbc.max_persistent integer

The maximum number of persistent ODBC connections per process.

odbc.max_links integer

The maximum number of ODBC connections per process, including persistent connections.

odbc.defaultlrl integer

Handling of LONG fields. Specifies the number of bytes returned to variables.

When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
odbc.defaultbinmode integer

Handling of binary data.

odbc.default_cursortype integer

Controls the ODBC cursor model. Possible values are SQL_CURSOR_FORWARD_ONLY, SQL_CURSOR_KEYSET_DRIVEN, SQL_CURSOR_DYNAMIC and SQL_CURSOR_STATIC (default).

Installation
Resource Types
Installing/Configuring


Installation

--with-adabas[=DIR]

Include Adabas D support. DIR is the Adabas base install directory, defaults to /usr/local.

--with-sapdb[=DIR]

Include SAP DB support. DIR is SAP DB base install directory, defaults to /usr/local.

--with-solid[=DIR]

Include Solid support. DIR is the Solid base install directory, defaults to /usr/local/solid.

--with-ibm-db2[=DIR]

Include IBM DB2 support. DIR is the DB2 base install directory, defaults to /home/db2inst1/sqllib.

--with-empress[=DIR]

Include Empress support. DIR is the Empress base install directory, defaults to $EMPRESSPATH. From PHP 4, this option only supports Empress Version 8.60 and above.

--with-empress-bcs[=DIR]

Include "Empress Local Access" support. DIR is the Empress base install directory, defaults to $EMPRESSPATH. From PHP 4, this option only supports Empress Version 8.60 and above.

--with-birdstep[=DIR]

Include Birdstep support. DIR is the Birdstep base install directory, defaults to /usr/local/birdstep.

--with-custom-odbc[=DIR]

Include a user defined ODBC support. The DIR is ODBC install base directory, which defaults to /usr/local. Make sure to define CUSTOM_ODBC_LIBS and have some odbc.h in your include dirs. E.g., you should define following for Sybase SQL Anywhere 5.5.00 on QNX, prior to run configure script:

   CPPFLAGS="-DODBC_QNX -DSQLANY_BUG"
   LDFLAGS=-lunix
   CUSTOM_ODBC_LIBS="-ldblib -lodbc".

--with-iodbc[=DIR]

Include iODBC support. DIR is the iODBC base install directory, defaults to /usr/local.

--with-esoob[=DIR]

Include Easysoft OOB support. DIR is the OOB base install directory, defaults to /usr/local/easysoft/oob/client.

--with-unixODBC[=DIR]

Include unixODBC support. DIR is the unixODBC base install directory, defaults to /usr/local.

--with-openlink[=DIR]

Include OpenLink ODBC support. DIR is the OpenLink base install directory, defaults to /usr/local. This is the same as iODBC.

--with-dbmaker[=DIR]

Include DBMaker support. DIR is the DBMaker base install directory, defaults to where the latest version of DBMaker is installed (such as /home/dbmaker/3.6).

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

OGG/Vorbis supports PCM encodings in the following formats
Constant | Definition
OGGVORBIS_PCM_U8 | Unsigned 8-bit PCM.
OGGVORBIS_PCM_S8 | Signed 8-bit PCM.
OGGVORBIS_PCM_U16_LE | Unsigned 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_U16_BE | Unsigned 16-bit PCM. Big Endian byte order.
OGGVORBIS_PCM_S16_LE | Signed 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_S16_BE | Signed 16-bit PCM. Big Endian byte order.
Resource Types
Context options
oggvorbis


Context options

OGG/Vorbis tuning options
Option | Definition | Relevance | Default
pcm_mode | PCM byte encoding used. See constants below. | Read / Write | OGGVORBIS_PCM_S16_LE
rate | PCM Sampling rate. Measured in Hz. | Write only | 44100
bitrate | Vorbis Average Bitrate Encoding / Variable Bitrate Encoding. Measured in bps (ABR) or Quality level (VBR: 0.0 to 1.0). 128000 ABR is rough equal to 0.4 VBR. | Write only | 128000
channels | Number of PCM channels. 1 == Mono, 2 == Stereo. | Write only | 2
serialno | Serial Number of stream within file. Must be unique within file. Because of the potential to select a duplicate serial number within a chained file, make efforts to manually assign unique numbers when encoding. | Write only | Random
comments | Associative array of file comments. Will be translated to strtoupper($name) . "=$value". Note: This context option is not available in oggvorbis-0.1 | Write only | array('ENCODER' => 'PHP/OggVorbis, http://pear.php.net/oggvorbis')
Predefined Constants
Examples
oggvorbis


Examples

Table of Contents

  • Examples on using the ogg:// wrapper.
Context options
Examples on using the ogg:// wrapper.
oggvorbis


Examples on using the ogg:// wrapper.

Example #1 Reading an OGG/Vorbis file

<?php
dl("oggvorbis.so");

/* By default, ogg:// will decode to Signed 16-bit Little Endian */
$fp = fopen('ogg://myaudio.ogg', 'r');

/* Collect some information about the file. */
$metadata = stream_get_meta_data($fp);

/* Inspect the first song (usually the only song,
   but OGG/Vorbis files may be chained) */
$songdata = $metadata['wrapper_data'][0];

echo "OGG/Vorbis file encoded by: {$songdata['vendor']}\n.";
echo "  {$songdata['channels']} channels of {$songdata['rate']}Hz sampling encoded at {$songdata['bitrate_nominal']}bps.\n";
foreach($songdata['comments'] as $comment) {
    echo "  $comment\n";
}

while ($audio_data = fread($fp, 8192)) {
  /* Do something with the PCM audio we're extracting from the OGG.
     Copying to /dev/dsp is a good target on linux systems,
     just remember to setup the device for your sampling mode first. */
}

fclose($fp);

?>

Example #2 Encode an audio file to OGG/Vorbis

<?php
dl('oggvorbis.so');

$context = stream_context_create(array('ogg'=>array(
             'pcm_mode' => OGGVORBIS_PCM_S8,  /* Signed 8bit audio */
             'rate' => 44100,                 /* 44kHz CD quality */
             'bitrate' => 0.5,                /* Midquality VBR */
             'channels' => 1,                 /* Mono */
             'serialno' => 12345)));          /* Unique within our stream */

/* Open file for appending.  This will "chain" a second OGG stream at the end of the first. */
$ogg = fopen('ogg://mysong.ogg', 'a', false, $context);

$pcm = fopen('mysample.pcm', 'r');

/* Compress the raw PCM audio from mysample.pcm into mysong.ogg */
stream_copy_to_stream($pcm, $ogg);

fclose($pcm);
fclose($ogg);
?>

Examples
OpenAL
Examples


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/oggvorbis

Requirements
Runtime Configuration
Installing/Configuring


Requirements

This extension requires PHP >= 4.3.0, » libogg >= 1.0, and » libvorbis >= 1.0.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
oggvorbis


OCI8 Obsolete Aliases and Functions

Table of Contents

  • ocibindbyname — Alias of oci_bind_by_name
  • ocicancel — Alias of oci_cancel
  • ocicloselob — Alias of
  • ocicollappend — Alias of
  • ocicollassign — Alias of
  • ocicollassignelem — Alias of
  • ocicollgetelem — Alias of
  • ocicollmax — Alias of
  • ocicollsize — Alias of
  • ocicolltrim — Alias of
  • ocicolumnisnull — Alias of oci_field_is_null
  • ocicolumnname — Alias of oci_field_name
  • ocicolumnprecision — Alias of oci_field_precision
  • ocicolumnscale — Alias of oci_field_scale
  • ocicolumnsize — Alias of oci_field_size
  • ocicolumntype — Alias of oci_field_type
  • ocicolumntyperaw — Alias of oci_field_type_raw
  • ocicommit — Alias of oci_commit
  • ocidefinebyname — Alias of oci_define_by_name
  • ocierror — Alias of oci_error
  • ociexecute — Alias of oci_execute
  • ocifetch — Alias of oci_fetch
  • ocifetchinto — Fetches the next row into an array (deprecated)
  • ocifetchstatement — Alias of oci_fetch_all
  • ocifreecollection — Alias of
  • ocifreecursor — Alias of oci_free_statement
  • ocifreedesc — Alias of
  • ocifreestatement — Alias of oci_free_statement
  • ociinternaldebug — Alias of oci_internal_debug
  • ociloadlob — Alias of
  • ocilogoff — Alias of oci_close
  • ocilogon — Alias of oci_connect
  • ocinewcollection — Alias of oci_new_collection
  • ocinewcursor — Alias of oci_new_cursor
  • ocinewdescriptor — Alias of oci_new_descriptor
  • ocinlogon — Alias of oci_new_connect
  • ocinumcols — Alias of oci_num_fields
  • ociparse — Alias of oci_parse
  • ociplogon — Alias of oci_pconnect
  • ociresult — Alias of oci_result
  • ocirollback — Alias of oci_rollback
  • ocirowcount — Alias of oci_num_rows
  • ocisavelob — Alias of
  • ocisavelobfile — Alias of
  • ociserverversion — Alias of oci_server_version
  • ocisetprefetch — Alias of oci_set_prefetch
  • ocistatementtype — Alias of oci_statement_type
  • ociwritelobtofile — Alias of
  • ociwritetemporarylob — Alias of
oci_statement_type
ocibindbyname
OCI8


Introduction

Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model.

Among the features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting.

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References

Tip

See also the Userland Naming Guide.

Classes and Objects
The Basics
Classes and Objects


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

ALC_FREQUENCY (integer)
Context Attribute
ALC_REFRESH (integer)
Context Attribute
ALC_SYNC (integer)
Context Attribute
AL_FREQUENCY (integer)
Buffer Setting
AL_BITS (integer)
Buffer Setting
AL_CHANNELS (integer)
Buffer Setting
AL_SIZE (integer)
Buffer Setting
AL_BUFFER (integer)
Source/Listener Setting (Integer)
AL_SOURCE_RELATIVE (integer)
Source/Listener Setting (Integer)
AL_SOURCE_STATE (integer)
Source/Listener Setting (Integer)
AL_PITCH (integer)
Source/Listener Setting (Float)
AL_GAIN (integer)
Source/Listener Setting (Float)
AL_MIN_GAIN (integer)
Source/Listener Setting (Float)
AL_MAX_GAIN (integer)
Source/Listener Setting (Float)
AL_MAX_DISTANCE (integer)
Source/Listener Setting (Float)
AL_ROLLOFF_FACTOR (integer)
Source/Listener Setting (Float)
AL_CONE_OUTER_GAIN (integer)
Source/Listener Setting (Float)
AL_CONE_INNER_ANGLE (integer)
Source/Listener Setting (Float)
AL_CONE_OUTER_ANGLE (integer)
Source/Listener Setting (Float)
AL_REFERENCE_DISTANCE (integer)
Source/Listener Setting (Float)
AL_POSITION (integer)
Source/Listener Setting (Float Vector)
AL_VELOCITY (integer)
Source/Listener Setting (Float Vector)
AL_DIRECTION (integer)
Source/Listener Setting (Float Vector)
AL_ORIENTATION (integer)
Source/Listener Setting (Float Vector)
AL_FORMAT_MONO8 (integer)
PCM Format
AL_FORMAT_MONO16 (integer)
PCM Format
AL_FORMAT_STEREO8 (integer)
PCM Format
AL_FORMAT_STEREO16 (integer)
PCM Format
AL_INITIAL (integer)
Source State
AL_PLAYING (integer)
Source State
AL_PAUSED (integer)
Source State
AL_STOPPED (integer)
Source State
AL_LOOPING (integer)
Source State
AL_TRUE (integer)
Boolean value recognized by OpenAL
AL_FALSE (integer)
Boolean value recognized by OpenAL
Resource Types
OpenAL Functions
OpenAL


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/openal.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Resource Types

This extension defines four resource types:
Open AL(Device) - Returned by openal_device_open(),
Open AL(Context) - Returned by openal_context_create(),
Open AL(Buffer) - Returned by openal_buffer_create(),
and Open AL(Source) - Returned by openal_source_create().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
OpenAL


Certificate Verification

When calling a function that will verify a signature/certificate, the cainfo parameter is an array containing file and directory names that specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.

Key/Certificate parameters
OpenSSL Functions
OpenSSL


Key/Certificate parameters

Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx() functions. Later versions may use one of the following methods:

  • Certificates

    1. An X.509 resource returned from openssl_x509_read()
    2. A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate
    3. A string containing the content of a certificate, PEM encoded

  • Public/Private Keys

    1. A key resource returned from openssl_get_publickey() or openssl_get_privatekey()
    2. For public keys only: an X.509 resource
    3. A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)
    4. A string containing the content of a certificate/key, PEM encoded
    5. For private keys, you may also use the syntax array($key, $passphrase) where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key

Server Name Indication constants
Certificate Verification
OpenSSL


Ciphers

OPENSSL_CIPHER_RC2_40 (integer)
OPENSSL_CIPHER_RC2_128 (integer)
OPENSSL_CIPHER_RC2_64 (integer)
OPENSSL_CIPHER_DES (integer)
OPENSSL_CIPHER_3DES (integer)

Note: These constants were added in 4.3.0.

Signature Algorithms
Version constants
Predefined Constants


Predefined Constants

Table of Contents

  • Purpose checking flags
  • Padding flags
  • Key types
  • PKCS7 Flags/Constants
  • Signature Algorithms
  • Ciphers
  • Version constants
  • Server Name Indication constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Resource Types
Purpose checking flags
OpenSSL


Server Name Indication constants

OPENSSL_TLSEXT_SERVER_NAME (string)
Whether SNI support is available or not.

Note: This constant were added in 5.3.2 and requires PHP to be built with OpenSSL 0.9.8j or greater.

Version constants
Key/Certificate parameters
Predefined Constants


Version constants

OPENSSL_VERSION_TEXT (string)
OPENSSL_VERSION_NUMBER (integer)

Note: These constants were added in 5.2.0.

Ciphers
Server Name Indication constants
Predefined Constants


Installation

To use PHP's OpenSSL support you must also compile PHP --with-openssl[=DIR].

Note: Note to Win32 Users
In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libeay32.dll
Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf file on your system. As of PHP 4.3.0, we include a sample configuration file in our win32 binary distributions. PHP 4.3.x and 4.4.x has the file in the openssl directory. PHP 5.x and 6.x has the file in the extras/openssl directory. If you are either using PHP 4.2.x or missing the file, you can obtain it from » the OpenSSL binaries page or by downloading a recent PHP release. Be aware that Windows Explorer hides the .cnf extension by default and says the file Type is SpeedDial.
PHP will search for the openssl.cnf using the following logic:

  • the OPENSSL_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.
  • the SSLEAY_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.
  • The file openssl.cnf will be assumed to be found in the default certificate area, as configured at the time that the openssl DLL was compiled. This is usually means that the default filename is c:\usr\local\ssl\openssl.cnf.

In your installation, you need to decide whether to install the configuration file at c:\usr\local\ssl\openssl.cnf or whether to install it someplace else and use environmental variables (possibly on a per-virtual-host basis) to locate the configuration file. Note that it is possible to override the default path from the script using the configargs of the functions that require a configuration file.

Requirements
Runtime Configuration
Installing/Configuring


Key types

OPENSSL_KEYTYPE_RSA (integer)
OPENSSL_KEYTYPE_DSA (integer)
OPENSSL_KEYTYPE_DH (integer)
Padding flags
PKCS7 Flags/Constants
Predefined Constants


Padding flags

OPENSSL_PKCS1_PADDING (integer)
OPENSSL_SSLV23_PADDING (integer)
OPENSSL_NO_PADDING (integer)
OPENSSL_PKCS1_OAEP_PADDING (integer)
Purpose checking flags
Key types
Predefined Constants


PKCS7 Flags/Constants

The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:

PKCS7 CONSTANTS
Constant | Description
PKCS7_TEXT | Adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur.
PKCS7_BINARY | Normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this option is present, no translation occurs. This is useful when handling binary data which may not be in MIME format.
PKCS7_NOINTERN | When verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however.
PKCS7_NOVERIFY | Do not verify the signers certificate of a signed message.
PKCS7_NOCHAIN | Do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs.
PKCS7_NOCERTS | When signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify() for example).
PKCS7_NOATTR | Normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included.
PKCS7_DETACHED | When signing a message, use cleartext signing with the MIME type "multipart/signed". This is the default if you do not specify any flags to openssl_pkcs7_sign(). If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME.
PKCS7_NOSIGS | Don't try and verify the signatures on a message

Note: These constants were added in 4.0.6.

Key types
Signature Algorithms
Predefined Constants


Purpose checking flags

X509_PURPOSE_SSL_CLIENT (integer)
X509_PURPOSE_SSL_SERVER (integer)
X509_PURPOSE_NS_SSL_SERVER (integer)
X509_PURPOSE_SMIME_SIGN (integer)
X509_PURPOSE_SMIME_ENCRYPT (integer)
X509_PURPOSE_CRL_SIGN (integer)
X509_PURPOSE_ANY (integer)
Predefined Constants
Padding flags
Predefined Constants


Requirements

In order to use the OpenSSL functions you need to install the » OpenSSL package. PHP between versions 4.0.5 and 4.3.1 will work with OpenSSL >= 0.9.5. Other versions (PHP <=4.0.4 and >= 4.3.2) require OpenSSL >= 0.9.6.

Warning

You are strongly encouraged to use the most recent OpenSSL version, otherwise your web server could be vulnerable to attack.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
OpenSSL


Signature Algorithms

OPENSSL_ALGO_DSS1 (integer)
OPENSSL_ALGO_SHA1 (integer)
Used as default algorithm by openssl_sign() and openssl_verify().
OPENSSL_ALGO_MD5 (integer)
OPENSSL_ALGO_MD4 (integer)
OPENSSL_ALGO_MD2 (integer)

Note: These constants were added in 5.0.0.

PKCS7 Flags/Constants
Ciphers
Predefined Constants


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Output Control configuration options
Name | Default | Changeable | Changelog
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR | Available since PHP 4.0.4.
implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 4.2.3.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

output_buffering boolean/integer

You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096). As of PHP 4.3.5, this directive is always Off in PHP-CLI.

output_handler string

You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.

Note:

      You cannot use both mb_output_handler() with
      ob_iconv_handler() and you cannot use both
      ob_gzhandler() and
      zlib.output_compression.

Note: Only built-in functions can be used with this directive. For user defined functions, use ob_start().

implicit_flush boolean

FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.

When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.

See also ob_implicit_flush().

Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
Output Control


Examples
Output Control
PHP Manual

Examples

Table of Contents

  • Examples
Predefined Constants
Examples
Output Control


Examples
Output Control Functions
Examples
PHP Manual

Examples

Example #1 Output Control example

<?php

ob_start();
echo "Hello\n";

setcookie("cookiename", "cookiedata");

ob_end_flush();

?>

In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)

Examples
Output Control Functions
Examples
PHP Manual


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Output Control


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
Object overloading


Examples

Table of Contents

  • Overloading a PHP class
Predefined Constants
Overloading a PHP class
Object overloading


Overloading a PHP class

Examples
Object overloading Functions
Examples
PHP Manual

Some simple examples on using the overload() function:

Example #1 Overloading a PHP class

<?php

class OO {
   var $a = 111;
   var $elem = array('b' => 9, 'c' => 42);

   // Callback method for getting a property
   function __get($prop_name, &$prop_value)
   {
       if (isset($this->elem[$prop_name])) {
           $prop_value = $this->elem[$prop_name];
           return true;
       } else {
           return false;
       }
   }

   // Callback method for setting a property
   function __set($prop_name, $prop_value)
   {
       $this->elem[$prop_name] = $prop_value;
       return true;
   }
}

// Here we overload the OO object
overload('OO');

$o = new OO;
echo "\$o->a: $o->a\n"; // print: $o->a: 111
echo "\$o->b: $o->b\n"; // print: $o->b: 9
echo "\$o->c: $o->c\n"; // print: $o->c: 42
echo "\$o->d: $o->d\n"; // print: $o->d:

// add a new item to the $elem array in OO
$o->x = 56;

// instantiate stdclass (it is built-in in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val->prop = 555;

// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o->a = array($val);
var_dump($o->a[0]->prop);

?>

Examples
Object overloading Functions
Examples


Installation

In order to use these functions, you must compile PHP with the --enable-overload option. Starting with PHP 4.3.0 this extension is enabled by default. You can disable overload support with --disable--overload.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

Note: Builtin support for overload is available with PHP 4.3.0.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Object overloading


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
Ovrimos SQL


Examples

Table of Contents

  • Connect to Ovrimos SQL Server and select from a system table
Predefined Constants
Connect to Ovrimos SQL Server and select from a system table
Ovrimos SQL


Connect to Ovrimos SQL Server and select from a system table

Examples
Ovrimos SQL Functions
Examples
PHP Manual

Example #1 Connect to Ovrimos SQL Server and select from a system table

<?php
$conn = ovrimos_connect("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

Examples
Ovrimos SQL Functions
Examples


Installation

To enable Ovrimos support in PHP just compile PHP with the --with-ovrimos[=DIR] parameter to your configure line. DIR is the Ovrimos' libsqlcli install directory.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You'll need to install the sqlcli library available in the Ovrimos SQL Server distribution.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Ovrimos SQL


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The following two tables lists all constants defined by the paradox extension.

Contants for field types
Name | Meaning
PX_FIELD_ALPHA | Character data with fixed length
PX_FIELD_DATE | Date, number of days since 1.1.0000
PX_FIELD_SHORT | Short integer (2 Bytes)
PX_FIELD_LONG | Long integer (4 Bytes)
PX_FIELD_CURRENCY | same as PX_FIELD_NUMBER
PX_FIELD_NUMBER | Double
PX_FIELD_LOGICAL | Boolean
PX_FIELD_MEMOBLOB | Binary large object
PX_FIELD_BLOB | Binary large object (not supported)
PX_FIELD_FMTMEMOBLOB | Binary large object
PX_FIELD_OLE | OLE object (basically a blob, not supported)
PX_FIELD_GRAPHIC | Graphic (basically a blob, not supported)
PX_FIELD_TIME | time, number of milli seconds since midnight
PX_FIELD_TIMESTAMP | timestamp, number of milli seconds since 1.1.0000
PX_FIELD_AUTOINC | Auto incrementing interger (like PX_FIELD_LONG)
PX_FIELD_BCD | Decimal number stored in bcd format (not supported)
PX_FIELD_BYTES | Array of Bytes with not more than 255 bytes (not supported)
PX_KEYTOLOWER | Turn all field names into lower case
PX_KEYTOUPPER | Turn all field names into upper case

Contants for file types
Name | Meaning
PX_FILE_INDEX_DB | Indexed database
PX_FILE_PRIM_INDEX | Primary index
PX_FILE_NON_INDEX_DB | None indexed database
PX_FILE_NON_INC_SEC_INDEX | None incremental secondary index
PX_FILE_SEC_INDEX | Secondary index
PX_FILE_INC_SEC_INDEX | Incremental secondary index
PX_FILE_NON_INC_SEC_INDEX_G | Non incremental secondary index
PX_FILE_SEC_INDEX_G | Secondary index
PX_FILE_INC_SEC_INDEX_G | Non incremental secondary index

Resource Types
Paradox Functions
Paradox


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/paradox

Make sure you have pxlib installed before. If you install pxlib from an rpm or debian package, do not forget to install the development package as well.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You need at least PHP 5.0.0 and pxlib >= 0.4.4 for the basic set of functions. Some newer functions are only available with pxlib >= 0.6.0. Reading and writing of encrypted databases requires at least pxlib >= 0.5.0. The paradox library (pxlib) is available at » http://pxlib.sourceforge.net.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

px_new() creates a new Paradox object required by all Paradox functions.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Paradox


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

PARSEKIT_QUIET (int)
Return full detail, but without unnecessary NULL entries.
PARSEKIT_SIMPLE (int)
Return shorthand opcode notation.
PARSEKIT_EXTENDED_VALUE (int)
Opnode Flag
PARSEKIT_RESULT_CONST (int)
Opnode Flag
PARSEKIT_RESULT_EA_TYPE (int)
Opnode Flag
PARSEKIT_RESULT_JMP_ADDR (int)
Opnode Flag
PARSEKIT_RESULT_OPARRAY (int)
Opnode Flag
PARSEKIT_RESULT_OPLINE (int)
Opnode Flag
PARSEKIT_RESULT_VAR (int)
Opnode Flag
PARSEKIT_USAGE_UNKNOWN (int)
Opnode Flag
PARSEKIT_ZEND_INTERNAL_CLASS (int)
Class Type
PARSEKIT_ZEND_USER_CLASS (int)
Class Type
PARSEKIT_ZEND_EVAL_CODE (int)
Function Type
PARSEKIT_ZEND_INTERNAL_FUNCTION (int)
Function Type
PARSEKIT_ZEND_OVERLOADED_FUNCTION (int)
Function Type
PARSEKIT_ZEND_OVERLOADED_FUNCTION_TEMPORARY (int) PHP >= 5.0.0
Function Type
PARSEKIT_ZEND_USER_FUNCTION (int)
Function Type
PARSEKIT_IS_CONST (int)
Node Type
PARSEKIT_IS_TMP_VAR (int)
Node Type
PARSEKIT_IS_UNUSED (int)
Node Type
PARSEKIT_IS_VAR (int)
Node Type
PARSEKIT_ZEND_ADD (int)
Opcode
PARSEKIT_ZEND_ADD_ARRAY_ELEMENT (int)
Opcode
PARSEKIT_ZEND_ADD_CHAR (int)
Opcode
PARSEKIT_ZEND_ADD_INTERFACE (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ADD_STRING (int)
Opcode
PARSEKIT_ZEND_ADD_VAR (int)
Opcode
PARSEKIT_ZEND_ASSIGN (int)
Opcode
PARSEKIT_ZEND_ASSIGN_ADD (int)
Opcode
PARSEKIT_ZEND_ASSIGN_BW_AND (int)
Opcode
PARSEKIT_ZEND_ASSIGN_BW_OR (int)
Opcode
PARSEKIT_ZEND_ASSIGN_BW_XOR (int)
Opcode
PARSEKIT_ZEND_ASSIGN_CONCAT (int)
Opcode
PARSEKIT_ZEND_ASSIGN_DIM (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ASSIGN_DIV (int)
Opcode
PARSEKIT_ZEND_ASSIGN_MOD (int)
Opcode
PARSEKIT_ZEND_ASSIGN_MUL (int)
Opcode
PARSEKIT_ZEND_ASSIGN_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ASSIGN_REF (int)
Opcode
PARSEKIT_ZEND_ASSIGN_SL (int)
Opcode
PARSEKIT_ZEND_ASSIGN_SR (int)
Opcode
PARSEKIT_ZEND_ASSIGN_SUB (int)
Opcode
PARSEKIT_ZEND_BEGIN_SILENCE (int)
Opcode
PARSEKIT_ZEND_BOOL (int)
Opcode
PARSEKIT_ZEND_BOOL_NOT (int)
Opcode
PARSEKIT_ZEND_BOOL_XOR (int)
Opcode
PARSEKIT_ZEND_BRK (int)
Opcode
PARSEKIT_ZEND_BW_AND (int)
Opcode
PARSEKIT_ZEND_BW_NOT (int)
Opcode
PARSEKIT_ZEND_BW_OR (int)
Opcode
PARSEKIT_ZEND_BW_XOR (int)
Opcode
PARSEKIT_ZEND_CASE (int)
Opcode
PARSEKIT_ZEND_CAST (int)
Opcode
PARSEKIT_ZEND_CATCH (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_CLONE (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_CONCAT (int)
Opcode
PARSEKIT_ZEND_CONT (int)
Opcode
PARSEKIT_ZEND_DECLARE_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_DECLARE_FUNCTION (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_DECLARE_INHERITED_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_DIV (int)
Opcode
PARSEKIT_ZEND_DO_FCALL (int)
Opcode
PARSEKIT_ZEND_DO_FCALL_BY_NAME (int)
Opcode
PARSEKIT_ZEND_ECHO (int)
Opcode
PARSEKIT_ZEND_END_SILENCE (int)
Opcode
PARSEKIT_ZEND_EXIT (int)
Opcode
PARSEKIT_ZEND_EXT_FCALL_BEGIN (int)
Opcode
PARSEKIT_ZEND_EXT_FCALL_END (int)
Opcode
PARSEKIT_ZEND_EXT_NOP (int)
Opcode
PARSEKIT_ZEND_EXT_STMT (int)
Opcode
PARSEKIT_ZEND_FETCH_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_FETCH_CONSTANT (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_FUNC_ARG (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_IS (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_R (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_RW (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_TMP_VAR (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_UNSET (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_W (int)
Opcode
PARSEKIT_ZEND_FETCH_FUNC_ARG (int)
Opcode
PARSEKIT_ZEND_FETCH_IS (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_FUNC_ARG (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_IS (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_R (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_RW (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_UNSET (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_W (int)
Opcode
PARSEKIT_ZEND_FETCH_R (int)
Opcode
PARSEKIT_ZEND_FETCH_RW (int)
Opcode
PARSEKIT_ZEND_FETCH_UNSET (int)
Opcode
PARSEKIT_ZEND_FETCH_W (int)
Opcode
PARSEKIT_ZEND_FE_FETCH (int)
Opcode
PARSEKIT_ZEND_FE_RESET (int)
Opcode
PARSEKIT_ZEND_FREE (int)
Opcode
PARSEKIT_ZEND_HANDLE_EXCEPTION (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IMPORT_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IMPORT_CONST (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IMPORT_FUNCTION (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INCLUDE_OR_EVAL (int)
Opcode
PARSEKIT_ZEND_INIT_ARRAY (int)
Opcode
PARSEKIT_ZEND_INIT_CTOR_CALL (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INIT_FCALL_BY_NAME (int)
Opcode
PARSEKIT_ZEND_INIT_METHOD_CALL (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INIT_STATIC_METHOD_CALL (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INIT_STRING (int)
Opcode
PARSEKIT_ZEND_INSTANCEOF (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY (int) PHP < 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY_DIM_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY_PROP_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY_VAR (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IS_EQUAL (int)
Opcode
PARSEKIT_ZEND_IS_IDENTICAL (int)
Opcode
PARSEKIT_ZEND_IS_NOT_EQUAL (int)
Opcode
PARSEKIT_ZEND_IS_NOT_IDENTICAL (int)
Opcode
PARSEKIT_ZEND_IS_SMALLER (int)
Opcode
PARSEKIT_ZEND_IS_SMALLER_OR_EQUAL (int)
Opcode
PARSEKIT_ZEND_JMP (int)
Opcode
PARSEKIT_ZEND_JMPNZ (int)
Opcode
PARSEKIT_ZEND_JMPNZ_EX (int)
Opcode
PARSEKIT_ZEND_JMPZ (int)
Opcode
PARSEKIT_ZEND_JMPZNZ (int)
Opcode
PARSEKIT_ZEND_JMPZ_EX (int)
Opcode
PARSEKIT_ZEND_JMP_NO_CTOR (int)
Opcode
PARSEKIT_ZEND_MOD (int)
Opcode
PARSEKIT_ZEND_MUL (int)
Opcode
PARSEKIT_ZEND_NEW (int)
Opcode
PARSEKIT_ZEND_NOP (int)
Opcode
PARSEKIT_ZEND_OP_DATA (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_POST_DEC (int)
Opcode
PARSEKIT_ZEND_POST_DEC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_POST_INC (int)
Opcode
PARSEKIT_ZEND_POST_INC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_PRE_DEC (int)
Opcode
PARSEKIT_ZEND_PRE_DEC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_PRE_INC (int)
Opcode
PARSEKIT_ZEND_PRE_INC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_PRINT (int)
Opcode
PARSEKIT_ZEND_QM_ASSIGN (int)
Opcode
PARSEKIT_ZEND_RAISE_ABSTRACT_ERROR (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_RECV (int)
Opcode
PARSEKIT_ZEND_RECV_INIT (int)
Opcode
PARSEKIT_ZEND_RETURN (int)
Opcode
PARSEKIT_ZEND_SEND_REF (int)
Opcode
PARSEKIT_ZEND_SEND_VAL (int)
Opcode
PARSEKIT_ZEND_SEND_VAR (int)
Opcode
PARSEKIT_ZEND_SEND_VAR_NO_REF (int)
Opcode
PARSEKIT_ZEND_SL (int)
Opcode
PARSEKIT_ZEND_SR (int)
Opcode
PARSEKIT_ZEND_SUB (int)
Opcode
PARSEKIT_ZEND_SWITCH_FREE (int)
Opcode
PARSEKIT_ZEND_THROW (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_TICKS (int)
Opcode
PARSEKIT_ZEND_UNSET_DIM_OBJ (int)
Opcode
PARSEKIT_ZEND_UNSET_VAR (int)
Opcode
PARSEKIT_ZEND_VERIFY_ABSTRACT_CLASS (int) PHP >= 5.0.0
Opcode

Resource Types
Parsekit Functions
Parsekit


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/parsekit.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Parsekit


Predefined Constants

The following list of signals are supported by the Process Control functions. Please see your systems signal(7) man page for details of the default behavior of these signals.

WNOHANG (integer)
WUNTRACED (integer)
SIG_IGN (integer)
SIG_DFL (integer)
SIG_ERR (integer)
SIGHUP (integer)
SIGINT (integer)
SIGQUIT (integer)
SIGILL (integer)
SIGTRAP (integer)
SIGABRT (integer)
SIGIOT (integer)
SIGBUS (integer)
SIGFPE (integer)
SIGKILL (integer)
SIGUSR1 (integer)
SIGSEGV (integer)
SIGUSR2 (integer)
SIGPIPE (integer)
SIGALRM (integer)
SIGTERM (integer)
SIGSTKFLT (integer)
SIGCLD (integer)
SIGCHLD (integer)
SIGCONT (integer)
SIGSTOP (integer)
SIGTSTP (integer)
SIGTTIN (integer)
SIGTTOU (integer)
SIGURG (integer)
SIGXCPU (integer)
SIGXFSZ (integer)
SIGVTALRM (integer)
SIGPROF (integer)
SIGWINCH (integer)
SIGPOLL (integer)
SIGIO (integer)
SIGPWR (integer)
SIGSYS (integer)
SIGBABY (integer)
SIG_BLOCK (integer)
Available since PHP 5.3.0.
SIG_UNBLOCK (integer)
Available since PHP 5.3.0.
SIG_SETMASK (integer)
Available since PHP 5.3.0.
SI_USER (integer)
Available since PHP 5.3.0.
SI_NOINFO (integer)
Available since PHP 5.3.0.
SI_KERNEL (integer)
Available since PHP 5.3.0.
SI_QUEUE (integer)
Available since PHP 5.3.0.
SI_TIMER (integer)
Available since PHP 5.3.0.
SI_MSGGQ (integer)
Available since PHP 5.3.0.
SI_ASYNCIO (integer)
Available since PHP 5.3.0.
SI_SIGIO (integer)
Available since PHP 5.3.0.
SI_TKILL (integer)
Available since PHP 5.3.0.
CLD_EXITED (integer)
Available since PHP 5.3.0.
CLD_KILLED (integer)
Available since PHP 5.3.0.
CLD_DUMPED (integer)
Available since PHP 5.3.0.
CLD_TRAPPED (integer)
Available since PHP 5.3.0.
CLD_STOPPED (integer)
Available since PHP 5.3.0.
CLD_CONTINUED (integer)
Available since PHP 5.3.0.
TRAP_BRKPT (integer)
Available since PHP 5.3.0.
TRAP_TRACE (integer)
Available since PHP 5.3.0.
POLL_IN (integer)
Available since PHP 5.3.0.
POLL_OUT (integer)
Available since PHP 5.3.0.
POLL_MSG (integer)
Available since PHP 5.3.0.
POLL_ERR (integer)
Available since PHP 5.3.0.
POLL_PRI (integer)
Available since PHP 5.3.0.
POLL_HUP (integer)
Available since PHP 5.3.0.
ILL_ILLOPC (integer)
Available since PHP 5.3.0.
ILL_ILLOPN (integer)
Available since PHP 5.3.0.
ILL_ILLADR (integer)
Available since PHP 5.3.0.
ILL_ILLTRP (integer)
Available since PHP 5.3.0.
ILL_PRVOPC (integer)
Available since PHP 5.3.0.
ILL_PRVREG (integer)
Available since PHP 5.3.0.
ILL_COPROC (integer)
Available since PHP 5.3.0.
ILL_BADSTK (integer)
Available since PHP 5.3.0.
FPE_INTDIV (integer)
Available since PHP 5.3.0.
FPE_INTOVF (integer)
Available since PHP 5.3.0.
FPE_FLTDIV (integer)
Available since PHP 5.3.0.
FPE_FLTOVF (integer)
Available since PHP 5.3.0.
FPE_FLTUND (integer)
Available since PHP 5.3.0.
FPE_FLTRES (integer)
Available since PHP 5.3.0.
FPE_FLTINV (integer)
Available since PHP 5.3.0.
FPE_FLTSUB (integer)
Available since PHP 5.3.0.
SEGV_MAPERR (integer)
Available since PHP 5.3.0.
SEGV_ACCERR (integer)
Available since PHP 5.3.0.
BUS_ADRALN (integer)
Available since PHP 5.3.0.
BUS_ADRERR (integer)
Available since PHP 5.3.0.
BUS_OBJERR (integer)
Available since PHP 5.3.0.
Resource Types
Examples
PCNTL


Process Control Example

Examples
PCNTL Functions
Examples
PHP Manual

This example forks off a daemon process with a signal handler.

Example #1 Process Control Example

<?php
declare(ticks=1);

$pid = pcntl_fork();
if ($pid == -1) {
     die("could not fork");
} else if ($pid) {
     exit(); // we are the parent
} else {
     // we are the child
}

// detatch from the controlling terminal
if (posix_setsid() == -1) {
    die("could not detach from terminal");
}

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

// loop forever performing tasks
while (1) {

    // do something interesting here

}

function sig_handler($signo)
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         default:
             // handle all other signals
     }

}

?>
Examples
PCNTL Functions
Examples


Examples

Table of Contents

  • Process Control Example
Predefined Constants
Process Control Example
PCNTL


Installation

Process Control support in PHP is not enabled by default. You have to compile the CGI or CLI version of PHP with --enable-pcntl configuration option when compiling PHP to enable Process Control support.

Note: Currently, this module will not function on non-Unix platforms (Windows).

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
PCNTL


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
PDF


Examples

Table of Contents

  • Basic Usage Examples
Predefined Constants
Basic Usage Examples
PDF


Basic Usage Examples

Most of the functions are fairly easy to use. The most difficult part is probably creating your first PDF document. The following example should help to get you started. It is developed for PHP 4 and creates the file hello.pdf with one page. It defines some document info field contents, loads the Helvetica-Bold font and outputs the text "Hello world! (says PHP)".

Example #1 Hello World example from PDFlib distribution for PHP 4

<?php
$p = PDF_new();

/*  open new PDF file; insert a file name to create the PDF on disk */
if (PDF_begin_document($p, "", "") == 0) {
    die("Error: " . PDF_get_errmsg($p));
}

PDF_set_info($p, "Creator", "hello.php");
PDF_set_info($p, "Author", "Rainer Schaaf");
PDF_set_info($p, "Title", "Hello world (PHP)!");

PDF_begin_page_ext($p, 595, 842, "");

$font = PDF_load_font($p, "Helvetica-Bold", "winansi", "");

PDF_setfont($p, $font, 24.0);
PDF_set_text_pos($p, 50, 700);
PDF_show($p, "Hello world!");
PDF_continue_text($p, "(says PHP)");
PDF_end_page_ext($p, "");

PDF_end_document($p, "");

$buf = PDF_get_buffer($p);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=hello.pdf");
print $buf;

PDF_delete($p);
?>

The following example comes with the PDFlib distribution for PHP 5. It uses the new exception handling and object encapsulation features available in PHP 5. It creates the file hello.pdf with one page. It defines some document info field contents, loads the Helvetica-Bold font and outputs the text "Hello world! (says PHP)".

Example #2 Hello World example from PDFlib distribution for PHP 5

<?php

try {
    $p = new PDFlib();

    /*  open new PDF file; insert a file name to create the PDF on disk */
    if ($p->begin_document("", "") == 0) {
        die("Error: " . $p->get_errmsg());
    }

    $p->set_info("Creator", "hello.php");
    $p->set_info("Author", "Rainer Schaaf");
    $p->set_info("Title", "Hello world (PHP)!");

    $p->begin_page_ext(595, 842, "");

    $font = $p->load_font("Helvetica-Bold", "winansi", "");

    $p->setfont($font, 24.0);
    $p->set_text_pos(50, 700);
    $p->show("Hello world!");
    $p->continue_text("(says PHP)");
    $p->end_page_ext("");

    $p->end_document("");

    $buf = $p->get_buffer();
    $len = strlen($buf);

    header("Content-type: application/pdf");
    header("Content-Length: $len");
    header("Content-Disposition: inline; filename=hello.pdf");
    print $buf;
}
catch (PDFlibException $e) {
    die("PDFlib exception occurred in hello sample:\n" .
    "[" . $e->get_errnum() . "] " . $e->get_apiname() . ": " .
    $e->get_errmsg() . "\n");
}
catch (Exception $e) {
    die($e);
}
$p = 0;
?>

Examples
PDF Functions
Examples


Installation

This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/pdflib.

To get these functions to work in PHP < 4.3.9, you have to compile PHP with --with-pdflib[=DIR]. DIR is the PDFlib base install directory, defaults to /usr/local.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

PDFlib Lite is available as open source. However, the PDFlib Lite license allows free use only under certain conditions. PDFlib Lite supports a subset of PDFlib's functionality; please see the PDFlib web site for details. The full version of PDFlib is available for download at » http://www.pdflib.com/products/pdflib-family/, but requires that you purchase a license for commercial use.

Issues with older versions of PDFlib

Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.

PDFlib 4.0 or greater is supported by PHP 4.3.0 and later.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

PDF_new() creates a new PDFlib object required by most PDF functions.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
PDF


Constants for PDO_4D

(No version information available, might only be in SVN)

Constants for PDO_4D — Constants for PDO_4D

Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver, if your code can run against multiple drivers.

PDO::FOURD_ATTR_CHARSET (integer)

Change the charset in which 4D returns data. (Default is UTF-8).

PDO::FOURD_ATTR_PREFERRED_IMAGE_TYPES (integer)

The requested format of the image, when selecting a row with a column type PICTURE. It may be any type that 4D supports.

PDO_4D DSN
SQL types with PDO_4D and PHP
Driver 4D for PDO


Examples PDO_4D

SQL acceptable by 4D
Vendor Specific Database Extensions
Driver 4D for PDO
PHP Manual

Examples with PDO_4D

(No version information available, might only be in SVN)

Examples with PDO_4D — Examples PDO_4D

This basic example show how to connect, execute a query, read data and disconnect from a 4D SQL server.

Example #1 Basic example with PDO_4D

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to the 4D SQL server
$db = new PDO_4D($dsn, $user, $pass);

try {
    $db->exec('CREATE TABLE test(id varCHAR(1) NOT NULL, val VARCHAR(10))');
} catch (PDOException $e) {
    die("Erreur 4D : " . $e->getMessage());
}

$db->exec("INSERT INTO test VALUES('A', 'A')");
$db->exec("INSERT INTO test VALUES('B', 'A')");
$db->exec("INSERT INTO test VALUES('C', 'C')");

$stmt = $db->prepare('SELECT id, val from test');

$stmt->execute();
print_r($stmt->fetchAll());

unset($stmt);
unset($db);
?>

The above example will output:

    Array
(
    [0] => Array
        (
            [ID] => A
            [0] => A
            [VAL] => B
            [1] => B
        )

    [1] => Array
        (
            [ID] => C
            [0] => C
            [VAL] => D
            [1] => D
        )

    [2] => Array
        (
            [ID] => E
            [0] => E
            [VAL] => F
            [1] => F
        )

)

This example shows how to execute a query in 4D language, and how to read the result through PDO_4D.

Example #2 Accessing 4D language from pdo_4d

Set up a 4D method, called method. Make sure in the method properties that the option Available via SQL is checked. The 4D code is the following.

C_TEXTE($0)
$0:=Version application(*);

The PHP code to use the above 4D method is :

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to the 4D server
$db = new pdo($dsn, $user, $pass);

$stmt = $db->prepare('SELECT {FN method() AS VARCHAR } FROM _USER_SCHEMAS LIMIT 1');

$stmt->execute();
print_r($stmt->fetchAll());

unset($stmt);
unset($db);
?>

The above example will output:

(
    [0] => Array
        (
            [<expression>] => F0011140
            [0] => F0011140
        )

)

Example #3 Escaping 4D table names

This examples illustrates how to escape characters in a 4D SQL query.

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to 4D server 4D
$db = new PDO_4D($dsn, $user, $pass);

$objects = array('[',']','[]','][','[[',']]','[[[',']]]','TBL ]]32[23');

foreach($objects as $id => $object) {
    $object = str_replace(']',']]', $object);
    print "$object\n";

    $db->exec('CREATE TABLE IF NOT EXISTS ['.$object.'](['.$object.'] FLOAT)');

    $req = "INSERT INTO [$object] ([$object]) VALUES ($id);";
    $db->query($req);

    $q = $db->prepare("SELECT [$object] FROM [$object]");
    $q->execute();
    $x[] = $q->fetch(PDO::FETCH_NUM);

    $db->exec('DROP TABLE ['.$object.'];');
}

?>

The above example will output:

[
]]
[]]
]][
[[
]]]]
[[[
]]]]]]
TBL ]]]]32[23

SQL acceptable by 4D
Vendor Specific Database Extensions
Driver 4D for PDO


SQL types with PDO_4D and PHP

(No version information available, might only be in SVN)

SQL types with PDO_4D and PHP — SQL types with PDO_4D and PHP

Supported SQL types
Type SQL 4D | Equivalent 4D | Note
ALPHA_NUMERIC | TEXT |
VARCHAR | TEXT |
TEXT | TEXT |
TIMESTAMP | DATE |
INTERVAL | HOUR |
DURATION | HOUR |
BOOLEAN | BOOLEAN |
BIT | BOOLEAN |
BYTE | INT32 |
INT16 | SMALLINT |
SMALLINT | SMALLINT |
INT32 | INT32 |
INT | INT32 |
INT64 | INT64 |
NUMERIC | INT64 |
REAL | REAL | Unsupported (use VARCHAR conversion)
FLOAT | FLOAT | Unsupported (use VARCHAR conversion)
DOUBLE PRECISION | FLOAT |
BLOB | BLOB | Must use a prepared statement, and PDO::PARAM_LOB
BIT VARYING | BLOB | Must use a prepared statement, and PDO::PARAM_LOB
CLOB | TEXT |
PICTURE | PICTURE | Must use a prepared statement, and PDO::PARAM_LOB

Constants for PDO_4D
SQL acceptable by 4D
Driver 4D for PDO


Initiates a transaction

PDO
PDO::commit
PDO
PHP Manual

PDO::beginTransaction

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::beginTransaction — Initiates a transaction

Description

bool PDO::beginTransaction ( void )

Turns off autocommit mode. While autocommit mode is turned off, changes made to the database via the PDO object instance are not committed until you end the transaction by calling PDO::commit(). Calling PDO::rollBack() will roll back all changes to the database and return the connection to autocommit mode.

Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Roll back a transaction

The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
    SET name = 'hamburger'");

/* Recognize mistake and roll back changes */
$dbh->rollBack();

/* Database connection is now back in autocommit mode */
?>

See Also

  • PDO::commit() - Commits a transaction
  • PDO::rollBack() - Rolls back a transaction

PDO
PDO::commit
PDO


Commits a transaction

PDO::beginTransaction
PDO::__construct
PDO
PHP Manual

PDO::commit

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::commit — Commits a transaction

Description

bool PDO::commit ( void )

Commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Commit a transaction

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema */
$sth = $dbh->exec("DROP TABLE fruit");

/* Commit the changes */
$dbh->commit();

/* Database connection is now back in autocommit mode */
?>

See Also

  • PDO::beginTransaction() - Initiates a transaction
  • PDO::rollBack() - Rolls back a transaction

PDO::beginTransaction
PDO::__construct
PDO


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PDO Configuration Options
Name | Default | Changeable | Changelog
pdo.dsn.* |  | php.ini only |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

pdo.dsn.* string

Defines DSN alias. See PDO::__construct() for thorough explanation.

Installation
Resource Types
Installing/Configuring


Connections and Connection management

Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).

Example #1 Connecting to MySQL

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>

If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().

Example #2 Handling connection errors

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    foreach($dbh->query('SELECT * from FOO') as $row) {
        print_r($row);
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

Warning

If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler().

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

Example #3 Closing a connection

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here

// and now we're done; close it
$dbh = null;
?>

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

Example #4 Persistent connections

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));
?>

Note: If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections.

Note: If you're using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it's recommended that you don't use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.

Predefined Constants
Transactions and auto-commit
PDO


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Warning

PDO uses class constants since PHP 5.1. Prior releases use global constants in the form PDO_PARAM_BOOL.

PDO::PARAM_BOOL (integer)
Represents a boolean data type.
PDO::PARAM_NULL (integer)
Represents the SQL NULL data type.
PDO::PARAM_INT (integer)
Represents the SQL INTEGER data type.
PDO::PARAM_STR (integer)
Represents the SQL CHAR, VARCHAR, or other string data type.
PDO::PARAM_LOB (integer)
Represents the SQL large object data type.
PDO::PARAM_STMT (integer)
Represents a recordset type. Not currently supported by any drivers.
PDO::PARAM_INPUT_OUTPUT (integer)
Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.
PDO::FETCH_LAZY (integer)
Specifies that the fetch method shall return each row as an object with variable names that correspond to the column names returned in the result set. PDO::FETCH_LAZY creates the object variable names as they are accessed.
PDO::FETCH_ASSOC (integer)
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns only a single value per column name.
PDO::FETCH_NAMED (integer)
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_NAMED returns an array of values per column name.
PDO::FETCH_NUM (integer)
Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_BOTH (integer)
Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_OBJ (integer)
Specifies that the fetch method shall return each row as an object with property names that correspond to the column names returned in the result set.
PDO::FETCH_BOUND (integer)
Specifies that the fetch method shall return TRUE and assign the values of the columns in the result set to the PHP variables to which they were bound with the PDOStatement::bindParam() or PDOStatement::bindColumn() methods.
PDO::FETCH_COLUMN (integer)
Specifies that the fetch method shall return only a single requested column from the next row in the result set.
PDO::FETCH_CLASS (integer)
Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class.

Note: The magic __set method is called if the property doesn't exist in the requested class

PDO::FETCH_INTO (integer)
Specifies that the fetch method shall update an existing instance of the requested class, mapping the columns to named properties in the class.
PDO::FETCH_FUNC (integer)
PDO::FETCH_GROUP (integer)
PDO::FETCH_UNIQUE (integer)
PDO::FETCH_KEY_PAIR (integer)
Fetch into an array where the 1st column is a key and all subsequent columns are values. Available since PHP 5.2.3.
PDO::FETCH_CLASSTYPE (integer)
Determine the class name from the value of first column.
PDO::FETCH_SERIALIZE (integer)
As PDO::FETCH_INTO but object is provided as a serialized string. Available since PHP 5.1.0.
PDO::FETCH_PROPS_LATE (integer)
Available since PHP 5.2.0
PDO::ATTR_AUTOCOMMIT (integer)
If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.
PDO::ATTR_PREFETCH (integer)
Setting the prefetch size allows you to balance speed against memory usage for your application. Not all database/driver combinations support setting of the prefetch size. A larger prefetch size results in increased performance at the cost of higher memory usage.
PDO::ATTR_TIMEOUT (integer)
Sets the timeout value in seconds for communications with the database.
PDO::ATTR_ERRMODE (integer)
See the Errors and error handling section for more information about this attribute.
PDO::ATTR_SERVER_VERSION (integer)
This is a read only attribute; it will return information about the version of the database server to which PDO is connected.
PDO::ATTR_CLIENT_VERSION (integer)
This is a read only attribute; it will return information about the version of the client libraries that the PDO driver is using.
PDO::ATTR_SERVER_INFO (integer)
This is a read only attribute; it will return some meta information about the database server to which PDO is connected.
PDO::ATTR_CONNECTION_STATUS (integer)
PDO::ATTR_CASE (integer)
Force column names to a specific case specified by the PDO::CASE_* constants.
PDO::ATTR_CURSOR_NAME (integer)
Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.
PDO::ATTR_CURSOR (integer)
Selects the cursor type. PDO currently supports either PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick with PDO::CURSOR_FWDONLY unless you know that you need a scrollable cursor.
PDO::ATTR_DRIVER_NAME (string)
Returns the name of the driver.

Example #1 using PDO::ATTR_DRIVER_NAME

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
  echo "Running on mysql; doing something mysql specific here\n";
}
?>

PDO::ATTR_ORACLE_NULLS (integer)
Convert empty strings to SQL NULL values on data fetches.
PDO::ATTR_PERSISTENT (integer)
Request a persistent connection, rather than creating a new connection. See Connections and Connection management for more information on this attribute.
PDO::ATTR_STATEMENT_CLASS (integer)
PDO::ATTR_FETCH_CATALOG_NAMES (integer)
Prepend the containing catalog name to each column name returned in the result set. The catalog name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
PDO::ATTR_FETCH_TABLE_NAMES (integer)
Prepend the containing table name to each column name returned in the result set. The table name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
PDO::ATTR_STRINGIFY_FETCHES (integer)
PDO::ATTR_MAX_COLUMN_LEN (integer)
PDO::ATTR_DEFAULT_FETCH_MODE (integer)
Available since PHP 5.2.0
PDO::ATTR_EMULATE_PREPARES (integer)
Available since PHP 5.1.3.
PDO::ERRMODE_SILENT (integer)
Do not raise an error or exception if an error occurs. The developer is expected to explicitly check for errors. This is the default mode. See Errors and error handling for more information about this attribute.
PDO::ERRMODE_WARNING (integer)
Issue a PHP E_WARNING message if an error occurs. See Errors and error handling for more information about this attribute.
PDO::ERRMODE_EXCEPTION (integer)
Throw a PDOException if an error occurs. See Errors and error handling for more information about this attribute.
PDO::CASE_NATURAL (integer)
Leave column names as returned by the database driver.
PDO::CASE_LOWER (integer)
Force column names to lower case.
PDO::CASE_UPPER (integer)
Force column names to upper case.
PDO::NULL_NATURAL (integer)
PDO::NULL_EMPTY_STRING (integer)
PDO::NULL_TO_STRING (integer)
PDO::FETCH_ORI_NEXT (integer)
Fetch the next row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_PRIOR (integer)
Fetch the previous row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_FIRST (integer)
Fetch the first row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_LAST (integer)
Fetch the last row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_ABS (integer)
Fetch the requested row by row number from the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_REL (integer)
Fetch the requested row by relative position from the current position of the cursor in the result set. Valid only for scrollable cursors.
PDO::CURSOR_FWDONLY (integer)
Create a PDOStatement object with a forward-only cursor. This is the default cursor choice, as it is the fastest and most common data access pattern in PHP.
PDO::CURSOR_SCROLL (integer)
Create a PDOStatement object with a scrollable cursor. Pass the PDO::FETCH_ORI_* constants to control the rows fetched from the result set.
PDO::ERR_NONE (string)
Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.
PDO::PARAM_EVT_ALLOC (integer)
Allocation event
PDO::PARAM_EVT_FREE (integer)
Deallocation event
PDO::PARAM_EVT_EXEC_PRE (integer)
Event triggered prior to execution of a prepared statement.
PDO::PARAM_EVT_EXEC_POST (integer)
Event triggered subsequent to execution of a prepared statement.
PDO::PARAM_EVT_FETCH_PRE (integer)
Event triggered prior to fetching a result from a resultset.
PDO::PARAM_EVT_FETCH_POST (integer)
Event triggered subsequent to fetching a result from a resultset.
PDO::PARAM_EVT_NORMALIZE (integer)
Event triggered during bound parameter registration allowing the driver to normalize the parameter name.
Resource Types
Connections and Connection management
PDO


Creates a PDO instance representing a connection to a database

PDO::commit
PDO::errorCode
PDO
PHP Manual

PDO::__construct

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::__construct — Creates a PDO instance representing a connection to a database

Description

PDO::__construct ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )

Creates a PDO instance to represent a connection to the requested database.

Parameters

dsn

The Data Source Name, or DSN, contains the information required to connect to the database.

In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.

The dsn parameter supports three different methods of specifying the arguments required to create a database connection:

Driver invocation

dsn contains the full DSN.

URI invocation

dsn consists of uri: followed by a URI that defines the location of a file containing the DSN string. The URI can specify a local file or a remote URL.

uri:file:///path/to/dsnfile

Aliasing

dsn consists of a name name that maps to pdo.dsn.name in php.ini defining the DSN string.

Note: The alias must be defined in php.ini, and not .htaccess or httpd.conf

username

The user name for the DSN string. This parameter is optional for some PDO drivers.

password

The password for the DSN string. This parameter is optional for some PDO drivers.

driver_options

A key=>value array of driver-specific connection options.

Return Values

Returns a PDO object on success.

Errors/Exceptions

PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.

Examples

Example #1 Create a PDO instance via driver invocation

<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Example #2 Create a PDO instance via URI invocation

The following example assumes that the file /usr/local/dbconnect exists with file permissions that enable PHP to read the file. The file contains the PDO DSN to connect to a DB2 database through the PDO_ODBC driver:

odbc:DSN=SAMPLE;UID=john;PWD=mypass

The PHP script can then create a database connection by simply passing the uri: parameter and pointing to the file URI:

<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'uri:file:///usr/local/dbconnect';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Example #3 Create a PDO instance using an alias

The following example assumes that php.ini contains the following entry to enable a connection to a MySQL database using only the alias mydb:

[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"
<?php
/* Connect to an ODBC database using an alias */
$dsn = 'mydb';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

PDO::commit
PDO::errorCode
PDO


PDO Drivers

Table of Contents

  • Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
  • Firebird/Interbase Functions (PDO_FIREBIRD)
  • IBM Functions (PDO_IBM)
  • Informix Functions (PDO_INFORMIX)
  • MySQL Functions (PDO_MYSQL)
  • Oracle Functions (PDO_OCI)
  • ODBC and DB2 Functions (PDO_ODBC)
  • PostgreSQL Functions (PDO_PGSQL)
  • SQLite Functions (PDO_SQLITE)
  • Driver 4D for PDO (PDO_4D)

The following drivers currently implement the PDO interface:

Driver name | Supported databases
PDO_DBLIB | FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD | Firebird/Interbase 6
PDO_IBM | IBM DB2
PDO_INFORMIX | IBM Informix Dynamic Server
PDO_MYSQL | MySQL 3.x/4.x/5.x
PDO_OCI | Oracle Call Interface
PDO_ODBC | ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL | PostgreSQL
PDO_SQLITE | SQLite 3 and SQLite 2
PDO_4D | 4D

PDOException
MS SQL Server (PDO)
PDO


Errors and error handling

PDO offers you a choice of 3 different error handling strategies, to fit your style of application development.

  • PDO::ERRMODE_SILENT

    This is the default mode. PDO will simply set the error code for you to inspect using the PDO::errorCode() and PDO::errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement::errorCode() or PDOStatement::errorInfo() method on that object. If the error resulted from a call on the database object, you would invoke those methods on the database object instead.

  • PDO::ERRMODE_WARNING

    In addition to setting the error code, PDO will emit a traditional E_WARNING message. This setting is useful during debugging/testing, if you just want to see what problems occurred without interrupting the flow of the application.

  • PDO::ERRMODE_EXCEPTION

    In addition to setting the error code, PDO will throw a PDOException and set its properties to reflect the error code and error information. This setting is also useful during debugging, as it will effectively "blow up" the script at the point of the error, very quickly pointing a finger at potential problem areas in your code (remember: transactions are automatically rolled back if the exception causes the script to terminate).

    Exception mode is also useful because you can structure your error handling more clearly than with traditional PHP-style warnings, and with less code/nesting than by running in silent mode and explicitly checking the return value of each database call.

    See Exceptions for more information about Exceptions in PHP.

PDO standardizes on using SQL-92 SQLSTATE error code strings; individual PDO drivers are responsible for mapping their native codes to the appropriate SQLSTATE codes. The PDO::errorCode() method returns a single SQLSTATE code. If you need more specific information about an error, PDO also offers an PDO::errorInfo() method which returns an array containing the SQLSTATE code, the driver specific error code and driver specific error string.

Prepared statements and stored procedures
Large Objects (LOBs)
PDO


Fetch the SQLSTATE associated with the last operation on the database handle

PDO::__construct
PDO::errorInfo
PDO
PHP Manual

PDO::errorCode

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle

Description

mixed PDO::errorCode ( void )

Return Values

Returns a SQLSTATE, a five characters alphanumeric identifier defined in the ANSI SQL-92 standard. Briefly, an SQLSTATE consists of a two characters class value followed by a three characters subclass value. A class value of 01 indicates a warning and is accompanied by a return code of SQL_SUCCESS_WITH_INFO. Class values other than '01', except for the class 'IM', indicate an error. The class 'IM' is specific to warnings and errors that derive from the implementation of PDO (or perhaps ODBC, if you're using the ODBC driver) itself. The subclass value '000' in any class indicates that there is no subclass for that SQLSTATE.

PDO::errorCode() only retrieves error codes for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorCode() will not reflect that error. You must call PDOStatement::errorCode() to return the error code for an operation performed on a particular statement handle.

Returns NULL if no operation has been run on the database handle.

Examples

Example #1 Retrieving a SQLSTATE code

<?php
/* Provoke an error -- the BONES table does not exist */
$dbh->exec("INSERT INTO bones(skull) VALUES ('lucy')");

echo "\nPDO::errorCode(): ";
print $dbh->errorCode();
?>

The above example will output:

PDO::errorCode(): 42S02

See Also

  • PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
  • PDOStatement::errorCode() - Fetch the SQLSTATE associated with the last operation on the statement handle
  • PDOStatement::errorInfo() - Fetch extended error information associated with the last operation on the statement handle

PDO::__construct
PDO::errorInfo
PDO


Fetch extended error information associated with the last operation on the database handle

PDO::errorCode
PDO::exec
PDO
PHP Manual

PDO::errorInfo

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle

Description

array PDO::errorInfo ( void )

Return Values

PDO::errorInfo() returns an array of error information about the last operation performed by this database handle. The array consists of the following fields:

Element | Information
0 | SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard).
1 | Driver-specific error code.
2 | Driver-specific error message.

Note: If the SQLSTATE error code is not set or there is no driver-specific error, the elements following element 0 will be set to NULL.

PDO::errorInfo() only retrieves error information for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorInfo() will not reflect the error from the statement handle. You must call PDOStatement::errorInfo() to return the error information for an operation performed on a particular statement handle.

Examples

Example #1 Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

<?php
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}
?>

The above example will output:

PDO::errorInfo():
Array
(
    [0] => HY000
    [1] => 1
    [2] => near "bogus": syntax error
)

See Also

  • PDO::errorCode() - Fetch the SQLSTATE associated with the last operation on the database handle
  • PDOStatement::errorCode() - Fetch the SQLSTATE associated with the last operation on the statement handle
  • PDOStatement::errorInfo() - Fetch extended error information associated with the last operation on the statement handle

PDO::errorCode
PDO::exec
PDO


Execute an SQL statement and return the number of affected rows

PDO::errorInfo
PDO::getAttribute
PDO
PHP Manual

PDO::exec

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::exec — Execute an SQL statement and return the number of affected rows

Description

int PDO::exec ( string $statement )

PDO::exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement.

PDO::exec() does not return results from a SELECT statement. For a SELECT statement that you only need to issue once during your program, consider issuing PDO::query(). For a statement that you need to issue multiple times, prepare a PDOStatement object with PDO::prepare() and issue the statement with PDOStatement::execute().

Parameters

statement

The SQL statement to prepare and execute.

Data inside the query should be properly escaped.

Return Values

PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

The following example incorrectly relies on the return value of PDO::exec(), wherein a statement that affected 0 rows results in a call to die():

<?php
$db->exec() or die(print_r($db->errorInfo(), true));
?>

Examples

Example #1 Issuing a DELETE statement

Count the number of rows deleted by a DELETE statement with no WHERE clause.

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

/* Delete all rows from the FRUIT table */
$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'");

/* Return number of rows that were deleted */
print("Deleted $count rows.\n");
?>

The above example will output:

Deleted 1 rows.

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::execute() - Executes a prepared statement

PDO::errorInfo
PDO::getAttribute
PDO


Retrieve a database connection attribute

PDO::exec
PDO::getAvailableDrivers
PDO
PHP Manual

PDO::getAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDO::getAttribute — Retrieve a database connection attribute

Description

mixed PDO::getAttribute ( int $attribute )

This function returns the value of a database connection attribute. To retrieve PDOStatement attributes, refer to PDOStatement::getAttribute().

Note that some database/driver combinations may not support all of the database connection attributes.

Parameters

attribute

One of the PDO::ATTR_* constants. The constants that apply to database connections are as follows:

  • PDO::ATTR_AUTOCOMMIT
  • PDO::ATTR_CASE
  • PDO::ATTR_CLIENT_VERSION
  • PDO::ATTR_CONNECTION_STATUS
  • PDO::ATTR_DRIVER_NAME
  • PDO::ATTR_ERRMODE
  • PDO::ATTR_ORACLE_NULLS
  • PDO::ATTR_PERSISTENT
  • PDO::ATTR_PREFETCH
  • PDO::ATTR_SERVER_INFO
  • PDO::ATTR_SERVER_VERSION
  • PDO::ATTR_TIMEOUT

Return Values

A successful call returns the value of the requested PDO attribute. An unsuccessful call returns null.

Examples

Example #1 Retrieving database connection attributes

<?php
$conn = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
$attributes = array(
    "AUTOCOMMIT", "ERRMODE", "CASE", "CLIENT_VERSION", "CONNECTION_STATUS",
    "ORACLE_NULLS", "PERSISTENT", "PREFETCH", "SERVER_INFO", "SERVER_VERSION",
    "TIMEOUT"
);

foreach ($attributes as $val) {
    echo "PDO::ATTR_$val: ";
    echo $conn->getAttribute(constant("PDO::ATTR_$val")) . "\n";
}
?>

See Also

  • PDO::setAttribute() - Set an attribute
  • PDOStatement::getAttribute() - Retrieve a statement attribute
  • PDOStatement::setAttribute() - Set a statement attribute

PDO::exec
PDO::getAvailableDrivers
PDO


Return an array of available PDO drivers

PDO::getAttribute
PDO::lastInsertId
PDO
PHP Manual

PDO::getAvailableDrivers

(PHP 5 >= 5.1.3, PECL pdo >= 1.0.3)

PDO::getAvailableDrivers — Return an array of available PDO drivers

Description

array PDO::getAvailableDrivers ( void )
array pdo_drivers ( void )

This function returns all currently available PDO drivers which can be used in DSN parameter of PDO::__construct(). This is a static method.

Return Values

PDO::getAvailableDrivers() returns an array of PDO driver names. If no drivers are available, it returns an empty array.

Examples

Example #1 A PDO::getAvailableDrivers() example

<?php
print_r(PDO::getAvailableDrivers());
?>

The above example will output something similar to:

Array
(
    [0] => mysql
    [1] => sqlite
)

PDO::getAttribute
PDO::lastInsertId
PDO


Installation

Installing PDO on Unix systems

  1. PDO and the PDO_SQLITE driver is enabled by default as of PHP 5.1.0. You may need to enable the PDO driver for your database of choice; consult the documentation for database-specific PDO drivers to find out more about that. Note: When building PDO as a shared extension (not recommended) then all PDO drivers must be loaded after PDO itself.

  2. When installing PDO as a shared module, the php.ini file needs to be updated so that the PDO extension will be loaded automatically when PHP runs. You will also need to enable any database specific drivers there too; make sure that they are listed after the pdo.so line, as PDO must be initialized before the database-specific extensions can be loaded. If you built PDO and the database-specific extensions statically, you can skip this step.

    extension=pdo.so

Windows users

  1. PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file:

    extension=php_pdo.dll

  2. Next, choose the other database-specific DLL files and either use dl() to load them at runtime, or enable them in php.ini below php_pdo.dll. For example:

    extension=php_pdo.dll
extension=php_pdo_firebird.dll
extension=php_pdo_informix.dll
extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_oci8.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll

    These DLLs should exist in the system's extension_dir.

Requirements
Runtime Configuration
Installing/Configuring


Returns the ID of the last inserted row or sequence value

PDO::getAvailableDrivers
PDO::prepare
PDO
PHP Manual

PDO::lastInsertId

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::lastInsertId — Returns the ID of the last inserted row or sequence value

Description

string PDO::lastInsertId ([ string $name = NULL ] )

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL() requires you to specify the name of a sequence object for the name parameter.

Note: This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.

Parameters

name

Name of the sequence object from which the ID should be returned.

Return Values

If a sequence name was not specified for the name parameter, PDO::lastInsertId() returns a string representing the row ID of the last row that was inserted into the database.

If a sequence name was specified for the name parameter, PDO::lastInsertId() returns a string representing the last value retrieved from the specified sequence object.

If the PDO driver does not support this capability, PDO::lastInsertId() triggers an IM001 SQLSTATE.

PDO::getAvailableDrivers
PDO::prepare
PDO


Large Objects (LOBs)

At some point in your application, you might find that you need to store "large" data in your database. Large typically means "around 4kb or more", although some databases can happily handle up to 32kb before data becomes "large". Large objects can be either textual or binary in nature. PDO allows you to work with this large data type by using the PDO::PARAM_LOB type code in your PDOStatement::bindParam() or PDOStatement::bindColumn() calls. PDO::PARAM_LOB tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.

Example #1 Displaying an image from a database

This example binds the LOB into the variable named $lob and then sends it to the browser using fpassthru(). Since the LOB is represented as a stream, functions such as fgets(), fread() and stream_get_contents() can be used on it.

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

header("Content-Type: $type");
fpassthru($lob);
?>

Example #2 Inserting an image into a database

This example opens up a file and passes the file handle to PDO to insert it as a LOB. PDO will do its best to get the contents of the file up to the database in the most efficient manner possible.

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // some function to allocate a new ID

// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$db->beginTransaction();
$stmt->execute();
$db->commit();
?>

Example #3 Inserting an image into a database: Oracle

Oracle requires a slightly different syntax for inserting a lob from a file. It's also essential that you perform the insert under a transaction, otherwise your newly inserted LOB will be committed with a zero-length as part of the implicit commit that happens when the query is executed:

<?php
$db = new PDO('oci:', 'scott', 'tiger');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) " .
"VALUES (?, ?, EMPTY_BLOB()) RETURNING imagedata INTO ?");
$id = get_new_id(); // some function to allocate a new ID

// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$stmt->beginTransaction();
$stmt->execute();
$stmt->commit();
?>

Errors and error handling
PDO
PDO


Prepares a statement for execution and returns a statement object

PDO::lastInsertId
PDO::query
PDO
PHP Manual

PDO::prepare

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::prepare — Prepares a statement for execution and returns a statement object

Description

PDOStatement PDO::prepare ( string $statement [, array $driver_options = array() ] )

Prepares an SQL statement to be executed by the PDOStatement::execute() method. The SQL statement can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed. You cannot use both named and question mark parameter markers within the same SQL statement; pick one or the other parameter style. Use these parameters to bind any user-input, do not include the user-input directly in the query.

You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name twice in a prepared statement. You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement.

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.

Parameters

statement

This must be a valid SQL statement for the target database server.

driver_options

This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have driver specific options that may be set at prepare-time.

Return Values

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

Note: Emulated prepared statements does not communicate with the database server so PDO::prepare() does not check the statement.

Examples

Example #1 Prepare an SQL statement with named parameters

<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array('calories' => 175, 'colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>

Example #2 Prepare an SQL statement with question mark parameters

<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>

See Also

  • PDO::exec() - Execute an SQL statement and return the number of affected rows
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::execute() - Executes a prepared statement

PDO::lastInsertId
PDO::query
PDO


Prepared statements and stored procedures

Many of the more mature databases support the concept of prepared statements. What are they? They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits:

  • The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize it's plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.
  • The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

Prepared statements are so useful that they are the only feature that PDO will emulate for drivers that don't support them. This ensures that an application will be able to use the same data access paradigm regardless of the capabilities of the database.

Example #1 Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the named placeholders.

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

Example #2 Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the positional ? placeholders.

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

Example #3 Fetching data using prepared statements

This example fetches data based on a key value supplied by a form. The user input is automatically quoted, so there is no risk of a SQL injection attack.

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
}
?>

If the database driver supports it, an application may also bind parameters for output as well as input. Output parameters are typically used to retrieve values from stored procedures. Output parameters are slightly more complex to use than input parameters, in that a developer must know how large a given parameter might be when they bind it. If the value turns out to be larger than the size they suggested, an error is raised.

Example #4 Calling a stored procedure with an output parameter

<?php
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);

// call the stored procedure
$stmt->execute();

print "procedure returned $return_value\n";
?>

Developers may also specify parameters that hold values both input and output; the syntax is similar to output parameters. In this next example, the string 'hello' is passed into the stored procedure, and when it returns, hello is replaced with the return value of the procedure.

Example #5 Calling a stored procedure with an input/output parameter

<?php
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);

// call the stored procedure
$stmt->execute();

print "procedure returned $value\n";
?>

Example #6 Invalid use of placeholder

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE '%?%'");
$stmt->execute(array($_GET['name']));

// placeholder must be used in the place of the whole value
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->execute(array("%$_GET[name]%"));
?>

Transactions and auto-commit
Errors and error handling
PDO


Executes an SQL statement, returning a result set as a PDOStatement object

PDO::prepare
PDO::quote
PDO
PHP Manual

PDO::query

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object

Description

PDOStatement PDO::query ( string $statement )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_COLUMN , int $colno )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_INTO , object $object )

PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.

For a query that you need to issue multiple times, you will realize better performance if you prepare a PDOStatement object using PDO::prepare() and issue the statement with multiple calls to PDOStatement::execute().

If you do not fetch all of the data in a result set before issuing your next call to PDO::query(), your call may fail. Call PDOStatement::closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO::query().

Note: Although this function is only documented as having a single parameter, you may pass additional arguments to this function. They will be treated as though you called PDOStatement::setFetchMode() on the resultant statement object.

Parameters

statement

The SQL statement to prepare and execute.

Data inside the query should be properly escaped.

Return Values

PDO::query() returns a PDOStatement object, or FALSE on failure.

Examples

Example #1 Demonstrate PDO::query

A nice feature of PDO::query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement.

<?php
function getFruit($conn) {
    $sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
    foreach ($conn->query($sql) as $row) {
        print $row['name'] . "\t";
        print $row['color'] . "\t";
        print $row['calories'] . "\n";
    }
}
?>

The above example will output:

apple   red     150
banana  yellow  250
kiwi    brown   75
lemon   yellow  25
orange  orange  300
pear    green   150
watermelon      pink    90

See Also

  • PDO::exec() - Execute an SQL statement and return the number of affected rows
  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement

PDO::prepare
PDO::quote
PDO


Quotes a string for use in a query.

PDO::query
PDO::rollBack
PDO
PHP Manual

PDO::quote

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.1)

PDO::quote — Quotes a string for use in a query.

Description

string PDO::quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )

PDO::quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.

If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into a SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, immune to SQL injection, but are often much faster to execute than interpolated queries, as both the server and client side can cache a compiled form of the query.

Not all PDO drivers implement this method (notably PDO_ODBC). Consider using prepared statements instead.

Parameters

string

The string to be quoted.

parameter_type

Provides a data type hint for drivers that have alternate quoting styles.

Return Values

Returns a quoted string that is theoretically safe to pass into an SQL statement. Returns FALSE if the driver does not support quoting in this way.

Examples

Example #1 Quoting a normal string

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>

The above example will output:

Unquoted string: Nice
Quoted string: 'Nice'

Example #2 Quoting a dangerous string

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Dangerous string */
$string = 'Naughty \' string';
print "Unquoted string: $string\n";
print "Quoted string:" . $conn->quote($string) . "\n";
?>

The above example will output:

Unquoted string: Naughty ' string
Quoted string: 'Naughty '' string'

Example #3 Quoting a complex string

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Complex string */
$string = "Co'mpl''ex \"st'\"ring";
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>

The above example will output:

Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement

PDO::query
PDO::rollBack
PDO


Rolls back a transaction

PDO::quote
PDO::setAttribute
PDO
PHP Manual

PDO::rollBack

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::rollBack — Rolls back a transaction

Description

bool PDO::rollBack ( void )

Rolls back the current transaction, as initiated by PDO::beginTransaction(). It is an error to call this method if no transaction is active.

If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction.

Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Roll back a transaction

The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
    SET name = 'hamburger'");

/* Recognize mistake and roll back changes */
$dbh->rollBack();

/* Database connection is now back in autocommit mode */
?>

See Also

  • PDO::beginTransaction() - Initiates a transaction
  • PDO::commit() - Commits a transaction

PDO::quote
PDO::setAttribute
PDO


Set an attribute

PDO::rollBack
PDOStatement
PDO
PHP Manual

PDO::setAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::setAttribute — Set an attribute

Description

bool PDO::setAttribute ( int $attribute , mixed $value )

Sets an attribute on the database handle. Some of the available generic attributes are listed below; some drivers may make use of additional driver specific attributes.

  • PDO::ATTR_CASE: Force column names to a specific case.

    • PDO::CASE_LOWER: Force column names to lower case.

    • PDO::CASE_NATURAL: Leave column names as returned by the database driver.

    • PDO::CASE_UPPER: Force column names to upper case.

  • PDO::ATTR_ERRMODE: Error reporting.

    • PDO::ERRMODE_SILENT: Just set error codes.

    • PDO::ERRMODE_WARNING: Raise E_WARNING.

    • PDO::ERRMODE_EXCEPTION: Throw exceptions.

  • PDO::ATTR_ORACLE_NULLS (available with all drivers, not just Oracle): Conversion of NULL and empty strings.

    • PDO::NULL_NATURAL: No conversion.

    • PDO::NULL_EMPTY_STRING: Empty string is converted to NULL.

    • PDO::NULL_TO_STRING: NULL is converted to an empty string.

  • PDO::ATTR_STRINGIFY_FETCHES: Convert numeric values to strings when fetching. Requires bool.

  • PDO::ATTR_STATEMENT_CLASS: Set user-supplied statement class derived from PDOStatement. Cannot be used with persistent PDO instances. Requires array(string classname, array(mixed constructor_args)).

  • PDO::ATTR_AUTOCOMMIT (available in OCI, Firebird and MySQL): Whether to autocommit every single statement.

  • PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (available in MySQL): Use buffered queries.

Return Values

Returns TRUE on success or FALSE on failure.

PDO::rollBack
PDOStatement
PDO


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
PDO


Transactions and auto-commit

Now that you're connected via PDO, you must understand how PDO manages transactions before you start issuing queries. If you've never encountered transactions before, they offer 4 major features: Atomicity, Consistency, Isolation and Durability (ACID). In layman's terms, any work carried out in a transaction, even if it is carried out in stages, is guaranteed to be applied to the database safely, and without interference from other connections, when it is committed. Transactional work can also be automatically undone at your request (provided you haven't already committed it), which makes error handling in your scripts easier.

Transactions are typically implemented by "saving-up" your batch of changes to be applied all at once; this has the nice side effect of drastically improving the efficiency of those updates. In other words, transactions can make your scripts faster and potentially more robust (you still need to use them correctly to reap that benefit).

Unfortunately, not every database supports transactions, so PDO needs to run in what is known as "auto-commit" mode when you first open the connection. Auto-commit mode means that every query that you run has its own implicit transaction, if the database supports it, or no transaction if the database doesn't support transactions. If you need a transaction, you must use the PDO::beginTransaction() method to initiate one. If the underlying driver does not support transactions, a PDOException will be thrown (regardless of your error handling settings: this is always a serious error condition). Once you are in a transaction, you may use PDO::commit() or PDO::rollBack() to finish it, depending on the success of the code you run during the transaction.

When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back. This is a safety measure to help avoid inconsistency in the cases where the script terminates unexpectedly--if you didn't explicitly commit the transaction, then it is assumed that something went awry, so the rollback is performed for the safety of your data.

Warning

The automatic rollback only happens if you initiate the transaction via PDO::beginTransaction(). If you manually issue a query that begins a transaction PDO has no way of knowing about it and thus cannot roll it back if something bad happens.

Example #1 Executing a batch in a transaction

In the following sample, let's assume that we are creating a set of entries for a new employee, who has been assigned an ID number of 23. In addition to entering the basic data for that person, we also need to record their salary. It's pretty simple to make two separate updates, but by enclosing them within the PDO::beginTransaction() and PDO::commit() calls, we are guaranteeing that no one else will be able to see those changes until they are complete. If something goes wrong, the catch block rolls back all changes made since the transaction was started, and then prints out an error message.

<?php
try {
  $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
      array(PDO::ATTR_PERSISTENT => true));
  echo "Connected\n";
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $dbh->beginTransaction();
  $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
  $dbh->exec("insert into salarychange (id, amount, changedate)
      values (23, 50000, NOW())");
  $dbh->commit();

} catch (Exception $e) {
  $dbh->rollBack();
  echo "Failed: " . $e->getMessage();
}
?>

You're not limited to making updates in a transaction; you can also issue complex queries to extract data, and possibly use that information to build up more updates and queries; while the transaction is active, you are guaranteed that no one else can make changes while you are in the middle of your work. For further reading on transactions, refer to the documentation provided by your database server.

Connections and Connection management
Prepared statements and stored procedures
PDO


Bind a column to a PHP variable

PDOStatement
PDOStatement->bindParam
PDOStatement
PHP Manual

PDOStatement->bindColumn

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement->bindColumn — Bind a column to a PHP variable

Description

bool PDOStatement::bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] )

PDOStatement::bindColumn() arranges to have a particular variable bound to a given column in the result-set from a query. Each call to PDOStatement::fetch() or PDOStatement::fetchAll() will update all the variables that are bound to columns.

Note: Since information about the columns is not always available to PDO until the statement is executed, portable applications should call this function after PDOStatement::execute().
However, to be able to bind a LOB column as a stream when using the PgSQL driver, applications should call this method before calling PDOStatement::execute(), otherwise the large object OID will be returned as an integer.

Parameters

column

Number of the column (1-indexed) or name of the column in the result set. If using the column name, be aware that the name should match the case of the column, as returned by the driver.

param

Name of the PHP variable to which the column will be bound.

type

Data type of the parameter, specified by the PDO::PARAM_* constants.

maxlen

A hint for pre-allocation.

driverdata

Optional parameter(s) for the driver.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Binding result set output to PHP variables

Binding columns in the result set to PHP variables is an effective way to make the data contained in each row immediately available to your application. The following example demonstrates how PDO allows you to bind and retrieve columns with a variety of options and with intelligent defaults.

<?php
function readData($dbh) {
  $sql = 'SELECT name, colour, calories FROM fruit';
  try {
    $stmt = $dbh->prepare($sql);
    $stmt->execute();

    /* Bind by column number */
    $stmt->bindColumn(1, $name);
    $stmt->bindColumn(2, $colour);

    /* Bind by column name */
    $stmt->bindColumn('calories', $cals);

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
      $data = $name . "\t" . $colour . "\t" . $cals . "\n";
      print $data;
    }
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
readData($dbh);
?>

The above example will output:

apple   red     150
banana  yellow  175
kiwi    green   75
orange  orange  150
mango   red     200
strawberry      red     25

See Also

  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchAll() - Returns an array containing all of the result set rows
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set

PDOStatement
PDOStatement->bindParam
PDOStatement


Binds a parameter to the specified variable name

PDOStatement->bindColumn
PDOStatement->bindValue
PDOStatement
PHP Manual

PDOStatement->bindParam

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement->bindParam — Binds a parameter to the specified variable name

Description

bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )

Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

Most parameters are input parameters, that is, parameters that are used in a read-only fashion to build up the query. Some drivers support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.

Parameters

parameter

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

variable

Name of the PHP variable to bind to the SQL statement parameter.

data_type

Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the data_type parameter.

length

Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length.

driver_options

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Execute a prepared statement with named placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Example #2 Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Example #3 Call a stored procedure with an INOUT parameter

<?php
/* Call a stored procedure with an INOUT parameter */
$colour = 'red';
$sth = $dbh->prepare('CALL puree_fruit(?)');
$sth->bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth->execute();
print("After pureeing fruit, the colour is: $colour");
?>

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::bindValue() - Binds a value to a parameter

PDOStatement->bindColumn
PDOStatement->bindValue
PDOStatement


Binds a value to a parameter

PDOStatement->bindParam
PDOStatement->closeCursor
PDOStatement
PHP Manual

PDOStatement->bindValue

(PHP 5 >= 5.1.0, PECL pdo >= 1.0.0)

PDOStatement->bindValue — Binds a value to a parameter

Description

bool PDOStatement::bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )

Binds a value to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement.

Parameters

parameter

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

value

The value to bind to the parameter.

data_type

Explicit data type for the parameter using the PDO::PARAM_* constants.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Execute a prepared statement with named placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>

Example #2 Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindValue(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
?>

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::bindParam() - Binds a parameter to the specified variable name

PDOStatement->bindParam
PDOStatement->closeCursor
PDOStatement


Closes the cursor, enabling the statement to be executed again.

PDOStatement->bindValue
PDOStatement->columnCount
PDOStatement
PHP Manual

PDOStatement->closeCursor

(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)

PDOStatement->closeCursor — Closes the cursor, enabling the statement to be executed again.

Description

bool PDOStatement::closeCursor ( void )

PDOStatement::closeCursor() frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a state that enables it to be executed again.

This method is useful for database drivers that do not support executing a PDOStatement object when a previously executed PDOStatement object still has unfetched rows. If your database driver suffers from this limitation, the problem may manifest itself in an out-of-sequence error.

PDOStatement::closeCursor() is implemented either as an optional driver specific method (allowing for maximum efficiency), or as the generic PDO fallback if no driver specific function is installed. The PDO generic fallback is semantically the same as writing the following code in your PHP script:

<?php
do {
    while ($stmt->fetch())
        ;
    if (!$stmt->nextRowset())
        break;
} while (true);
?>

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A PDOStatement::closeCursor() example

In the following example, the $stmt PDOStatement object returns multiple rows but the application fetches only the first row, leaving the PDOStatement object in a state of having unfetched rows. To ensure that the application will work with all database drivers, the author inserts a call to PDOStatement::closeCursor() on $stmt before executing the $otherStmt PDOStatement object.

<?php
/* Create a PDOStatement object */
$stmt = $dbh->prepare('SELECT foo FROM bar');

/* Create a second PDOStatement object */
$otherStmt = $dbh->prepare('SELECT foobaz FROM foobar');

/* Execute the first statement */
$stmt->execute();

/* Fetch only the first row from the results */
$stmt->fetch();

/* The following call to closeCursor() may be required by some drivers */
$stmt->closeCursor();

/* Now we can execute the second statement */
$otherStmt->execute();
?>

See Also

  • PDOStatement::execute() - Executes a prepared statement

PDOStatement->bindValue
PDOStatement->columnCount
PDOStatement


Returns the number of columns in the result set

PDOStatement->closeCursor
PDOStatement->debugDumpParams
PDOStatement
PHP Manual

PDOStatement->columnCount

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement->columnCount — Returns the number of columns in the result set

Description

int PDOStatement::columnCount ( void )

Use PDOStatement::columnCount() to return the number of columns in the result set represented by the PDOStatement object.

If the PDOStatement object was returned from PDO::query(), the column count is immediately available.

If the PDOStatement object was returned from PDO::prepare(), an accurate column count will not be available until you invoke PDOStatement::execute().

Return Values

Returns the number of columns in the result set represented by the PDOStatement object. If there is no result set, PDOStatement::columnCount() returns 0.

Examples

Example #1 Counting columns

This example demonstrates how PDOStatement::columnCount() operates with and without a result set.

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

$sth = $dbh->prepare("SELECT name, colour FROM fruit");

/* Count the number of columns in the (non-existent) result set */
$colcount = $sth->columnCount();
print("Before execute(), result set has $colcount columns (should be 0)\n");

$sth->execute();

/* Count the number of columns in the result set */
$colcount = $sth->columnCount();
print("After execute(), result set has $colcount columns (should be 2)\n");

?>

The above example will output:

Before execute(), result set has 0 columns (should be 0)
After execute(), result set has 2 columns (should be 2)

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::rowCount() - Returns the number of rows affected by the last SQL statement

PDOStatement->closeCursor
PDOStatement->debugDumpParams
PDOStatement


Dump a SQL prepared command

PDOStatement->columnCount
PDOStatement->errorCode
PDOStatement
PHP Manual

PDOStatement->debugDumpParams

(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)

PDOStatement->debugDumpParams — Dump a SQL prepared command

Description

bool PDOStatement::debugDumpParams ( void )

Dumps the informations contained by a prepared statement directly on the output. It will provide the SQL query in use, the number of parameters used (Params), the list of parameters, with their name, type (paramtype) as an integer, their key name or position, the value, and the position in the query (if this is supported by the PDO driver, otherwise, it will be -1).

This is a debug function, which dump directly the data on the normal output.

Tip

As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).

This will only dumps the parameters in the statement at the moment of the dump. Extra parameters are not stored in the statement, and not displayed.

Return Values

No value is returned.

Examples

Example #1 PDOStatement::debugDumpParams() example with named parameters

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

$sth->debugDumpParams();

?>

The above example will output:

SQL: [96] SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour
Params:  2
Key: Name: [9] :calories
paramno=-1
name=[9] ":calories"
is_param=1
param_type=1
Key: Name: [7] :colour
paramno=-1
name=[7] ":colour"
is_param=1
param_type=2

Example #2 PDOStatement::debugDumpParams() example with unnamed parameters

<?php

/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$name = 'apple';

$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();

$sth->debugDumpParams();

?>

The above example will output:

SQL: [82] SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?
Params:  2
Key: Position #0:
paramno=0
name=[0] ""
is_param=1
param_type=1
Key: Position #1:
paramno=1
name=[0] ""
is_param=1
param_type=2

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::bindParam() - Binds a parameter to the specified variable name
  • PDOStatement::bindValue() - Binds a value to a parameter

PDOStatement->columnCount
PDOStatement->errorCode
PDOStatement


Fetch the SQLSTATE associated with the last operation on the statement handle

PDOStatement->debugDumpParams
PDOStatement->errorInfo
PDOStatement
PHP Manual

PDOStatement->errorCode

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement->errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle

Description

string PDOStatement::errorCode ( void )

Return Values

Identical to PDO::errorCode(), except that PDOStatement::errorCode() only retrieves error codes for operations performed with PDOStatement objects.

Examples

Example #1 Retrieving a SQLSTATE code

<?php
/* Provoke an error -- the BONES table does not exist */
$err = $dbh->prepare('SELECT skull FROM bones');
$err->execute();

echo "\nPDOStatement::errorCode(): ";
print $err->errorCode();
?>

The above example will output:

PDOStatement::errorCode(): 42S02

See Also

  • PDO::errorCode() - Fetch the SQLSTATE associated with the last operation on the database handle
  • PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
  • PDOStatement::errorInfo() - Fetch extended error information associated with the last operation on the statement handle

PDOStatement->debugDumpParams
PDOStatement->errorInfo
PDOStatement


Fetch extended error information associated with the last operation on the statement handle

PDOStatement->errorCode
PDOStatement->execute
PDOStatement
PHP Manual

PDOStatement->errorInfo

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement->errorInfo — Fetch extended error information associated with the last operation on the statement handle

Description

array PDOStatement::errorInfo ( void )

Return Values

PDOStatement::errorInfo() returns an array of error information about the last operation performed by this statement handle. The array consists of the following fields:

Element | Information
0 | SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard).
1 | Driver specific error code.
2 | Driver specific error message.

Examples

Example #1 Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

<?php
/* Provoke an error -- the BONES table does not exist */
$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);
?>

The above example will output:

PDOStatement::errorInfo():
Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)

See Also

  • PDO::errorCode() - Fetch the SQLSTATE associated with the last operation on the database handle
  • PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
  • PDOStatement::errorCode() - Fetch the SQLSTATE associated with the last operation on the statement handle

PDOStatement->errorCode
PDOStatement->execute
PDOStatement


Executes a prepared statement

PDOStatement->errorInfo
PDOStatement->fetch
PDOStatement
PHP Manual

PDOStatement->execute

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement->execute — Executes a prepared statement

Description

bool PDOStatement::execute ([ array $input_parameters = array() ] )

Execute the prepared statement. If the prepared statement included parameter markers, you must either:

  • call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers

  • or pass an array of input-only parameter values

Parameters

input_parameters

An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.

You cannot bind multiple values to a single parameter; for example, you cannot bind two values to a single named parameter in an IN() clause.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Execute a prepared statement with bound variables

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Example #2 Execute a prepared statement with an array of insert values (named parameters)

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>

Example #3 Execute a prepared statement with an array of insert values (placeholders)

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));
?>

Example #4 Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Notes

Note: Some drivers require to close cursor before executing next statement.

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::bindParam() - Binds a parameter to the specified variable name
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchAll() - Returns an array containing all of the result set rows
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set

PDOStatement->errorInfo
PDOStatement->fetch
PDOStatement


Fetches the next row from a result set

PDOStatement->execute
PDOStatement->fetchAll
PDOStatement
PHP Manual

PDOStatement->fetch

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement->fetch — Fetches the next row from a result set

Description

 mixed PDOStatement::fetch
  ([ int $fetch_style = PDO::FETCH_BOTH
 [, int $cursor_orientation = PDO::FETCH_ORI_NEXT
 [, int $cursor_offset = 0
]]] )

Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.

Parameters

fetch_style

Controls how the next row will be returned to the caller. This value must be one of the PDO::FETCH_* constants, defaulting to PDO::FETCH_BOTH.

  • PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set

  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

  • PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement::bindColumn() method

  • PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the class. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class is determined from a value of the first column.

  • PDO::FETCH_INTO: updates an existing instance of the requested class, mapping the columns of the result set to named properties in the class

  • PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed

  • PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

  • PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set

cursor_orientation

For a PDOStatement object representing a scrollable cursor, this value determines which row will be returned to the caller. This value must be one of the PDO::FETCH_ORI_* constants, defaulting to PDO::FETCH_ORI_NEXT. To request a scrollable cursor for your PDOStatement object, you must set the PDO::ATTR_CURSOR attribute to PDO::CURSOR_SCROLL when you prepare the SQL statement with PDO::prepare().

offset

For a PDOStatement object representing a scrollable cursor for which the cursor_orientation parameter is set to PDO::FETCH_ORI_ABS, this value specifies the absolute number of the row in the result set that shall be fetched.

For a PDOStatement object representing a scrollable cursor for which the cursor_orientation parameter is set to PDO::FETCH_ORI_REL, this value specifies the row to fetch relative to the cursor position before PDOStatement::fetch() was called.

Return Values

The return value of this function on success depends on the fetch type. In all cases, FALSE is returned on failure.

Examples

Example #1 Fetching rows using different fetch styles

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");

print("PDO::FETCH_BOTH: ");
print("Return next row as an array indexed by both column name and number\n");
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print("\n");

print("PDO::FETCH_LAZY: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print("\n");

print("PDO::FETCH_OBJ: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;
print("\n");
?>

The above example will output:

PDO::FETCH_ASSOC: Return next row as an array indexed by column name
Array
(
    [NAME] => apple
    [COLOUR] => red
)

PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number
Array
(
    [NAME] => banana
    [0] => banana
    [COLOUR] => yellow
    [1] => yellow
)

PDO::FETCH_LAZY: Return next row as an anonymous object with column names as properties
PDORow Object
(
    [NAME] => orange
    [COLOUR] => orange
)

PDO::FETCH_OBJ: Return next row as an anonymous object with column names as properties
kiwi

Example #2 Fetching rows with a scrollable cursor

<?php
function readDataForwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET';
  try {
    $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    }
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
function readDataBackwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet';
  try {
    $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
    do {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    } while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR));
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}

print "Reading forwards:\n";
readDataForwards($conn);

print "Reading backwards:\n";
readDataBackwards($conn);
?>

The above example will output:

Reading forwards:
21    10    5
16    0     5
19    20    10

Reading backwards:
19    20    10
16    0     5
21    10    5

See Also

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::fetchAll() - Returns an array containing all of the result set rows
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
  • PDOStatement::fetchObject() - Fetches the next row and returns it as an object.
  • PDOStatement::setFetchMode() - Set the default fetch mode for this statement

PDOStatement->execute
PDOStatement->fetchAll
PDOStatement


Returns an array containing all of the result set rows

PDOStatement->fetch
PDOStatement->fetchColumn
PDOStatement
PHP Manual

PDOStatement->fetchAll

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement->fetchAll — Returns an array containing all of the result set rows

Description

array PDOStatement::fetchAll ([ int $fetch_style = PDO::FETCH_BOTH [, int $column_index = 0 [, array $ctor_args = array() ]]] )

Parameters

fetch_style

Controls the contents of the returned array as documented in PDOStatement::fetch().

To return an array consisting of all values of a single column from the result set, specify PDO::FETCH_COLUMN. You can specify which column you want with the column-index parameter.

To fetch only the unique values of a single column from the result set, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_UNIQUE.

To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.

column_index

Returns the indicated 0-indexed column when the value of fetch_style is PDO::FETCH_COLUMN.

ctor_args

Arguments of custom class constructor.

Return Values

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name.

Using this method to fetch large result sets will result in a heavy demand on system and possibly network resources. Rather than retrieving all of the data and manipulating it in PHP, consider using the database server to manipulate the result sets. For example, use the WHERE and SORT BY clauses in SQL to restrict results before retrieving and processing them with PHP.

Examples

Example #1 Fetch all remaining rows in a result set

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

The above example will output:

Fetch all of the remaining rows in the result set:
Array
(
    [0] => Array
        (
            [NAME] => pear
            [0] => pear
            [COLOUR] => green
            [1] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [0] => watermelon
            [COLOUR] => pink
            [1] => pink
        )

)

Example #2 Fetching all values of a single column from a result set

The following example demonstrates how to return all of the values of a single column from a result set, even though the SQL statement itself may return multiple columns per row.

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
?>

The above example will output:

Array(3)
(
    [0] =>
    string(5) => apple
    [1] =>
    string(4) => pear
    [2] =>
    string(10) => watermelon
)

Example #3 Grouping all values by a single column

The following example demonstrates how to return an associative array grouped by the values of the specified column in the result set. The array contains three keys: values apple and pear are returned as arrays that contain two different colours, while watermelon is returned as an array that contains only one colour.

<?php
$insert = $dbh->prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert->execute(array('apple', 'green'));
$insert->execute(array('pear', 'yellow'));

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Group values by the first column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>

The above example will output:

array(3) {
  ["apple"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(3) "red"
  }
  ["pear"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(6) "yellow"
  }
  ["watermelon"]=>
  array(1) {
    [0]=>
    string(5) "green"
  }
}

See Also

  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::setFetchMode() - Set the default fetch mode for this statement

PDOStatement->fetch
PDOStatement->fetchColumn
PDOStatement


Returns a single column from the next row of a result set

PDOStatement->fetchAll
PDOStatement->fetchObject
PDOStatement
PHP Manual

PDOStatement->fetchColumn

(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)

PDOStatement->fetchColumn — Returns a single column from the next row of a result set

Description

string PDOStatement::fetchColumn ([ int $column_number = 0 ] )

Returns a single column from the next row of a result set or FALSE if there are no more rows.

Parameters

column_number

0-indexed number of the column you wish to retrieve from the row. If no value is supplied, PDOStatement::fetchColumn() fetches the first column.

Return Values

PDOStatement::fetchColumn() returns a single column in the next row of a result set.

Warning

There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.

Examples

Example #1 Return first column of the next row

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch the first column from the next row in the result set */
print("Fetch the first column from the next row in the result set:\n");
$result = $sth->fetchColumn();
print("name = $result\n");

print("Fetch the second column from the next row in the result set:\n");
$result = $sth->fetchColumn(1);
print("colour = $result\n");
?>

The above example will output:

Fetch the first column from the next row in the result set:
name = lemon
Fetch the second column from the next row in the result set:
colour = red

See Also

  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchAll() - Returns an array containing all of the result set rows
  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::setFetchMode() - Set the default fetch mode for this statement

PDOStatement->fetchAll
PDOStatement->fetchObject
PDOStatement


Fetches the next row and returns it as an object.

PDOStatement->fetchColumn
PDOStatement->getAttribute
PDOStatement
PHP Manual

PDOStatement->fetchObject

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.4)

PDOStatement->fetchObject — Fetches the next row and returns it as an object.

Description

mixed PDOStatement::fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )

Fetches the next row and returns it as an object. This function is an
alternative to PDOStatement::fetch() with
PDO::FETCH_CLASS or
PDO::FETCH_OBJ style.

Parameters

class_name

Name of the created class.

ctor_args

Elements of this array are passed to the constructor.

Return Values

Returns an instance of the required class with property names that correspond to the column names or FALSE on failure.

See Also

  • PDOStatement::fetch() - Fetches the next row from a result set

PDOStatement->fetchColumn
PDOStatement->getAttribute
PDOStatement


Retrieve a statement attribute

PDOStatement->fetchObject
PDOStatement->getColumnMeta
PDOStatement
PHP Manual

PDOStatement->getAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement->getAttribute — Retrieve a statement attribute

Description

mixed PDOStatement::getAttribute ( int $attribute )

Gets an attribute of the statement. Currently, no generic attributes exist but only driver specific:

  • PDO::ATTR_CURSOR_NAME (Firebird and ODBC specific): Get the name of cursor for UPDATE ... WHERE CURRENT OF.

Return Values

Returns the attribute value.

See Also

  • PDO::getAttribute() - Retrieve a database connection attribute
  • PDO::setAttribute() - Set an attribute
  • PDOStatement::setAttribute() - Set a statement attribute

PDOStatement->fetchObject
PDOStatement->getColumnMeta
PDOStatement


Returns metadata for a column in a result set

PDOStatement->getAttribute
PDOStatement->nextRowset
PDOStatement
PHP Manual

PDOStatement->getColumnMeta

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement->getColumnMeta — Returns metadata for a column in a result set

Description

array PDOStatement::getColumnMeta ( int $column )
Warning

This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.

Retrieves the metadata for a 0-indexed column in a result set as an associative array.

Warning

Not all PDO drivers support PDOStatement::getColumnMeta().

Parameters

column

The 0-indexed column in the result set.

Return Values

Returns an associative array containing the following values representing the metadata for a single column:

Column metadata
Name | Value
native_type | The PHP native type used to represent the column value.
driver:decl_type | The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement::getColumnMeta().
flags | Any flags set for this column.
name | The name of this column as returned by the database.
table | The name of this column's table as returned by the database.
len | The length of this column. Normally -1 for types other than floating point decimals.
precision | The numeric precision of this column. Normally 0 for types other than floating point decimals.
pdo_type | The type of this column as represented by the PDO::PARAM_* constants.

Returns FALSE if the requested column does not exist in the result set, or if no result set exists.

Changelog

Version | Description
5.2.3 | table field

Examples

Example #1 Retrieving column metadata

The following example shows the results of retrieving the metadata for a single column generated by a function (COUNT) in a PDO_SQLITE driver.

<?php
$select = $DB->query('SELECT COUNT(*) FROM fruit');
$meta = $select->getColumnMeta(0);
var_dump($meta);
?>

The above example will output:

array(6) {
  ["native_type"]=>
  string(7) "integer"
  ["flags"]=>
  array(0) {
  }
  ["name"]=>
  string(8) "COUNT(*)"
  ["len"]=>
  int(-1)
  ["precision"]=>
  int(0)
  ["pdo_type"]=>
  int(2)
}

See Also

  • PDOStatement::columnCount() - Returns the number of columns in the result set
  • PDOStatement::rowCount() - Returns the number of rows affected by the last SQL statement

PDOStatement->getAttribute
PDOStatement->nextRowset
PDOStatement


Advances to the next rowset in a multi-rowset statement handle

PDOStatement->getColumnMeta
PDOStatement->rowCount
PDOStatement
PHP Manual

PDOStatement->nextRowset

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement->nextRowset — Advances to the next rowset in a multi-rowset statement handle

Description

bool PDOStatement::nextRowset ( void )

Some database servers support stored procedures that return more than one rowset (also known as a result set). PDOStatement::nextRowset() enables you to access the second and subsequent rowsets associated with a PDOStatement object. Each rowset can have a different set of columns from the preceding rowset.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Fetching multiple rowsets returned from a stored procedure

The following example shows how to call a stored procedure, MULTIPLE_ROWSETS, that returns three rowsets. We use a do / while loop to loop over the PDOStatement::nextRowset() method, which returns false and terminates the loop when no more rowsets can be returned.

<?php
$sql = 'CALL multiple_rowsets()';
$stmt = $conn->query($sql);
$i = 1;
do {
    $rowset = $stmt->fetch(PDO::FETCH_NUM);
    if ($rowset) {
        printResultSet($rowset, $i);
    }
    $i++;
} while ($stmt->nextRowset());

function printResultSet(&$rowset, $i) {
    print "Result set $i:\n";
    foreach ($rowset as $row) {
        foreach ($row as $col) {
            print $col . "\t";
        }
        print "\n";
    }
    print "\n";
}
?>

The above example will output:

Result set 1:
apple    red
banana   yellow

Result set 2:
orange   orange    150
banana   yellow    175

Result set 3:
lime     green
apple    red
banana   yellow

See Also

  • PDOStatement::columnCount() - Returns the number of columns in the result set
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::getColumnMeta() - Returns metadata for a column in a result set
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object

PDOStatement->getColumnMeta
PDOStatement->rowCount
PDOStatement


Returns the number of rows affected by the last SQL statement

PDOStatement->nextRowset
PDOStatement->setAttribute
PDOStatement
PHP Manual

PDOStatement->rowCount

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement->rowCount — Returns the number of rows affected by the last SQL statement

Description

int PDOStatement::rowCount ( void )

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

Return Values

Returns the number of rows.

Examples

Example #1 Return the number of deleted rows

PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.

<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();

/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>

The above example will output:

Deleted 9 rows.

Example #2 Counting rows returned by a SELECT statement

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {

    /* Check the number of rows that match the SELECT statement */
  if ($res->fetchColumn() > 0) {

        /* Issue the real SELECT statement and work with the results */
         $sql = "SELECT name FROM fruit WHERE calories > 100";
       foreach ($conn->query($sql) as $row) {
           print "Name: " .  $row['NAME'] . "\n";
         }
    }
    /* No rows matched -- do something else */
  else {
      print "No rows matched the query.";
    }
}

$res = null;
$conn = null;
?>

The above example will output:

apple
banana
orange
pear

See Also

  • PDOStatement::columnCount() - Returns the number of columns in the result set
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object

PDOStatement->nextRowset
PDOStatement->setAttribute
PDOStatement


Set a statement attribute

PDOStatement->rowCount
PDOStatement->setFetchMode
PDOStatement
PHP Manual

PDOStatement->setAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement->setAttribute — Set a statement attribute

Description

bool PDOStatement::setAttribute ( int $attribute , mixed $value )

Sets an attribute on the statement. Currently, no generic attributes are set but only driver specific:

  • PDO::ATTR_CURSOR_NAME (Firebird and ODBC specific): Set the name of cursor for UPDATE ... WHERE CURRENT OF.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • PDO::getAttribute() - Retrieve a database connection attribute
  • PDO::setAttribute() - Set an attribute
  • PDOStatement::getAttribute() - Retrieve a statement attribute

PDOStatement->rowCount
PDOStatement->setFetchMode
PDOStatement


Set the default fetch mode for this statement

PDOStatement->setAttribute
PDOException
PDOStatement
PHP Manual

PDOStatement->setFetchMode

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement->setFetchMode — Set the default fetch mode for this statement

Description

bool PDOStatement::setFetchMode ( int $mode )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_COLUMN , int $colno )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_INTO , object $object )

Parameters

mode

The fetch mode must be one of the PDO::FETCH_* constants.

colno

Column number.

classname

Class name.

ctorargs

Constructor arguments.

object

Object.

Return Values

Returns 1 on success or FALSE on failure.

Examples

Example #1 Setting the fetch mode

The following example demonstrates how PDOStatement::setFetchMode() changes the default fetch mode for a PDOStatement object.

<?php
$sql = 'SELECT name, colour, calories FROM fruit';
try {
  $stmt = $dbh->query($sql);
  $result = $stmt->setFetchMode(PDO::FETCH_NUM);
  while ($row = $stmt->fetch()) {
    print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
  }
}
catch (PDOException $e) {
  print $e->getMessage();
}
?>

The above example will output:

apple   red     150
banana  yellow  250
orange  orange  300
kiwi    brown   75
lemon   yellow  25
pear    green   150
watermelon      pink    90

PDOStatement->setAttribute
PDOException
PDOStatement


Constants for Options

The functions kadm5_create_principal(),
kadm5_modify_principal(), and
kadm5_get_principal() allow to specify or return
principal's options as an associative array. The keys for the associative
array are defined as string constants below:

Options for creating/modifying/retrieving principals
constant | funcdef | description
KADM5_PRINCIPAL | long | The expire time of the princial as a Kerberos timestamp.
KADM5_PRINC_EXPIRE_TIME | long | The expire time of the princial as a Kerberos timestamp.
KADM5_LAST_PW_CHANGE | long | The time this principal's password was last changed.
KADM5_PW_EXPIRATION | long | The expire time of the principal's current password, as a Kerberos timestamp.
KADM5_MAX_LIFE | long | The maximum lifetime of any Kerberos ticket issued to this principal.
KADM5_MAX_RLIFE | long | The maximum renewable lifetime of any Kerberos ticket issued to or for this principal.
KADM5_MOD_NAME | string | The name of the Kerberos principal that most recently modified this principal.
KADM5_MOD_TIME | long | The time this principal was last modified, as a Kerberos timestamp.
KADM5_KVNO | long | The version of the principal's current key.
KADM5_POLICY | string | The name of the policy controlling this principal.
KADM5_CLEARPOLICY | long | Standard procedure is to assign the 'default' policy to new principals. KADM5_CLEARPOLICY suppresses this behaviour.
KADM5_LAST_SUCCESS | long | The KDC time of the last successfull AS_REQ.
KADM5_LAST_FAILED | long | The KDC time of the last failed AS_REQ.
KADM5_FAIL_AUTH_COUNT | long | The number of consecutive failed AS_REQs.
KADM5_RANDKEY | long | Generates a random password for the principal. The parameter password will be ignored.
KADM5_ATTRIBUTES | long | A bitfield of attributes for use by the KDC.

Constants for Attribute Flags
Examples
Predefined Constants


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PostgreSQL configuration options
Name | Default | Changeable | Changelog
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.2.0.
pgsql.ignore_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
pgsql.log_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

pgsql.allow_persistent boolean

Whether to allow persistent Postgres connections.

pgsql.max_persistent integer

The maximum number of persistent Postgres connections per process.

pgsql.max_links integer

The maximum number of Postgres connections per process, including persistent connections.

pgsql.auto_reset_persistent integer

Detect broken persistent links with pg_pconnect(). Needs a little overhead.

pgsql.ignore_notice integer

Whether or not to ignore PostgreSQL backend notices.

pgsql.log_notice integer

Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

PGSQL_ASSOC (integer)
Passed to pg_fetch_array(). Return an associative array of field names and values.
PGSQL_NUM (integer)
Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.
PGSQL_BOTH (integer)
Passed to pg_fetch_array(). Return an array of field values that is both numerically indexed (by field number) and associated (by field name).
PGSQL_CONNECT_FORCE_NEW (integer)
Passed to pg_connect() to force the creation of a new connection, rather then re-using an existing identical connection.
PGSQL_CONNECTION_BAD (integer)
Returned by pg_connection_status() indicating that the database connection is in an invalid state.
PGSQL_CONNECTION_OK (integer)
Returned by pg_connection_status() indicating that the database connection is in a valid state.
PGSQL_SEEK_SET (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.
PGSQL_SEEK_CUR (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the current position.
PGSQL_SEEK_END (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.
PGSQL_EMPTY_QUERY (integer)
Returned by pg_result_status(). The string sent to the server was empty.
PGSQL_COMMAND_OK (integer)
Returned by pg_result_status(). Successful completion of a command returning no data.
PGSQL_TUPLES_OK (integer)
Returned by pg_result_status(). Successful completion of a command returning data (such as a SELECT or SHOW).
PGSQL_COPY_OUT (integer)
Returned by pg_result_status(). Copy Out (from server) data transfer started.
PGSQL_COPY_IN (integer)
Returned by pg_result_status(). Copy In (to server) data transfer started.
PGSQL_BAD_RESPONSE (integer)
Returned by pg_result_status(). The server's response was not understood.
PGSQL_NONFATAL_ERROR (integer)
Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.
PGSQL_FATAL_ERROR (integer)
Returned by pg_result_status(). A fatal error occurred.
PGSQL_TRANSACTION_IDLE (integer)
Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.
PGSQL_TRANSACTION_ACTIVE (integer)
Returned by pg_transaction_status(). A command is in progress on the connection. A query has been sent via the connection and not yet completed.
PGSQL_TRANSACTION_INTRANS (integer)
Returned by pg_transaction_status(). The connection is idle, in a transaction block.
PGSQL_TRANSACTION_INERROR (integer)
Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.
PGSQL_TRANSACTION_UNKNOWN (integer)
Returned by pg_transaction_status(). The connection is bad.
PGSQL_DIAG_SEVERITY (integer)
Passed to pg_result_error_field(). The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these. Always present.
PGSQL_DIAG_SQLSTATE (integer)
Passed to pg_result_error_field(). The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. This field is not localizable, and is always present.
PGSQL_DIAG_MESSAGE_PRIMARY (integer)
Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.
PGSQL_DIAG_MESSAGE_DETAIL (integer)
Passed to pg_result_error_field(). Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.
PGSQL_DIAG_MESSAGE_HINT (integer)
Passed to pg_result_error_field(). Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. May run to multiple lines.
PGSQL_DIAG_STATEMENT_POSITION (integer)
Passed to pg_result_error_field(). A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes.
PGSQL_DIAG_INTERNAL_POSITION (integer)
Passed to pg_result_error_field(). This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears.
PGSQL_DIAG_INTERNAL_QUERY (integer)
Passed to pg_result_error_field(). The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.
PGSQL_DIAG_CONTEXT (integer)
Passed to pg_result_error_field(). An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.
PGSQL_DIAG_SOURCE_FILE (integer)
Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_LINE (integer)
Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_FUNCTION (integer)
Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.
PGSQL_ERRORS_TERSE (integer)
Passed to pg_set_error_verbosity(). Specified that returned messages include severity, primary text, and position only; this will normally fit on a single line.
PGSQL_ERRORS_DEFAULT (integer)
Passed to pg_set_error_verbosity(). The default mode produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines).
PGSQL_ERRORS_VERBOSE (integer)
Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.
PGSQL_STATUS_LONG (integer)
Passed to pg_result_status(). Indicates that numerical result code is desired.
PGSQL_STATUS_STRING (integer)
Passed to pg_result_status(). Indicates that textual result command tag is desired.
PGSQL_CONV_IGNORE_DEFAULT (integer)
Passed to pg_convert(). Ignore default values in the table during conversion.
PGSQL_CONV_FORCE_NULL (integer)
Passed to pg_convert(). Use SQL NULL in place of an empty string.
PGSQL_CONV_IGNORE_DEFAULT (integer)
Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.
Resource Types
Examples
PostgreSQL


Examples

Table of Contents

  • PostgreSQL extension overview example
Predefined Constants
PostgreSQL extension overview example
PostgreSQL


PostgreSQL extension overview example

Examples
PostgreSQL Functions
Examples
PHP Manual

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a PostgreSQL database.

Example #1 PostgreSQL extension overview example

<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
    or die('Could not connect: ' . pg_last_error());

// Performing SQL query
$query = 'SELECT * FROM authors';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());

// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

// Free resultset
pg_free_result($result);

// Closing connection
pg_close($dbconn);
?>

Examples
PostgreSQL Functions
Examples


Installation

In order to enable PostgreSQL support, --with-pgsql[=DIR] is required when you compile PHP. DIR is the PostgreSQL base install directory, defaults to /usr/local/pgsql. If shared object module is available, PostgreSQL module may be loaded using extension directive in php.ini or dl() function.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To use PostgreSQL support, you need PostgreSQL 6.5 or later, PostgreSQL 8.0 or later to enable all PostgreSQL module features. PostgreSQL supports many character encodings including multibyte character encoding. The current version and more information about PostgreSQL is available at » http://www.postgresql.org/ and the » PostgreSQL Documentation.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

There are two resource types used in the PostgreSQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
PostgreSQL


Add an empty directory to the phar archive

Phar
Phar::addFile
Phar
PHP Manual

Phar::addEmptyDir

(Unknown)

Phar::addEmptyDir — Add an empty directory to the phar archive

Description

void Phar::addEmptyDir ( string $dirname )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().

Parameters

dirname

The name of the empty directory to create in the phar archive

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A Phar::addEmptyDir() example

<?php
try {
    $a = new Phar('/path/to/phar.phar');

    $a->addEmptyDir('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive
  • Phar::addFile() - Add a file from the filesystem to the phar archive
  • Phar::addFromString() - Add a file from the filesystem to the phar archive

Phar
Phar::addFile
Phar


Add a file from the filesystem to the phar archive

Phar::addEmptyDir
Phar::addFromString
Phar
PHP Manual

Phar::addFile

(Unknown)

Phar::addFile — Add a file from the filesystem to the phar archive

Description

void Phar::addFile ( string $file [, string $localname ] )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

With this method, any file or URL can be added to the phar archive. If the optional second parameter localname is specified, the file will be stored in the archive with that name, otherwise the file parameter is used as the path to store within the archive. URLs must have a localname or an exception is thrown. This method is similar to ZipArchive::addFile().

Parameters

file

Full or relative path to a file on disk to be added to the phar archive.

localname

Path that the file will be stored in the archive.

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A Phar::addFile() example

<?php
try {
    $a = new Phar('/path/to/phar.phar');

    $a->addFile('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->getContent();

    $a->addFile('/full/path/to/file', 'my/file.txt');
    $c = $a['my/file.txt']->getContent();

    // demonstrate URL usage
    $a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • Phar::addFromString() - Add a file from the filesystem to the phar archive
  • Phar::addEmptyDir() - Add an empty directory to the phar archive

Phar::addEmptyDir
Phar::addFromString
Phar


Add a file from the filesystem to the phar archive

Phar::addFile
Phar::apiVersion
Phar
PHP Manual

Phar::addFromString

(Unknown)

Phar::addFromString — Add a file from the filesystem to the phar archive

Description

void Phar::addFromString ( string $localname , string $contents )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

With this method, any string can be added to the phar archive. The file will be stored in the archive with localname as its path. This method is similar to ZipArchive::addFromString().

Parameters

localname

Path that the file will be stored in the archive.

contents

The file contents to store

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A Phar::addFromString() example

<?php
try {
    $a = new Phar('/path/to/phar.phar');

    $a->addFromString('path/to/file.txt', 'my simple file');
    $b = $a['path/to/file.txt']->getContent();

    // to add contents from a stream handle for large files, use offsetSet()
    $c = fopen('/path/to/hugefile.bin');
    $a['largefile.bin'] = $c;
    fclose($c);
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • PharData::addFromString() - Add a file from the filesystem to the tar/zip archive
  • Phar::addFile() - Add a file from the filesystem to the phar archive
  • Phar::addEmptyDir() - Add an empty directory to the phar archive

Phar::addFile
Phar::apiVersion
Phar


Returns the api version

Phar::addFromString
Phar::buildFromDirectory
Phar
PHP Manual

Phar::apiVersion

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::apiVersion — Returns the api version

Description

string Phar::apiVersion ( void )

Return the API version of the phar file format that will be used when creating phars. The Phar extension supports reading API version 1.0.0 or newer. API version 1.1.0 is required for SHA-256 and SHA-512 hash, and API version 1.1.1 is required to store empty directories.

Parameters

Return Values

The API version string as in "1.0.0".

Examples

Example #1 A Phar::apiVersion() example

<?php
echo Phar::apiVersion();
?>

The above example will output:

1.1.1

Phar::addFromString
Phar::buildFromDirectory
Phar


Construct a phar archive from the files within a directory.

Phar::apiVersion
Phar::buildFromIterator
Phar
PHP Manual

Phar::buildFromDirectory

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::buildFromDirectory — Construct a phar archive from the files within a directory.

Description

array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Populate a phar archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use Phar::buildFromIterator().

Parameters

base_dir

The full or relative path to the directory that contains all files to add to the archive.

regex

An optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.

Return Values

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Errors/Exceptions

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

Examples

Example #1 A Phar::buildFromDirectory() example

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');
$phar->setStub($phar->createDefaultWebStub('cli/index.php', 'www/index.php'));

$phar2 = new Phar('project2.phar', 0, 'project2.phar');
// add all files in the project, only include php files
$phar->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
$phar->setStub($phar->createDefaultWebStub('cli/index.php', 'www/index.php'));
?>

See Also

  • Phar::buildFromIterator() - Construct a phar archive from an iterator.

Phar::apiVersion
Phar::buildFromIterator
Phar


Construct a phar archive from an iterator.

Phar::buildFromDirectory
Phar::canCompress
Phar
PHP Manual

Phar::buildFromIterator

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::buildFromIterator — Construct a phar archive from an iterator.

Description

array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Populate a phar archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the phar to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.

Parameters

iter

Any iterator that either associatively maps phar file to location or returns SplFileInfo objects

base_directory

For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the phar archive

Return Values

Phar::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Examples

Example #1 A Phar::buildFromIterator() with SplFileInfo

For most phar archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a phar archive containing the files in this sample directory layout:

/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php

This code could be used to add these files to the "project.phar" phar archive:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new RecursiveDirectoryIterator('/path/to/project')),
    '/path/to/project');
$phar->setStub($phar->createDefaultWebStub('cli/index.php', 'www/index.php'));
?>

The file project.phar can then be used immediately. Phar::buildFromIterator() does not set values such as compression, metadata, and this can be done after creating the phar archive.

As an interesting note, Phar::buildFromIterator() can also be used to copy the contents of an existing phar archive, as the Phar object descends from DirectoryIterator:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new Phar('/path/to/anotherphar.phar')),
    'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultWebStub('cli/index.php', 'www/index.php'));
?>

Example #2 A Phar::buildFromIterator() with other iterators

The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
    new ArrayIterator(
     array(
        'internal/file.php' => dirname(__FILE__) . '/somefile.php',
        'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
     )));
$phar->setStub($phar->createDefaultWebStub('cli/index.php', 'www/index.php'));
?>

Errors/Exceptions

This method returns UnexpectedValueException when the iterator returns incorrect values, such as an integer key instead of a string, a BadMethodCallException when an SplFileInfo-based iterator is passed without a base_directory parameter, or a PharException if there were errors saving the phar archive.

See Also

  • Phar::buildFromDirectory() - Construct a phar archive from the files within a directory.

Phar::buildFromDirectory
Phar::canCompress
Phar


Returns whether phar extension supports compression using either zlib or bzip2

Phar::buildFromIterator
Phar::canWrite
Phar
PHP Manual

Phar::canCompress

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2

Description

bool Phar::canCompress ([ int $type = 0 ] )

This should be used to test whether compression is possible prior to loading a phar archive containing compressed files.

Parameters

type

Either Phar::GZ or Phar::BZ2 can be used to test whether compression is possible with a specific compression algorithm (zlib or bzip2).

Return Values

TRUE if compression/decompression is available, FALSE if not.

Examples

Example #1 A Phar::canCompress() example

<?php
if (Phar::canCompress()) {
    echo file_get_contents('phar://compressedphar.phar/internal/file.txt');
} else {
    echo 'no compression available';
}
?>

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file

Phar::buildFromIterator
Phar::canWrite
Phar


Returns whether phar extension supports writing and creating phars

Phar::canCompress
Phar::compress
Phar
PHP Manual

Phar::canWrite

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::canWrite — Returns whether phar extension supports writing and creating phars

Description

bool Phar::canWrite ( void )

This static method determines whether write access has been disabled in the system php.ini via the phar.readonly ini variable.

Parameters

Return Values

TRUE if write access is enabled, FALSE if it is disabled.

Examples

Example #1 A Phar::canWrite() example

<?php
if (Phar::canWrite()) {
    file_put_contents('phar://myphar.phar/file.txt', 'hi there');
}
?>

See Also

  • phar.readonly
  • Phar::isWritable() - Returns true if the phar archive can be modified

Phar::canCompress
Phar::compress
Phar


Compresses the entire Phar archive using Gzip or Bzip2 compression

Phar::canWrite
Phar::compressAllFilesBZIP2
Phar
PHP Manual

Phar::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression

Description

object Phar::compress ( int $compression [, string $extension ] )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based and phar-based phar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.

For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.

Parameters

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

extension

By default, the extension is .phar.gz or .phar.bz2 for compressing phar archives, and .phar.tar.gz or .phar.tar.bz2 for compressing tar archives. For decompressing, the default file extensions are .phar and .phar.tar.

Return Values

Returns a Phar object.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

Examples

Example #1 A Phar::compress() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

Phar::canWrite
Phar::compressAllFilesBZIP2
Phar


Compresses all files in the current Phar archive using Bzip2 compression

Phar::compress
Phar::compressAllFilesGZ
Phar
PHP Manual

Phar::compressAllFilesBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression

Description

bool Phar::compressAllFilesBZIP2 ( void )

Note: This
method has been removed from the phar extension as of version 2.0.0.  Alternative
implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and
Phar::decompressFiles().

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method compresses all files in the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files prior to re-compressing with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not available, or if any files are compressed using gzip compression and the zlib extension is not enabled.

Examples

Example #1 A Phar::compressAllFilesBZIP2() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
$p->compressAllFilesBZIP2();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
?>

The above example will output:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(true)
bool(false)
string(11) "myfile2.txt"
bool(true)
bool(true)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

Phar::compress
Phar::compressAllFilesGZ
Phar


Compresses all files in the current Phar archive using Gzip compression

Phar::compressAllFilesBZIP2
Phar::compressFiles
Phar
PHP Manual

Phar::compressAllFilesGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip compression

Description

bool Phar::compressAllFilesGZ ( void )

Note: This
method has been removed from the phar extension as of version 2.0.0.  Alternative
implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and
Phar::decompressFiles().

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based phar archives, this method compresses the entire archive using gzip compression. The resulting file can be processed with the gunzip command, or accessed directly and transparently with the Phar extension.

For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2 compression, the bzip2 extension must be enabled in order to decompress the files prior to re-compressing with gzip compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Examples

Example #1 A Phar::compressAllFilesGZ() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
$p->compressAllFilesGZ();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
?>

The above example will output:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

Phar::compressAllFilesBZIP2
Phar::compressFiles
Phar


Compresses all files in the current Phar archive

Phar::compressAllFilesGZ
Phar::__construct
Phar
PHP Manual

Phar::compressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::compressFiles — Compresses all files in the current Phar archive

Description

void Phar::compressFiles ( int $compression )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress() to compress an entire tar-based phar archive.

For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Parameters

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

Return Values

No value is returned.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Examples

Example #1 A Phar::compressFiles() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

The above example will output:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive

Phar::compressAllFilesGZ
Phar::__construct
Phar


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Filesystem and Streams Configuration Options
Name | Default | Changeable | Changelog
phar.readonly | "1" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
phar.extract_list | "" | PHP_INI_ALL | Available from phar 1.1.0 to 1.2.3, removed in 2.0.0.
phar.cache_list | "" | PHP_INI_SYSTEM | Available from phar 2.0.0.

Here's a short explanation of the configuration directives.

phar.readonly boolean

This option disables creation or modification of Phar archives using the phar stream or Phar object's write support. This setting should always be enabled on production machines, as the phar extension's convenient write support could allow straightforward creation of a php-based virus when coupled with other common security vulnerabilities.

Note: This setting can only be unset in php.ini due to security reasons. If phar.readonly is disabled in php.ini, the user may enable phar.readonly in a script or disable it later. If phar.readonly is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.

phar.require_hash boolean

This option will force all opened Phar archives to contain some kind of signature (currently MD5, SHA1, SHA256 and SHA512 are supported), and will refuse to process any Phar archive that does not contain a signature.

Note: This setting can only be unset in php.ini due to security reasons. If phar.require_hash is disabled in php.ini, the user may enable phar.require_hash in a script or disable it later. If phar.require_hash is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.
This setting does not affect reading plain tar files with the PharData class.

phar.extract_list string

This INI setting has been removed as of phar 2.0.0

Allows mappings from a full path to a phar archive or its alias to the location of its extracted files. The format of the parameter is name=archive,name2=archive2. This allows extraction of phar files to disk, and allows phar to act as a kind of mapper to extracted disk files. This is often done for performance reasons, or to assist with debugging a phar.

Example #1 phar.extract_list usage example

in php.ini:
phar.extract_list = archive=/full/path/to/archive/,arch2=/full/path/to/arch2
<?php
include "phar://archive/content.php";
include "phar://arch2/foo.php";
?>

phar.cache_list string

This INI setting was added in phar 2.0.0

Allows mapping phar archives to be pre-parsed at web server startup, providing a performance improvement that brings running files out of a phar archive very close to the speed of running those files from a traditional disk-based installation.

Example #2 phar.cache_list usage example

in php.ini (windows):
phar.cache_list =C:\path\to\phar1.phar;C:\path\to\phar2.phar
in php.ini (unix):
phar.cache_list =/path/to/phar1.phar:/path/to/phar2.phar

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Phar compression constants
Constant | Value | Description
Phar::NONE (integer) | 0x00000000 | no compression
Phar::COMPRESSED (integer) | 0x0000F000 | bitmask that can be used with file flags to determine if any compression is present
Phar::GZ (integer) | 0x00001000 | zlib (gzip) compression
Phar::BZ2 (integer) | 0x00002000 | bzip2 compression
Phar file format constants
Constant | Value | Description
Phar::SAME (integer) | 0 | retain the same file format
Phar::PHAR (integer) | 1 | phar file format
Phar::TAR (integer) | 2 | tar file format
Phar::ZIP (integer) | 3 | zip file format
Phar signature constants
Constant | Value | Description
Phar::MD5 (integer) | 0x0001 | signature with md5 hash algorithm
Phar::SHA1 (integer) | 0x0002 | signature with sha1 hash algorithm
Phar::SHA256 (integer) | 0x0003 | signature with sha256 hash algorithm (requires hash extension)
Phar::SHA512 (integer) | 0x0004 | signature with sha512 hash algorithm (requires hash extension)
Phar::OPENSSL (integer) | 0x0010 | signature with OpenSSL public/private key pair. This is a true, asymmetric key signature.
Phar webPhar mime override constants
Constant | Value | Description
Phar::PHP (integer) | 1 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP file
Phar::PHPS (integer) | 2 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP source file through highlight_file()
Resource Types
Using Phar Archives
Phar


Construct a Phar archive object

Phar::compressFiles
Phar::convertToData
Phar
PHP Manual

Phar::__construct

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::__construct — Construct a Phar archive object

Description

void Phar::__construct ( string $fname [, int $flags [, string $alias ]] )

Parameters

fname

Path to an existing Phar archive or to-be-created archive

flags

Flags to pass to parent class RecursiveDirectoryIterator.

alias

Alias with which this Phar archive should be referred to in calls to stream functionality.

Errors/Exceptions

Throws BadMethodCallException if called twice, UnexpectedValueException if the phar archive can't be opened.

Examples

Example #1 A Phar::__construct() example

<?php
try {
    $p = new Phar('/path/to/my.phar', CURRENT_AS_FILEINFO | KEY_AS_FILENAME,
                  'my.phar');
} catch (UnexpectedValueException $e) {
    die('Could not open my.phar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}
// this works now
echo file_get_contents('phar://my.phar/example.txt');
// and works as if we had typed
echo file_get_contents('phar:///path/to/my.phar/example.txt');
?>

Phar::compressFiles
Phar::convertToData
Phar


Convert a phar archive to a non-executable tar or zip file

Phar::__construct
Phar::convertToExecutable
Phar
PHP Manual

Phar::convertToData

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::convertToData — Convert a phar archive to a non-executable tar or zip file

Description

PharData Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

This method is used to convert an executable phar archive to either a tar or zip file. To make the tar or zip non-executable, the phar stub and phar alias files are removed from the newly created archive.

If no changes are specified, this method throws a BadMethodCallException if the archive is in phar file format. For archives in tar or zip file format, this method converts the archive to a non-executable archive.

If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parameters

format

This should be one of Phar::TAR or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.

If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.

Return Values

The method returns a PharData object on success and throws an exception on failure.

Errors/Exceptions

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), and a PharException if any problems are encountered during the phar creation process.

Examples

Example #1 A Phar::convertToData() example

Using Phar::convertToData():

<?php
try {
    $tarphar = new Phar('myphar.phar.tar');
    // note that myphar.phar.tar is *not* unlinked
    // convert it to the non-executable tar file format
    // creates myphar.tar
    $tar = $tarphar->convertToData();
    // convert to non-executable zip format, creates myphar.zip
    $zip = $tarphar->convertToData(Phar::ZIP);
    // create myphar.tbz
    $tgz = $tarphar->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
    // creates myphar.phar.tgz
    $phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
    // handle the error here
}
?>

See Also

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

Phar::__construct
Phar::convertToExecutable
Phar


Convert a phar archive to another executable phar archive file format

Phar::convertToData
Phar::copy
Phar
PHP Manual

Phar::convertToExecutable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format

Description

Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method is used to convert a phar archive to another file format. For instance, it can be used to create a tar-based executable phar archive from a zip-based executable phar archive, or from an executable phar archive in the phar file format. In addition, it can be used to apply whole-archive compression to a tar or phar-based archive.

If no changes are specified, this method throws a BadMethodCallException.

If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parameters

format

This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.

If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.

Return Values

The method returns a Phar object on success and throws an exception on failure.

Errors/Exceptions

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.

Examples

Example #1 A Phar::convertToExecutable() example

Using Phar::convertToExecutable():

<?php
try {
    $tarphar = new Phar('myphar.phar.tar');
    // convert it to the phar file format
    // note that myphar.phar.tar is *not* unlinked
    $phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
    $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
    // creates myphar.phar.tgz
    $compressed = $phar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
    // handle the error here
}
?>

See Also

  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

Phar::convertToData
Phar::copy
Phar


Copy a file internal to the phar archive to another new file within the phar

Phar::convertToExecutable
Phar::count
Phar
PHP Manual

Phar::copy

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::copy — Copy a file internal to the phar archive to another new file within the phar

Description

bool Phar::copy ( string $oldfile , string $newfile )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Copy a file internal to the phar archive to another new file within the phar. This is an object-oriented alternative to using copy() with the phar stream wrapper.

Parameters

oldfile

newfile

Return Values

returns TRUE on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

Errors/Exceptions

throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.

Examples

Example #1 A Phar::copy() example

This example shows using Phar::copy() and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All Phar methods throw exceptions, whereas the stream wrapper uses trigger_error().

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar['a'] = 'hi';
    $phar->copy('a', 'b');
    echo $phar['b']; // outputs "hi"
} catch (Exception $e) {
    // handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.phar/a', 'phar//myphar.phar/c');
echo file_get_contents('phar://myphar.phar/c'); // outputs "hi"
?>

Phar::convertToExecutable
Phar::count
Phar


Returns the number of entries (files) in the Phar archive

Phar::copy
Phar::createDefaultStub
Phar
PHP Manual

Phar::count

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::count — Returns the number of entries (files) in the Phar archive

Description

int Phar::count ( void )

Parameters

Return Values

The number of files contained within this phar, or 0 (the number zero) if none.

Examples

Example #1 A Phar::count() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
    echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p['file.txt'] = 'hi';
echo 'The new phar has ' . $p->count() . " entries\n";
?>

The above example will output:

The new phar has 0 entries
The new phar has 1 entries

Phar::copy
Phar::createDefaultStub
Phar


Create a phar-file format specific stub

Phar::count
Phar::decompress
Phar
PHP Manual

Phar::createDefaultStub

(Unknown)

Phar::createDefaultStub — Create a phar-file format specific stub

Description

string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )

This method is intended for creation of phar-file format-specific stubs, and is not intended for use with tar- or zip-based phar archives.

Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:

<?php
include 'myphar.phar';
?>

or by simple execution:

php myphar.phar

This method provides a simple and easy method to create a stub that will run a startup file from the phar archive. In addition, different files can be specified for running the phar archive from the command line versus through a web server. The loader stub also calls Phar::interceptFileFuncs() to allow easy bundling of a PHP application that accesses the file system. If the phar extension is not present, the loader stub will extract the phar archive to a temporary directory and then operate on the files. A shutdown function erases the temporary files on exit.

Return Values

Returns a string containing the contents of a customized bootstrap loader (stub) that allows the created Phar archive to work with or without the Phar extension enabled.

Errors/Exceptions

Throws UnexpectedValueException if either parameter is longer than 400 bytes.

Examples

Example #1 A Phar::createDefaultStub() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar archive

Phar::count
Phar::decompress
Phar


Creating Phar Archives

Table of Contents

  • Creating Phar Archives: Introduction
Using Phar Archives: the Phar and PharData class
Creating Phar Archives: Introduction
Phar


Creating Phar Archives: Introduction

To be written fully in the near future. Before reading this, be sure to read How to use Phar Archives.

A great place to start is by reading about Phar::buildFromIterator(), and the specifics of the file format choices available for archives. A healthy understanding of what a stub is and does is crucial to phar archive creation, and so Phar::setStub() and Phar::createDefaultStub() are good places to start as well. If you are distributing a web-based application, it is crucial to know about Phar::webPhar() and related method Phar::mungServer(). Any application that accesses its own files should also consider using Phar::interceptFileFuncs().

Creating Phar Archives
What makes a phar a phar and not a tar or a zip?
Creating Phar Archives


Decompresses the entire Phar archive

Phar::createDefaultStub
Phar::decompressFiles
Phar
PHP Manual

Phar::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::decompress — Decompresses the entire Phar archive

Description

object Phar::decompress ([ string $extension ] )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based and phar-based phar archives, this method decompresses the entire archive.

For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

In addition, this method automatically changes the file extension of the archive, .phar by default for phar archives, or .phar.tar for tar-based phar archives. Alternatively, a file extension may be specified with the second parameter.

Parameters

extension

For decompressing, the default file extensions are .phar and .phar.tar. Use this parameter to specify another file extension. Be aware that all executable phar archives must contain .phar in their filename.

Return Values

A Phar object is returned.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

Examples

Example #1 A Phar::decompress() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar.gz');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p3 = $p2->decompress(); // creates /path/to/my.phar
?>

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

Phar::createDefaultStub
Phar::decompressFiles
Phar


Decompresses all files in the current Phar archive

Phar::decompress
Phar::delMetadata
Phar
PHP Manual

Phar::decompressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::decompressFiles — Decompresses all files in the current Phar archive

Description

bool Phar::decompressFiles ( void )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress() to compress an entire tar-based phar archive.

For Zip-based and phar-based phar archives, this method decompresses all files in the Phar archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Examples

Example #1 A Phar::decompressFiles() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

The above example will output:

string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive

Phar::decompress
Phar::delMetadata
Phar


Delete a file within a phar archive

Phar::delMetadata
Phar::extractTo
Phar
PHP Manual

Phar::delete

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::delete — Delete a file within a phar archive

Description

bool Phar::delete ( string $entry )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Delete a file within an archive. This is the functional equivalent of calling unlink() on the stream wrapper equivalent, as shown in the example below.

Parameters

entry

Path within an archive to the file to delete.

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A Phar::delete() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->delete('unlink/me.php');
    // this is equivalent to:
    unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • PharData::delete() - Delete a file within a tar/zip archive
  • Phar::unlinkArchive() - Completely remove a phar archive from disk and from memory

Phar::delMetadata
Phar::extractTo
Phar


Deletes the global metadata of the phar

Phar::decompressFiles
Phar::delete
Phar
PHP Manual

Phar::delMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::delMetadata — Deletes the global metadata of the phar

Description

bool Phar::delMetadata ( void )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Deletes the global metadata of the phar

Parameters

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A Phar::delMetaData() example

<?php
try {
    $phar = new Phar('myphar.phar');
    var_dump($phar->getMetadata());
    $phar->setMetadata("hi there");
    var_dump($phar->getMetadata());
    $phar->delMetadata();
    var_dump($phar->getMetadata());
} catch (Exception $e) {
    // handle errors
}
?>

The above example will output:

NULL
string(8) "hi there"
NULL

See Also

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data

Phar::decompressFiles
Phar::delete
Phar


Extract the contents of a phar archive to a directory

Phar::delete
Phar::getMetaData
Phar
PHP Manual

Phar::extractTo

(Unknown)

Phar::extractTo — Extract the contents of a phar archive to a directory

Description

bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Extract all files within a phar archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo().

Parameters

pathto

Path within an archive to the file to delete.

files

The name of a file or directory to extract, or an array of files/directories to extract

overwrite

Set to TRUE to enable overwriting existing files

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A Phar::extractTo() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->extractTo('/full/path'); // extract all files
    $phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
    $phar->extractTo('/this/path',
        array('file1.txt', 'file2.txt')); // extract 2 files only
    $phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • PharData::extractTo() - Extract the contents of a tar/zip archive to a directory

Phar::delete
Phar::getMetaData
Phar


What makes a phar a phar and not a tar or a zip?

Table of Contents

  • Ingredients of all Phar archives, independent of file format
  • Phar file stub
  • Head-to-head comparison of Phar, Tar and Zip
  • Tar-based phars
  • Zip-based phars
  • Phar File Format
  • Global Phar bitmapped flags
  • Phar manifest file entry definition
  • Phar Signature format
Creating Phar Archives: Introduction
Ingredients of all Phar archives, independent of file format
Phar


Head-to-head comparison of Phar, Tar and Zip

What are the good and the bad things about the three supported file formats in the phar extension? This table attempts to address that question.

Feature matrix: Phar vs. Tar vs. Zip
Feature | Phar | Tar | Zip
Standard File Format | No | Yes | Yes
Can be executed without the Phar Extension [1] | Yes | No | No
Per-file compression | Yes | No | Yes
Whole-archive compression | Yes | Yes | No
Whole-archive signature validation | Yes | Yes | Yes (PHP 5.3.1+)
Web-specific application support | Yes | Yes | Yes
Per-file Meta-data | Yes | Yes | Yes
Whole-Archive Meta-data | Yes | Yes | Yes
Archive creation/modification [2] | Yes | Yes | Yes
Full support for all stream wrapper functions | Yes | Yes | Yes
Can be created/modified even if phar.readonly=1 [3] | No | Yes | Yes

Tip

[1] PHP can only directly access the contents of a Phar archive without the Phar extension if it is using a stub that extracts the contents of the phar archive. The stub created by Phar::createDefaultStub() extracts the phar archive and runs its contents from a temporary directory if no phar extension is found.

Tip

[2] All write access requires phar.readonly to be disabled in php.ini or on the command-line directly.

Tip

[3] Only tar and zip archives without .phar in their filename and without an executable stub .phar/stub.php can be created if phar.readonly=1.

Phar file stub
Tar-based phars
What makes a phar a phar and not a tar or a zip?


Global Phar bitmapped flags

Here are the bitmapped flags currently recognized by the Phar extension for the global Phar flat bitmap:

Bitmap values recognized
Value | Description
0x00010000 | If set, this Phar contains a verification signature
0x00001000 | If set, this Phar contains at least 1 file that is compressed with zlib compression
0x00002000 | If set, this Phar contains at least 1 file that is compressed with bzip compression

Phar File Format
Phar manifest file entry definition
What makes a phar a phar and not a tar or a zip?


Ingredients of all Phar archives, independent of file format

All Phar archives contain three to four sections:

  1. a stub

  2. a manifest describing the contents

  3. the file contents

  4. [optional] a signature for verifying Phar integrity (phar file format only)

What makes a phar a phar and not a tar or a zip?
Phar file stub
What makes a phar a phar and not a tar or a zip?


Phar manifest file entry definition

Each file in the manifest contains the following information:

Phar Manifest file entry
Size in bytes | Description
4 bytes | Filename length in bytes
?? | Filename (length specified in previous)
4 bytes | Un-compressed file size in bytes
4 bytes | Unix timestamp of file
4 bytes | Compressed file size in bytes
4 bytes | CRC32 checksum of un-compressed file contents
4 bytes | Bit-mapped File-specific flags
4 bytes | Serialized File Meta-data length (0 for none)
?? | Serialized File Meta-data, stored in serialize() format

Note that as of API version 1.1.1, empty directories are stored as filenames with a trailing slash like my/directory/

The File-specific bitmap values recognized are:

Bitmap values recognized
Value | Description
0x000001FF | These bits are reserved for defining specific file permissions of a file. Permissions are used for fstat() and can be used to recreate desired permissions upon extraction.
0x00001000 | If set, this file is compressed with zlib compression
0x00002000 | If set, this file is compressed with bzip compression

Global Phar bitmapped flags
Phar Signature format
What makes a phar a phar and not a tar or a zip?


Phar File Format

The phar file format is literally laid out as stub/manifest/contents/signature, and stores the crucial information of what is included in the phar archive in its manifest.

The Phar manifest is a highly optimized format that allows per-file specification of file compression, file permissions, and even user-defined meta-data such as file user or group. All values greater than 1 byte are stored in little-endian byte order, with the exception of the API version, which for historical reasons is stored as 3 nibbles in big-endian order.

All unused flags are reserved for future use, and must not be used to store custom information. Use the per-file meta-data facility to store customized information about particular files.

The basic file format of a Phar archive manifest is as follows:

Global Phar manifest format
Size in bytes | Description
4 bytes | Length of manifest in bytes (1 MB limit)
4 bytes | Number of files in the Phar
2 bytes | API version of the Phar manifest (currently 1.0.0)
4 bytes | Global Phar bitmapped flags
4 bytes | Length of Phar alias
?? | Phar alias (length based on previous)
4 bytes | Length of Phar metadata (0 for none)
?? | Serialized Phar Meta-data, stored in serialize() format
at least 24 * number of entries bytes | entries for each file

Zip-based phars
Global Phar bitmapped flags
What makes a phar a phar and not a tar or a zip?


Phar Signature format

Phars containing a signature always have the signature appended to the end of the Phar archive after the loader, manifest, and file contents. The two signature formats supported at this time are MD5 and SHA1.

Signature format
Length in bytes | Description
16 or 20 bytes | The actual signature, 20 bytes for an SHA1 signature, 16 bytes for an MD5 signature, 32 bytes for an SHA256 signature, and 64 bytes for an SHA512 signature.
4 bytes | Signature flags. 0x0001 is used to define an MD5 signature, 0x0002 is used to define an SHA1 signature, 0x0004 is used to define an SHA256 signature, and 0x0008 is used to define an SHA512 signature. The SHA256 and SHA512 signature support was introduced with API version 1.1.0.
4 bytes | Magic GBMB used to define the presence of a signature.

Phar manifest file entry definition
Phar
What makes a phar a phar and not a tar or a zip?


Phar file stub

A Phar's stub is a simple PHP file. The smallest possible stub follows:

<?php __HALT_COMPILER();

A stub must contain as a minimum, the __HALT_COMPILER(); token at its conclusion. Typically, a stub will contain loader functionality like so:

<?php
Phar::mapPhar();
include 'phar://myphar.phar/index.php';
__HALT_COMPILER();

There are no restrictions on the contents of a Phar stub, except for the requirement that it conclude with __HALT_COMPILER();. The closing PHP tag

?>
may be included or omitted, but there can be no more than 1 space between the ; and the close tag
?>
 or the phar extension will be unable to process the Phar archive's manifest.

In a tar or zip-based phar archive, the stub is stored in the .phar/stub.php file. The default stub for phar-based Phar archives contains approximately 7k of code to extract the contents of the phar and execute them. See Phar::createDefaultStub() for more detail.

The phar alias is stored in a tar or zip-based phar archive in the .phar/alias.txt file as plain text.

Ingredients of all Phar archives, independent of file format
Head-to-head comparison of Phar, Tar and Zip
What makes a phar a phar and not a tar or a zip?


Tar-based phars

Archives based on the tar file format follow the more modern USTAR file format. The design of the tar file header makes them more efficient to access than the zip file format, and almost as efficient as the phar file format. File names are limited to 255 bytes, including full path within the phar archive. There is no limit on the number of files within a tar-based phar archive. These archives can fully compressed in gzip or bzip2 format and still be executed by the Phar extension.

To compress an entire archive, use Phar::compress(). To decompress an entire archive, use Phar::decompress().

Head-to-head comparison of Phar, Tar and Zip
Zip-based phars
What makes a phar a phar and not a tar or a zip?


Zip-based phars

Archives based on the zip file format support several features built into the zip file format. Per-file and whole-archive metadata is stored in the zip file comment and zip archive comment as a serialized string. Pre-existing zip comments will be successfully read as a string. Per-file compression read/write is supported with zlib compression, and read access is supported with bzip2 compression. There is no limit on the number of files within a zip-based phar archive. Empty directories are stored in the zip archive as files with a trailing slash like my/directory/

Tar-based phars
Phar File Format
What makes a phar a phar and not a tar or a zip?


Returns phar archive meta-data

Phar::extractTo
Phar::getModified
Phar
PHP Manual

Phar::getMetaData

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getMetaData — Returns phar archive meta-data

Description

mixed Phar::getMetaData ( void )

Retrieve archive meta-data. Meta-data can be any PHP variable that can be serialized.

Parameters

No parameters.

Return Values

any PHP variable that can be serialized and is stored as meta-data for the Phar archive, or NULL if no meta-data is stored.

Examples

Example #1 A Phar::getMetaData() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.php'] = '<?php echo "hello";';
    $p->setMetaData(array('bootstrap' => 'file.php'));
    var_dump($p->getMetaData());
} catch (Exception $e) {
    echo 'Could not modify phar:', $e;
}
?>

The above example will output:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

See Also

  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

Phar::extractTo
Phar::getModified
Phar


Return whether phar was modified

Phar::getMetaData
Phar::getSignature
Phar
PHP Manual

Phar::getModified

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getModified — Return whether phar was modified

Description

bool Phar::getModified ( void )

This method can be used to determine whether a phar has either had an internal file deleted, or contents of a file changed in some way.

Parameters

No parameters.

Return Values

TRUE if the phar has been modified since opened, FALSE if not.

Phar::getMetaData
Phar::getSignature
Phar


Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Phar::getModified
Phar::getStub
Phar
PHP Manual

Phar::getSignature

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Description

array Phar::getSignature ( void )

Returns the verification signature of a phar archive in a hexadecimal string.

Parameters

Return Values

Array with the opened archive's signature in hash key and MD5, SHA-1, SHA-256, SHA-512, or OpenSSL in hash_type. This signature is a hash calculated on the entire phar's contents, and may be used to verify the integrity of the archive. A valid signature is absolutely required of all executable phar archives if the phar.require_hash INI variable is set to true.

Phar::getModified
Phar::getStub
Phar


Return the PHP loader or bootstrap stub of a Phar archive

Phar::getSignature
Phar::getSupportedCompression
Phar
PHP Manual

Phar::getStub

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive

Description

string Phar::getStub ( void )

Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:

<?php
include 'myphar.phar';
?>

or by simple execution:

php myphar.phar

Return Values

Returns a string containing the contents of the bootstrap loader (stub) of the current Phar archive.

Errors/Exceptions

Throws RuntimeException if it is not possible to read the stub from the Phar archive.

Examples

Example #1 A Phar::getStub() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
echo $p->getStub();
echo "==NEXT==\n";
$p->setStub("<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>");
echo $p->getStub();
?>

The above example will output:

<?php __HALT_COMPILER(); ?>
==NEXT==
<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>

See Also

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

Phar::getSignature
Phar::getSupportedCompression
Phar


Return array of supported compression algorithms

Phar::getStub
Phar::getSupportedSignatures
Phar
PHP Manual

Phar::getSupportedCompression

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::getSupportedCompression — Return array of supported compression algorithms

Description

array Phar::getSupportedCompression ( void )

Parameters

No parameters.

Return Values

Returns an array containing any of Phar::GZ or Phar::BZ2, depending on the availability of the zlib extension or the bz2 extension.

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

Phar::getStub
Phar::getSupportedSignatures
Phar


Return array of supported signature types

Phar::getSupportedCompression
Phar::getVersion
Phar
PHP Manual

Phar::getSupportedSignatures

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::getSupportedSignatures — Return array of supported signature types

Description

array Phar::getSupportedSignatures ( void )

Return array of supported signature types

Parameters

No parameters.

Return Values

Returns an array containing any of MD5, SHA-1, SHA-256, SHA-512, or OpenSSL.

See Also

  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
  • Phar::setSignatureAlgorithm() - set the signature algorithm for a phar and apply it. The

Phar::getSupportedCompression
Phar::getVersion
Phar


Return version info of Phar archive

Phar::getSupportedSignatures
Phar::hasMetaData
Phar
PHP Manual

Phar::getVersion

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getVersion — Return version info of Phar archive

Description

string Phar::getVersion ( void )

Returns the API version of an opened Phar archive.

Parameters

Return Values

The opened archive's API version. This is not to be confused with the API version that the loaded phar extension will use to create new phars. Each Phar archive has the API version hard-coded into its manifest. See Phar file format documentation for more information.

See Also

  • Phar::apiVersion() - Returns the api version

Phar::getSupportedSignatures
Phar::hasMetaData
Phar


Returns whether phar has global meta-data

Phar::getVersion
Phar::interceptFileFuncs
Phar
PHP Manual

Phar::hasMetaData

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::hasMetaData — Returns whether phar has global meta-data

Description

bool Phar::hasMetadata ( void )

Returns whether phar has global meta-data set.

Parameters

No parameters.

Return Values

Returns TRUE if meta-data has been set, and FALSE if not.

Examples

Example #1 A Phar::hasMetaData() example

<?php
try {
    $phar = new Phar('myphar.phar');
    var_dump($phar->hasMetadata());
    $phar->setMetadata(array('thing' => 'hi'));
    var_dump($phar->hasMetadata());
    $phar->delMetadata();
    var_dump($phar->hasMetadata());
} catch (Exception $e) {
    // handle error
}
?>

The above example will output:

bool(false)
bool(true)
bool(false)

See Also

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar

Phar::getVersion
Phar::interceptFileFuncs
Phar


Installation

The Phar extension is built into PHP as of PHP version 5.3.0. Phar may be installed via the PECL extension with previous PHP versions, and the » Phar PECL page contains further information and history.

Windows users must include the php_phar.dll file within php.ini to use this extension.

Requirements
Runtime Configuration
Installing/Configuring


instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Phar::hasMetaData
Phar::isBuffering
Phar
PHP Manual

Phar::interceptFileFuncs

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::interceptFileFuncs — instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Description

void Phar::interceptFileFuncs ( void )

instructs phar to intercept fopen(), readfile(), file_get_contents(), opendir(), and all of the stat-related functions. If any of these functions is called from within a phar archive with a relative path, the call is modified to access a file within the phar archive. Absolute paths are assumed to be attempts to load external files from the filesystem.

This function makes it possible to run PHP applications designed to run off of a hard disk as a phar application.

Parameters

No parameters.

Return Values

Examples

Example #1 A Phar::interceptFileFuncs() example

<?php
Phar::interceptFileFuncs();
include 'phar://' . __FILE__ . '/file.php';
?>

Assuming that this phar is at /path/to/myphar.phar and it contains file.php and file2.txt, if file.php contains this code:

Example #2 A Phar::interceptFileFuncs() example

<?php
echo file_get_contents('file2.txt');
?>

Normally PHP would search the current directory for file2.txt, which would translate as the directory of file.php, or the current directory of a command-line user. Phar::interceptFileFuncs() instructs PHP to consider the current directory to be phar:///path/to/myphar.phar/ and so opens phar:///path/to/myphar.phar/file2.txt in the above example code.

Phar::hasMetaData
Phar::isBuffering
Phar


Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

Phar::interceptFileFuncs
Phar::isCompressed
Phar
PHP Manual

Phar::isBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

Description

bool Phar::isBuffering ( void )

This method can be used to determine whether a Phar will save changes to disk immediately, or whether a call to Phar->stopBuffering() is needed to enable saving changes.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Return Values

Returns TRUE if the write operations are being buffer, FALSE otherwise.

Examples

Example #1 A Phar::isBuffering() example

<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p2 = new Phar('existingphar.phar');
$p['file1.txt'] = 'hi';
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>
=2=
<?php
$p->startBuffering();
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
$p->stopBuffering();
?>
=3=
<?php
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>

The above example will output:

bool(false)
bool(false)
=2=
bool(true)
bool(false)
=3=
bool(false)
bool(false)

See Also

  • Phar::startBuffering() - Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::stopBuffering() - Stop buffering write requests to the Phar archive, and save changes to disk

Phar::interceptFileFuncs
Phar::isCompressed
Phar


Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

Phar::isBuffering
Phar::isFileFormat
Phar
PHP Manual

Phar::isCompressed

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

Description

mixed Phar::isCompressed ( void )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on). Zip-based phar archives cannot be compressed as a file, and so this method will always return FALSE if a zip-based phar archive is queried.

Parameters

No parameters.

Return Values

Phar::GZ, Phar::BZ2 or FALSE

Examples

Example #1 A Phar::isCompressed() example

<?php
try {
    $phar1 = new Phar('myphar.zip.phar');
    var_dump($phar1->isCompressed());
    $phar2 = new Phar('myuncompressed.tar.phar');
    var_dump($phar2->isCompressed());
    $phar2->compressAllFilesGZ();
    var_dump($phar2->isCompressed() == Phar::GZ);
} catch (Exception $e) {
}
?>

The above example will output:

bool(false)
bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

Phar::isBuffering
Phar::isFileFormat
Phar


Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

Phar::isCompressed
Phar::isValidPharFilename
Phar
PHP Manual

Phar::isFileFormat

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

Description

bool Phar::isFileFormat ( int $format )

Parameters

format

Either Phar::PHAR, Phar::TAR, or Phar::ZIP to test for the format of the archive.

Return Values

Returns TRUE if the phar archive matches the file format requested by the parameter

Errors/Exceptions

PharException is thrown if the parameter is an unknown file format specifier.

See Also

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file

Phar::isCompressed
Phar::isValidPharFilename
Phar


Returns whether the given filename is a valid phar filename

Phar::isFileFormat
Phar::isWritable
Phar
PHP Manual

Phar::isValidPharFilename

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename

Description

bool Phar::isValidPharFilename ( string $filename [, bool $executable = true ] )

Returns whether the given filename is a valid phar filename that will be recognized as a phar archive by the phar extension. This can be used to test a name without having to instantiate a phar archive and catch the inevitable Exception that will be thrown if an invalid name is specified.

Parameters

filename

The name or full path to a phar archive not yet created

executable

This parameter determines whether the filename should be treated as a phar executable archive, or a data non-executable archive

Return Values

Returns TRUE if the filename is valid, FALSE if not.

Phar::isFileFormat
Phar::isWritable
Phar


Returns true if the phar archive can be modified

Phar::isValidPharFilename
Phar::loadPhar
Phar
PHP Manual

Phar::isWritable

(Unknown)

Phar::isWritable — Returns true if the phar archive can be modified

Description

bool Phar::isWritable ( void )

This method returns TRUE if phar.readonly is 0, and the actual phar archive on disk is not read-only.

Parameters

No parameters.

Return Values

Returns TRUE if the phar archive can be modified

See Also

  • Phar::canWrite() - Returns whether phar extension supports writing and creating phars
  • PharData::isWritable() - Returns true if the tar/zip archive can be modified

Phar::isValidPharFilename
Phar::loadPhar
Phar


Loads any phar archive with an alias

Phar::isWritable
Phar::mapPhar
Phar
PHP Manual

Phar::loadPhar

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::loadPhar — Loads any phar archive with an alias

Description

bool Phar::loadPhar ( string $filename [, string $alias ] )

This can be used to read the contents of an external Phar archive. This is most useful for assigning an alias to a phar so that subsequent references to the phar can use the shorter alias, or for loading Phar archives that only contain data and are not intended for execution/inclusion in PHP scripts.

Parameters

filename

the full or relative path to the phar archive to open

alias

The alias that may be used to refer to the phar archive. Note that many phar archives specify an explicit alias inside the phar archive, and a PharException will be thrown if a new alias is specified in this case.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

PharException is thrown if an alias is passed in and the phar archive already has an explicit alias

Examples

Example #1 A Phar::loadPhar() example

Phar::loadPhar can be used anywhere to load an external Phar archive, whereas Phar::mapPhar should be used in a loader stub for a Phar.

<?php
try {
    Phar::loadPhar('/path/to/phar.phar', 'my.phar');
    echo file_get_contents('phar://my.phar/file.txt');
} catch (PharException $e) {
    echo $e;
}
?>

See Also

  • Phar::mapPhar() - Reads the currently executed file (a phar) and registers its manifest

Phar::isWritable
Phar::mapPhar
Phar


Reads the currently executed file (a phar) and registers its manifest

Phar::loadPhar
Phar::mount
Phar
PHP Manual

Phar::mapPhar

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest

Description

bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )

This static method can only be used inside a Phar archive's loader stub in order to initialize the phar when it is directly executed, or when it is included in another script.

Parameters

alias

The alias that can be used in phar:// URLs to refer to this archive, rather than its full path.

dataoffset

Unused variable, here for compatibility with PEAR's PHP_Archive.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

PharException is thrown if not called directly within PHP execution, if no __HALT_COMPILER(); token is found in the current source file, or if the file cannot be opened for reading.

Examples

Example #1 A Phar::mapPhar() example

mapPhar should be used only inside a phar's loader stub. Use loadPhar to load an external phar into memory.

Here is a sample Phar loader stub that uses mapPhar.

<?php
function __autoload($class)
{
    include 'phar://me.phar/' . str_replace('_', '/', $class) . '.php';
}
try {
    Phar::mapPhar('me.phar');
    include 'phar://me.phar/startup.php';
} catch (PharException $e) {
    echo $e->getMessage();
    die('Cannot initialize Phar');
}
__HALT_COMPILER();

See Also

  • Phar::loadPhar() - Loads any phar archive with an alias

Phar::loadPhar
Phar::mount
Phar


Mount an external path or file to a virtual location within the phar archive

Phar::mapPhar
Phar::mungServer
Phar
PHP Manual

Phar::mount

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::mount — Mount an external path or file to a virtual location within the phar archive

Description

void Phar::mount ( string $pharpath , string $externalpath )

Much like the unix file system concept of mounting external devices to paths within the directory tree, Phar::mount() allows referring to external files and directories as if they were inside of an archive. This allows powerful abstraction such as referring to external configuration files as if they were inside the archive.

Parameters

pharpath

The internal path within the phar archive to use as the mounted path location. If executed within a phar archive, this may be a relative path, otherwise this must be a full phar URL.

externalpath

A path or URL to an external file or directory to mount within the phar archive

Return Values

No return. PharException is thrown on failure.

Errors/Exceptions

Throws PharException if any problems occur mounting the path.

Examples

Example #1 A Phar::mount() example

The following example shows accessing an external configuration file as if it were a path within a phar archive.

First, the code inside of a phar archive:

<?php
$configuration = simplexml_load_string(file_get_contents(
    Phar::running(false) . '/config.xml'));
?>

Next the external code used to mount the configuration file:

<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
Phar::mount('phar:///path/to/archive.phar/config.xml', '/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>

Another method is to put the mounting code inside the stub of the phar archive. Here is an example of setting up a default configuration file if no user configuration is specified:

<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
if (defined('EXTERNAL_CONFIG')) {
    Phar::mount('config.xml', EXTERNAL_CONFIG);
    if (file_exists(__DIR__ . '/extra_config.xml')) {
        Phar::mount('extra.xml', __DIR__ . '/extra_config.xml');
    }
} else {
    Phar::mount('config.xml', 'phar://' . __FILE__ . '/default_config.xml');
    Phar::mount('extra.xml', 'phar://' . __FILE__ . '/default_extra.xml');
}
// now run the application
include 'phar://' . __FILE__ . '/index.php';
__HALT_COMPILER();
?>

...and the code externally to load this phar archive:

<?php
define('EXTERNAL_CONFIG', '/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>

Phar::mapPhar
Phar::mungServer
Phar


Defines a list of up to 4 $_SERVER variables that should be modified for execution

Phar::mount
Phar::offsetExists
Phar
PHP Manual

Phar::mungServer

(Unknown)

Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution

Description

void Phar::mungServer ( array $munglist )

Phar::mungServer() should only be called within the stub of a phar archive.

Defines a list of up to 4 $_SERVER variables that should be modified for execution. Variables that can be modified to remove traces of phar execution are REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME.

On its own, this method does nothing. Only when combined with Phar::webPhar() does it take effect, and only when the requested file is a PHP file to be parsed. Note that the PATH_INFO and PATH_TRANSLATED variables are always modified.

The original values of variables that are modified are stored in the SERVER array with PHAR_ prepended, so for instance SCRIPT_NAME would be saved as PHAR_SCRIPT_NAME.

Parameters

munglist

an array containing as string indices any of REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME. Other values trigger an exception, and Phar::mungServer() is case-sensitive.

Return Values

No return.

Errors/Exceptions

Throws UnexpectedValueException if any problems are found with the passed in data.

Examples

Example #1 A Phar::mungServer() example

<?php
// example stub
Phar::mungServer(array('REQUEST_URI'));
Phar::webPhar();
__HALT_COMPILER();
?>

See Also

  • Phar::webPhar() - mapPhar for web-based phars. front controller for web applications
  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive

Phar::mount
Phar::offsetExists
Phar


determines whether a file exists in the phar

Phar::mungServer
Phar::offsetGet
Phar
PHP Manual

Phar::offsetExists

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetExists — determines whether a file exists in the phar

Description

bool Phar::offsetExists ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets.

offsetExists() is called whenever isset() is called.

Parameters

offset

The filename (relative path) to look for in a Phar.

Return Values

Returns TRUE if the file exists within the phar, or FALSE if not.

Examples

Example #1 A Phar::offsetExists() example

<?php
$p = new Phar(dirname(__FILE__) . '/my.phar', 0, 'my.phar');
$p['firstfile.txt'] = 'first file';
$p['secondfile.txt'] = 'second file';
// the next set of lines call offsetExists() indirectly
var_dump(isset($p['firstfile.txt']));
var_dump(isset($p['nothere.txt']));
?>

The above example will output:

bool(true)
bool(false)

See Also

  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • Phar::offsetUnset() - remove a file from a phar

Phar::mungServer
Phar::offsetGet
Phar


Gets a PharFileInfo object for a specific file

Phar::offsetExists
Phar::offsetSet
Phar
PHP Manual

Phar::offsetGet

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetGet — Gets a PharFileInfo object for a specific file

Description

int Phar::offsetGet ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. Phar::offsetGet is used for retrieving files from a Phar archive.

Parameters

offset

The filename (relative path) to look for in a Phar.

Return Values

A PharFileInfo object is returned that can be used to iterate over a file's contents or to retrieve information about the current file.

Errors/Exceptions

This method throws BadMethodCallException if the file does not exist in the Phar archive.

Examples

Example #1 Phar::offsetGet() example

As with all classes that implement the ArrayAccess interface, Phar::offsetGet is automatically called when using the [] angle bracket operator.

<?php
$p = new Phar(dirname(__FILE__) . '/myphar.phar', 0, 'myphar.phar');
$p['exists.txt'] = "file exists\n";
try {
    // automatically calls offsetGet()
    echo $p['exists.txt'];
    echo $p['doesnotexist.txt'];
} catch (BadMethodCallException $e) {
    echo $e;
}
?>

The above example will output:

file exists
Entry doesnotexist.txt does not exist

See Also

  • Phar::offsetExists() - determines whether a file exists in the phar
  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • Phar::offsetUnset() - remove a file from a phar

Phar::offsetExists
Phar::offsetSet
Phar


set the contents of an internal file to those of an external file

Phar::offsetGet
Phar::offsetUnset
Phar
PHP Manual

Phar::offsetSet

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetSet — set the contents of an internal file to those of an external file

Description

void Phar::offsetSet ( string $offset , string $value )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a Phar archive.

Parameters

offset

The filename (relative path) to modify in a Phar.

value

Content of the file.

Return Values

No return values.

Errors/Exceptions

if phar.readonly is 1, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to 0. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

Examples

Example #1 A Phar::offsetSet() example

offsetSet should not be accessed directly, but instead used via array access with the [] operator.

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
try {
    // calls offsetSet
    $p['file.txt'] = 'Hi there';
} catch (Exception $e) {
    echo 'Could not modify file.txt:', $e;
}
?>

See Also

  • Phar::offsetExists() - determines whether a file exists in the phar
  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetUnset() - remove a file from a phar

Phar::offsetGet
Phar::offsetUnset
Phar


remove a file from a phar

Phar::offsetSet
Phar::running
Phar
PHP Manual

Phar::offsetUnset

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetUnset — remove a file from a phar

Description

bool Phar::offsetUnset ( string $offset )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset() language construct.

Parameters

offset

The filename (relative path) to modify in a Phar.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

if phar.readonly is 1, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to 0. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

Examples

Example #1 A Phar::offsetUnset() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
try {
    // deletes file.txt from my.phar by calling offsetUnset
    unset($p['file.txt']);
} catch (Exception $e) {
    echo 'Could not delete file.txt: ', $e;
}
?>

See Also

  • Phar::offsetExists() - determines whether a file exists in the phar
  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • Phar::unlinkArchive() - Completely remove a phar archive from disk and from memory
  • Phar::delete() - Delete a file within a phar archive

Phar::offsetSet
Phar::running
Phar


Requirements

Phar requires PHP 5.2.0 or newer. Additional features require the SPL extension in order to take advantage of iteration and array access to a Phar's file contents. The phar stream does not require any additional extensions to function.

You may optionally wish to enable the zlib and bzip2 extensions to take advantage of compressed phar support. In addition, to take advantage of OpenSSL signing, the OpenSSL extension must be enabled.

Note that a bug in the zlib.deflate stream filter fixed in PHP version 5.2.6 and newer may cause truncation of gzip and bzip2-compressed phar archives.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

The Phar extension provides the phar stream, which allows accessing files contained within a phar transparently. See also the description of the Phar file format.

Runtime Configuration
Predefined Constants
Installing/Configuring


Returns the full path on disk or full phar URL to the currently executing Phar archive

Phar::offsetUnset
Phar::setAlias
Phar
PHP Manual

Phar::running

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive

Description

string Phar::running ([ bool $retphar = true ] )

Returns the full path to the running phar archive. This is intended for use much like the __FILE__ magic constant, and only has effect inside an executing phar archive.

Inside the stub of an archive, Phar::running() returns "". Simply use __FILE__ to access the current running phar inside a stub.

Parameters

retphar

If FALSE, the full path on disk to the phar archive is returned. If TRUE, a full phar URL is returned.

Return Values

Returns the filename if valid, empty string otherwise.

Examples

Example #1 A Phar::running() example

For the following example, assume the file is within phar archive /path/to/phar/my.phar and the file is located at path my/file.txt within the phar archive.

<?php
$a = Phar::running(); // $a is "phar:///path/to/my.phar"
$b = Phar::running(false); // $b is "/path/to/my.phar"
?>

Phar::offsetUnset
Phar::setAlias
Phar


Set the alias for the Phar archive

Phar::running
Phar::setDefaultStub
Phar
PHP Manual

Phar::setAlias

(PHP >= 5.3.0, PECL phar >= 1.2.1)

Phar::setAlias — Set the alias for the Phar archive

Description

bool Phar::setAlias ( string $alias )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Set the alias for the Phar archive, and write it as the permanent alias for this phar archive. An alias can be used internally to a phar archive to ensure that use of the phar stream wrapper to access internal files always works regardless of the location of the phar archive on the filesystem. Another alternative is to rely upon Phar's interception of include() or to use Phar::interceptFileFuncs() and use relative paths.

Parameters

alias

A shorthand string that this archive can be referred to in phar stream wrapper access.

Return Values

Errors/Exceptions

Throws UnexpectedValueException when write access is disabled, and PharException if the alias is already in use or any problems were encountered flushing changes to disk.

Examples

Example #1 A Phar::setAlias() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->setAlias('myp.phar');
} catch (Exception $e) {
    // handle error
}
?>

See Also

  • Phar::__construct() - Construct a Phar archive object
  • Phar::interceptFileFuncs() - instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Phar::running
Phar::setDefaultStub
Phar


Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

Phar::setAlias
Phar::setMetadata
Phar
PHP Manual

Phar::setDefaultStub

(Unknown)

Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

Description

bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method is a convenience method that combines the functionality of Phar::createDefaultStub() and Phar::setStub().

Parameters

index

Relative path within the phar archive to run if accessed on the command-line

webindex

Relative path within the phar archive to run if accessed through a web browser

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

Examples

Example #1 A Phar::setDefaultStub() example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->setDefaultStub('cli.php', 'web/index.php');
    // this is the same as:
    // $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

Phar::setAlias
Phar::setMetadata
Phar


Sets phar archive meta-data

Phar::setDefaultStub
Phar::setSignatureAlgorithm
Phar
PHP Manual

Phar::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setMetadata — Sets phar archive meta-data

Description

void Phar::setMetadata ( mixed $metadata )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Phar::setMetadata() should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata() should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

Parameters

metadata

Any PHP variable containing information to store that describes the phar archive

Return Values

No value is returned.

Examples

Example #1 A Phar::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.php'] = '<?php echo "hello"';
    $p->setMetadata(array('bootstrap' => 'file.php'));
    var_dump($p->getMetadata());
} catch (Exception $e) {
    echo 'Could not create and/or modify phar:', $e;
}
?>

The above example will output:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

See Also

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

Phar::setDefaultStub
Phar::setSignatureAlgorithm
Phar


set the signature algorithm for a phar and apply it.

Phar::setMetadata
Phar::setStub
Phar
PHP Manual

Phar::setSignatureAlgorithm

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it.

Description

void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

set the signature algorithm for a phar and apply it. The signature algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::OPENSSL.

Note that all executable phar archives have a signature created automatically, SHA1 by default. data tar- or zip-based archives (archives created with the PharData class) must have their signature created and set explicitly via Phar::setSignatureAlgorithm().

Parameters

sigtype

    One of Phar::MD5,
Phar::SHA1, Phar::SHA256,
Phar::SHA512, or Phar::OPENSSL

privatekey

The contents of an OpenSSL private key, as extracted from a certificate or OpenSSL key file:

<?php
$private = openssl_get_privatekey(file_get_contents('private.pem'));
$pkey = '';
openssl_pkey_export($private, $pkey);
$p->setSignatureAlgorithm(Phar::OPENSSL, $pkey);
?>

See phar introduction for instructions on naming and placement of the public key file.

Return Values

No value is returned.

Errors/Exceptions

Throws UnexpectedValueException for many errors, and a PharException if any problems occur flushing changes to disk.

See Also

  • Phar::getSupportedSignatures() - Return array of supported signature types
  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Phar::setMetadata
Phar::setStub
Phar


Used to set the PHP loader or bootstrap stub of a Phar archive

Phar::setSignatureAlgorithm
Phar::startBuffering
Phar
PHP Manual

Phar::setStub

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive

Description

bool Phar::setStub ( string $stub )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method is used to add a PHP bootstrap loader stub to a new Phar archive, or to replace the loader stub in an existing Phar archive.

The loader stub for a Phar archive is used whenever an archive is included directly as in this example:

<?php
include 'myphar.phar';
?>

The loader is not accessed when including a file through the phar stream wrapper like so:

<?php
include 'phar://myphar.phar/somefile.php';
?>

Parameters

stub

A string or an open stream handle to use as the executable stub for this phar archive.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

Examples

Example #1 A Phar::setStub() example

<?php
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['a.php'] = '<?php var_dump("Hello");';
    $p->setStub('<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
    include 'phar://brandnewphar.phar/a.php';
    var_dump($p->getStub());
    $p['b.php'] = '<?php var_dump("World");';
    $p->setStub('<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
    include 'phar://brandnewphar.phar/b.php';
    var_dump($p->getStub());
} catch (Exception $e) {
    echo 'Write operations failed on brandnewphar.phar: ', $e;
}
?>

The above example will output:

string(5) "Hello"
string(82) "<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"
string(5) "World"
string(83) "<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"

See Also

  • Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

Phar::setSignatureAlgorithm
Phar::startBuffering
Phar


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Phar


Start buffering Phar write operations, do not modify the Phar object on disk

Phar::setStub
Phar::stopBuffering
Phar
PHP Manual

Phar::startBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk

Description

void Phar::startBuffering ( void )

Although technically unnecessary, the Phar::startBuffering() method can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. the Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Return Values

No value is returned.

Examples

Example #1 A Phar::startBuffering() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
    echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p->startBuffering();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']->setCompressedGZ();
$p['file3.txt'] = 'babyface';
$p['file3.txt']->setMetaData(42);
$p->setStub("<?php
function __autoload($class)
{
    include 'phar://myphar.phar/' . str_replace('_', '/', $class) . '.php';
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER();");
$p->stopBuffering();
?>

See Also

  • Phar::stopBuffering() - Stop buffering write requests to the Phar archive, and save changes to disk
  • Phar::isBuffering() - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

Phar::setStub
Phar::stopBuffering
Phar


Stop buffering write requests to the Phar archive, and save changes to disk

Phar::startBuffering
Phar::uncompressAllFiles
Phar
PHP Manual

Phar::stopBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk

Description

void Phar::stopBuffering ( void )

Phar::stopBuffering() is used in conjunction with the Phar::startBuffering() method. Phar::startBuffering() can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. The Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Return Values

No value is returned.

Errors/Exceptions

PharException is thrown if any problems are encountered flushing changes to disk.

Examples

Example #1 A Phar::stopBuffering() example

<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file1.txt'] = 'hi';
$p->startBuffering();
var_dump($p->getStub());
$p->setStub("<?php
function __autoload(\$class)
{
    include 'phar://brandnewphar.phar/' . str_replace('_', '/', \$class) . '.php';
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();");
$p->stopBuffering();
var_dump($p->getStub());
?>

The above example will output:

string(24) "<?php __HALT_COMPILER();"
string(195) "<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();"

See Also

  • Phar::startBuffering() - Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::isBuffering() - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

Phar::startBuffering
Phar::uncompressAllFiles
Phar


Uncompresses all files in the current Phar archive

Phar::stopBuffering
Phar::unlinkArchive
Phar
PHP Manual

Phar::uncompressAllFiles

(PECL phar < 2.0.0)

Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive

Description

bool Phar::uncompressAllFiles ( void )

Note: This
method has been removed from the phar extension as of version 2.0.0.  Alternative
implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and
Phar::decompressFiles().

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method decompresses all files in the Phar archive. If any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files, and any files compressed using bzip2 compression require the bzip2 extension to decompress the files. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not enabled and any files are compressed using bzip2 compression, or if any files are compressed using gzip compression and the zlib extension is not enabled.

Examples

Example #1 A Phar::uncompressAllFiles() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p->compressAllFilesGZ();
    foreach ($p as $file) {
        var_dump($file->getFileName());
        var_dump($file->isCompressed());
        var_dump($file->isCompressedBZIP2());
        var_dump($file->isCompressedGZ());
    }
    $p->uncompressAllFiles();
    foreach ($p as $file) {
        var_dump($file->getFileName());
        var_dump($file->isCompressed());
        var_dump($file->isCompressedBZIP2());
        var_dump($file->isCompressedGZ());
    }
} catch (Exception $e) {
    echo 'Write operations failed on my.phar: ', $e;
}
?>

The above example will output:

string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

Phar::stopBuffering
Phar::unlinkArchive
Phar


Completely remove a phar archive from disk and from memory

Phar::uncompressAllFiles
Phar::webPhar
Phar
PHP Manual

Phar::unlinkArchive

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::unlinkArchive — Completely remove a phar archive from disk and from memory

Description

bool Phar::unlinkArchive ( string $archive )

Removes a phar archive for disk and memory.

Parameters

archive

The path on disk to the phar archive.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

PharException is thrown if there are any open file pointers to the phar archive, or any existing Phar, PharData, or PharFileInfo objects referring to the phar archive.

Examples

Example #1 A Phar::unlinkArchive() example

<?php
// simple usage
Phar::unlinkArchive('/path/to/my.phar');

// more common example:
$p = new Phar('my.phar');
$fp = fopen('phar://my.phar/file.txt', 'r');
// this creates 'my.phar.gz'
$gp = $p->compress(Phar::GZ);
// remove all references to the archive
unset($p);
fclose($fp);
// now remove all traces of the archive
Phar::unlinkArchive('my.phar');
?>

See Also

  • Phar::delete() - Delete a file within a phar archive
  • Phar::offsetUnset() - remove a file from a phar

Phar::uncompressAllFiles
Phar::webPhar
Phar


Using Phar Archives

Table of Contents

  • Using Phar Archives: Introduction
  • Using Phar Archives: the phar stream wrapper
  • Using Phar Archives: the Phar and PharData class
Predefined Constants
Using Phar Archives: Introduction
Phar


Using Phar Archives: Introduction

Phar archives are similar in concept to Java JAR archives, but are tailored to the needs and to the flexibility of PHP applications. A Phar archive is used to distribute a complete PHP application or library in a single file. Unlike Java's implementation of JAR archives, no external tool is required to process or run a PHP Phar archive. A Phar archive application is used exactly like any other PHP application:

php coolapplication.phar

Using a Phar archive library is identical to using any other PHP library:

<?php
include 'coollibrary.phar';
?>

The phar stream wrapper provides the core of the phar extension, and is explained in detail here. The phar stream wrapper allows accessing the files within a phar archive using PHP's standard file functions fopen(), opendir(), and others that work on regular files. The phar stream wrapper supports all read/write operations on both files and directories.

<?php
include 'phar://coollibrary.phar/internal/file.php';
header('Content-type: image/jpeg');
// phars can be accessed by full path or by alias
echo file_get_contents('phar:///fullpath/to/coollibrary.phar/images/wow.jpg');
?>

The Phar class implements advanced functionality for accessing files and for creating phar archives. The Phar class is explained in detail here.

<?php
try {
    // open an existing phar
    $p = new Phar('coollibrary.phar', 0);
    // Phar extends SPL's DirectoryIterator class
    foreach (new RecursiveIteratorIterator($p) as $file) {
        // $file is a PharFileInfo class, and inherits from SplFileInfo
        echo $file->getFileName() . "\n";
        echo file_get_contents($file->getPathName()) . "\n"; // display contents;
    }
    if (isset($p['internal/file.php'])) {
        var_dump($p['internal/file.php']->getMetaData());
    }

    // create a new phar - phar.readonly must be 0 in php.ini
    // phar.readonly is enabled by default for security reasons.
    // On production servers, Phars need never be created,
    // only executed.
    if (Phar::canWrite()) {
        $p = new Phar('newphar.tar.phar', 0, 'newphar.tar.phar');
        // make this a tar-based phar archive, compressed with gzip compression (.tar.gz)
        $p = $p->convertToExecutable(Phar::TAR, Phar::GZ);

        // create transaction - nothing is written to newphar.phar
        // until stopBuffering() is called, although temporary storage is needed
        $p->startBuffering();
        // add all files in /path/to/project, saving in the phar with the prefix "project"
        $p->buildFromIterator(new RecursiveIteratorIterator(new DirectoryIterator('/path/to/project')), '/path/to/');

        // add a new file via the array access API
        $p['file1.txt'] = 'Information';
        $fp = fopen('hugefile.dat', 'rb');
        // copy all data from the stream
        $p['data/hugefile.dat'] = $fp;

        if (Phar::canCompress(Phar::GZ)) {
            $p['data/hugefile.dat']->compress(Phar::GZ);
        }

        $p['images/wow.jpg'] = file_get_contents('images/wow.jpg');
        // any value can be saved as file-specific meta-data
        $p['images/wow.jpg']->setMetaData(array('mime-type' => 'image/jpeg'));
        $p['index.php'] = file_get_contents('index.php');
        $p->setMetaData(array('bootstrap' => 'index.php'));

        // save the phar archive to disk
        $p->stopBuffering();
    }
} catch (Exception $e) {
    echo 'Could not open Phar: ', $e;
}
?>

In addition, verification of phar file contents can be done using any of the supported symmetric hash algorithms (MD5, SHA1, SHA256 and SHA512 if ext/hash is enabled) and using asymmetric public/private key signing using OpenSSL (new in Phar 2.0.0). To take advantage of OpenSSL signing, you need to generate a public/private key pair, and use the private key to set the signature using Phar::setSignatureAlgorithm(). In addition, the public key as extracted using this code:

<?php
$public = openssl_get_publickey(file_get_contents('private.pem'));
$pkey = '';
openssl_pkey_export($public, $pkey);
?>

must be saved adjacent to the phar archive it verifies. If the phar archive is saved as /path/to/my.phar, the public key must be saved as /path/to/my.phar.pubkey, or phar will be unable to verify the OpenSSL signature.

As of version 2.0.0, The Phar class also provides 3 static methods, Phar::webPhar(), Phar::mungServer() and Phar::interceptFileFuncs() that are crucial to packaging up PHP applications designed for usage on regular filesystems and for web-based applications. Phar::webPhar() implements a front controller that routes HTTP calls to the correct location within the phar archive. Phar::mungServer() is used to modify the values of the $_SERVER array to trick applications that process these values. Phar::interceptFileFuncs() instructs Phar to intercept calls to fopen(), file_get_contents(), opendir(), and all of the stat-based functions (file_exists(), is_readable() and so on) and route all relative paths to locations within the phar archive.

As an example, packaging up a release of the popular phpMyAdmin application for use as a phar archive requires only this simple script and then phpMyAdmin.phar.tar.php can be accessed as a regular file from your web server after modifying the user/password:

<?php
@unlink('phpMyAdmin.phar.tar.php');
copy('phpMyAdmin-2.11.3-english.tar.gz', 'phpMyAdmin.phar.tar.php');
$a = new Phar('phpMyAdmin.phar.tar.php');
$a->startBuffering();
$a["phpMyAdmin-2.11.3-english/config.inc.php"] = '<?php
/* Servers configuration */
$i = 0;

/* Server localhost (config:root) [1] */
$i++;
$cfg[\'Servers\'][$i][\'host\'] = \'localhost\';
$cfg[\'Servers\'][$i][\'extension\'] = \'mysqli\';
$cfg[\'Servers\'][$i][\'connect_type\'] = \'tcp\';
$cfg[\'Servers\'][$i][\'compress\'] = false;
$cfg[\'Servers\'][$i][\'auth_type\'] = \'config\';
$cfg[\'Servers\'][$i][\'user\'] = \'root\';
$cfg[\'Servers\'][$i][\'password\'] = \'\';

/* End of servers configuration */
if (strpos(PHP_OS, \'WIN\') !== false) {
    $cfg[\'UploadDir\'] = getcwd();
} else {
    $cfg[\'UploadDir\'] = \'/tmp/pharphpmyadmin\';
    @mkdir(\'/tmp/pharphpmyadmin\');
    @chmod(\'/tmp/pharphpmyadmin\', 0777);
}';
$a->setStub('<?php
Phar::interceptFileFuncs();
Phar::webPhar("phpMyAdmin.phar", "phpMyAdmin-2.11.3-english/index.php");
echo "phpMyAdmin is intended to be executed from a web browser\n";
exit -1;
__HALT_COMPILER();
');
$a->stopBuffering();
?>

Using Phar Archives
Using Phar Archives: the phar stream wrapper
Using Phar Archives


Using Phar Archives: the Phar and PharData class

The Phar class supports reading and manipulation of Phar archives, as well as iteration through inherited functionality of the RecursiveDirectoryIterator class. With support for the ArrayAccess interface, files inside a Phar archive can be accessed as if they were part of an associative array.

The PharData class extends the Phar, and allows creating and modifying non-executable (data) tar and zip archives even if phar.readonly=1 in php.ini. As such, PharData::setAlias() and PharData::setStub() are both disabled as the concept of alias and stub are unique to executable phar archives.

It is important to note that when creating a Phar archive, the full path should be passed to the Phar object constructor. Relative paths will fail to initialize.

Assuming that $p is a Phar object initialized as follows:

<?php
$p = new Phar('/path/to/myphar.phar', 0, 'myphar.phar');
?>

An empty Phar archive will be created at /path/to/myphar.phar, or if /path/to/myphar.phar already exists, it will be opened again. The literal myphar.phar demonstrates the concept of an alias that can be used to reference /path/to/myphar.phar in URLs as in:

<?php
// these two calls to file_get_contents() are equivalent if
// /path/to/myphar.phar has an explicit alias of "myphar.phar"
// in its manifest, or if the phar was initialized with the
// previous example's Phar object setup
$f = file_get_contents('phar:///path/to/myphar.phar/whatever.txt');
$f = file_get_contents('phar://myphar.phar/whatever.txt');
?>

With the newly created $p Phar object, the following is possible:

  • $a = $p['file.php'] creates a PharFileInfo class that refers to the contents of phar://myphar.phar/file.php
  • $p['file.php'] = $v creates a new file (phar://myphar.phar/file.php), or overwrites an existing file within myphar.phar. $v can be either a string or an open file pointer, in which case the entire contents of the file will be used to create the new file. Note that $p->addFromString('file.php', $v) is functionally equivalent to the above. Also possible is to add the contents of a file with $p->addFile('/path/to/file.php', 'file.php'). Lastly, an empty directory can be created with $p->addEmptyDir('empty').
  • isset($p['file.php']) can be used to determine whether phar://myphar.phar/file.php exists within myphar.phar.
  • unset($p['file.php']) erases phar://myphar.phar/file.php from myphar.phar.

In addition, the Phar object is the only way to access Phar-specific metadata, through Phar::getMetaData(), and the only way to set or retrieve a Phar archive's PHP loader stub through Phar::getStub() and Phar::setStub(). Additionally, compression for the entire Phar archive at once can only be manipulated using the Phar class.

The full list of Phar object functionality is documented below.

The PharFileInfo class extends the SplFileInfo class, and adds several methods for manipulating Phar-specific details of a file contained within a Phar, such as manipulating compression and metadata.

Using Phar Archives: the phar stream wrapper
Creating Phar Archives
Using Phar Archives


Using Phar Archives: the phar stream wrapper

The Phar stream wrapper fully supports fopen() for read and write (not append), unlink(), stat(), fstat(), fseek(), rename() and directory stream operations opendir() and as of version 2.0.0, rmdir() and mkdir().

Individual file compression and per-file metadata can also be manipulated in a Phar archive using stream contexts:

<?php
$context = stream_context_create(array('phar' =>
                                    array('compress' => Phar::GZ)),
                                    array('metadata' => array('user' => 'cellog')));
file_put_contents('phar://my.phar/somefile.php', 0, $context);
?>

The phar stream wrapper does not operate on remote files, and cannot operate on remote files, and so is allowed even when the allow_url_fopen and allow_url_include INI options are disabled.

Although it is possible to create phar archives from scratch just using stream operations, it is best to use the functionality built into the Phar class. The stream wrapper is best used for read-only operations.

Using Phar Archives: Introduction
Using Phar Archives: the Phar and PharData class
Using Phar Archives


mapPhar for web-based phars. front controller for web applications

Phar::unlinkArchive
PharData
Phar
PHP Manual

Phar::webPhar

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::webPhar — mapPhar for web-based phars. front controller for web applications

Description

void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, array $rewrites ]]]]] )

Phar::mapPhar() for web-based phars. This method parses $_SERVER['REQUEST_URI'] and routes a request from a web browser to an internal file within the phar archive. In essence, it simulates a web server, routing requests to the correct file, echoing the correct headers and parsing PHP files as needed. This powerful method is part of what makes it easy to convert an existing PHP application into a phar archive. Combined with Phar::mungServer() and Phar::interceptFileFuncs(), any web application can be used unmodified from a phar archive.

Phar::webPhar() should only be called from the stub of a phar archive (see here for more information on what a stub is).

Parameters

alias

The alias that can be used in phar:// URLs to refer to this archive, rather than its full path.

index

The location within the phar of the directory index.

f404

The location of the script to run when a file is not found. This script should output the proper HTTP 404 headers.

mimetypes

An array mapping additional file extensions to MIME type. By default, these extensions are mapped to these mime types:

<?php
$mimes = array(
    'phps' => 2, // pass to highlight_file()
    'c' => 'text/plain',
    'cc' => 'text/plain',
    'cpp' => 'text/plain',
    'c++' => 'text/plain',
    'dtd' => 'text/plain',
    'h' => 'text/plain',
    'log' => 'text/plain',
    'rng' => 'text/plain',
    'txt' => 'text/plain',
    'xsd' => 'text/plain',
    'php' => 1, // parse as PHP
    'inc' => 1, // parse as PHP
    'avi' => 'video/avi',
    'bmp' => 'image/bmp',
    'css' => 'text/css',
    'gif' => 'image/gif',
    'htm' => 'text/html',
    'html' => 'text/html',
    'htmls' => 'text/html',
    'ico' => 'image/x-ico',
    'jpe' => 'image/jpeg',
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'js' => 'application/x-javascript',
    'midi' => 'audio/midi',
    'mid' => 'audio/midi',
    'mod' => 'audio/mod',
    'mov' => 'movie/quicktime',
    'mp3' => 'audio/mp3',
    'mpg' => 'video/mpeg',
    'mpeg' => 'video/mpeg',
    'pdf' => 'application/pdf',
    'png' => 'image/png',
    'swf' => 'application/shockwave-flash',
    'tif' => 'image/tiff',
    'tiff' => 'image/tiff',
    'wav' => 'audio/wav',
    'xbm' => 'image/xbm',
    'xml' => 'text/xml',
);
?>

rewrites

An array mapping URI to internal file, simulating mod_rewrite of apache. For example:

<?php
array(
    'myinfo' => 'myinfo.php'
);
?>

would route calls to http://<host>/myphar.phar/myinfo to the file phar:///path/to/myphar.phar/myinfo.php, preserving GET/POST. This does not quite work like mod_rewrite in that it would not match http://<host>/myphar.phar/myinfo/another.

Return Values

No value is returned.

Errors/Exceptions

Throws PharException when unable to open the internal file to output, or if called from a non-stub. If an invalid array value is passed into mimetypes or to rewrites , then UnexpectedValueException is thrown.

Examples

Example #1 A Phar::webPhar() example

With the example below, the created phar will display Hello World if one browses to /myphar.phar/index.php or to /myphar.phar, and will display the source of index.phps if one browses to /myphar.phar/index.phps.

<?php
// creating the phar archive:
try {
    $phar = new Phar('myphar.phar');
    $phar['index.php'] = '<?php echo "Hello World"; ?>';
    $phar['index.phps'] = '<?php echo "Hello World"; ?>';
    $phar->setStub('<?php
Phar::webPhar();
__HALT_COMPILER(); ?>');
} catch (Exception $e) {
    // handle error here
}
?>

See Also

  • Phar::mungServer() - Defines a list of up to 4 $_SERVER variables that should be modified for execution
  • Phar::interceptFileFuncs() - instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Phar::unlinkArchive
PharData
Phar


Add an empty directory to the tar/zip archive

PharData
PharData::addFile
PharData
PHP Manual

PharData::addEmptyDir

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addEmptyDir — Add an empty directory to the tar/zip archive

Description

bool PharData::addEmptyDir ( string $dirname )

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().

Parameters

dirname

The name of the empty directory to create in the phar archive

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A PharData::addEmptyDir() example

<?php
try {
    $a = new PharData('/path/to/my.tar');

    $a->addEmptyDir('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • Phar::addEmptyDir() - Add an empty directory to the phar archive
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • PharData::addFromString() - Add a file from the filesystem to the tar/zip archive

PharData
PharData::addFile
PharData


Add a file from the filesystem to the tar/zip archive

PharData::addEmptyDir
PharData::addFromString
PharData
PHP Manual

PharData::addFile

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addFile — Add a file from the filesystem to the tar/zip archive

Description

void Phar::addFile ( string $file [, string $localname ] )

With this method, any file or URL can be added to the tar/zip archive. If the optional second parameter localname is specified, the file will be stored in the archive with that name, otherwise the file parameter is used as the path to store within the archive. URLs must have a localname or an exception is thrown. This method is similar to ZipArchive::addFile().

Parameters

file

Full or relative path to a file on disk to be added to the phar archive.

localname

Path that the file will be stored in the archive.

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A PharData::addFile() example

<?php
try {
    $a = new PharData('/path/to/my.tar');

    $a->addFile('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->getContent();

    $a->addFile('/full/path/to/file', 'my/file.txt');
    $c = $a['my/file.txt']->getContent();

    // demonstrate URL usage
    $a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • PharData::offsetSet() - set the contents of a file within the tar/zip to those of an external file or string
  • Phar::addFile() - Add a file from the filesystem to the phar archive
  • PharData::addFromString() - Add a file from the filesystem to the tar/zip archive
  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive

PharData::addEmptyDir
PharData::addFromString
PharData


Add a file from the filesystem to the tar/zip archive

PharData::addFile
PharData::buildFromDirectory
PharData
PHP Manual

PharData::addFromString

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addFromString — Add a file from the filesystem to the tar/zip archive

Description

bool PharData::addFromString ( string $localname , string $contents )

With this method, any string can be added to the tar/zip archive. The file will be stored in the archive with localname as its path. This method is similar to ZipArchive::addFromString().

Parameters

localname

Path that the file will be stored in the archive.

contents

The file contents to store

Return Values

no return value, exception is thrown on failure.

Examples

Example #1 A PharData::addFromString() example

<?php
try {
    $a = new PharData('/path/to/my.tar');

    $a->addFromString('path/to/file.txt', 'my simple file');
    $b = $a['path/to/file.txt']->getContent();

    // to add contents from a stream handle for large files, use offsetSet()
    $c = fopen('/path/to/hugefile.bin');
    $a['largefile.bin'] = $c;
    fclose($c);
} catch (Exception $e) {
    // handle errors here
}
?>

See Also

  • PharData::offsetSet() - set the contents of a file within the tar/zip to those of an external file or string
  • Phar::addFromString() - Add a file from the filesystem to the phar archive
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive

PharData::addFile
PharData::buildFromDirectory
PharData


Construct a tar/zip archive from the files within a directory.

PharData::addFromString
PharData::buildFromIterator
PharData
PHP Manual

PharData::buildFromDirectory

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory.

Description

array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

Populate a tar/zip archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use PharData::buildFromIterator().

Parameters

base_dir

The full or relative path to the directory that contains all files to add to the archive.

regex

An optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.

Return Values

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Errors/Exceptions

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

Examples

Example #1 A PharData::buildFromDirectory() example

<?php
$phar = new PharData('project.tar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');

$phar2 = new PharData('project2.zip');
// add all files in the project, only include php files
$phar->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
?>

See Also

  • Phar::buildFromDirectory() - Construct a phar archive from the files within a directory.
  • PharData::buildFromIterator() - Construct a tar or zip archive from an iterator.

PharData::addFromString
PharData::buildFromIterator
PharData


Construct a tar or zip archive from an iterator.

PharData::buildFromDirectory
PharData::compress
PharData
PHP Manual

PharData::buildFromIterator

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::buildFromIterator — Construct a tar or zip archive from an iterator.

Description

array PharData::buildFromIterator ( Iterator $iter [, string $base_directory ] )

Populate a tar or zip archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the tar/zip to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.

Examples

Example #1 A PharData::buildFromIterator() with SplFileInfo

For most tar/zip archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a tar/zip archive containing the files in this sample directory layout:

/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php

This code could be used to add these files to the "project.tar" tar archive:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new RecursiveDirectoryIterator('/path/to/project')),
    '/path/to/project');
?>

The file project.tar can then be used immediately. PharData::buildFromIterator() does not set values such as compression, metadata, and this can be done after creating the tar/zip archive.

As an interesting note, PharData::buildFromIterator() can also be used to copy the contents of an existing phar, tar or zip archive, as the PharData object descends from DirectoryIterator:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new Phar('/path/to/anotherphar.phar')),
    'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultWebStub('cli/index.php', 'www/index.php'));
?>

Example #2 A PharData::buildFromIterator() with other iterators

The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new ArrayIterator(
     array(
        'internal/file.php' => dirname(__FILE__) . '/somefile.php',
        'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
     )));
?>

Parameters

iter

Any iterator that either associatively maps tar/zip file to location or returns SplFileInfo objects

base_directory

For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the tar/zip archive

Return Values

PharData::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Errors/Exceptions

This method returns UnexpectedValueException when the iterator returns incorrect values, such as an integer key instead of a string, a BadMethodCallException when an SplFileInfo-based iterator is passed without a base_directory parameter, or a PharException if there were errors saving the phar archive.

See Also

  • Phar::buildFromIterator() - Construct a phar archive from an iterator.

PharData::buildFromDirectory
PharData::compress
PharData


Compresses the entire tar/zip archive using Gzip or Bzip2 compression

PharData::buildFromIterator
PharData::compressFiles
PharData
PHP Manual

PharData::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression

Description

object PharData::compress ( int $compression , string $extension )

For tar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.

For zip archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression.

In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.

Parameters

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

extension

By default, the extension is .tar.gz or .tar.bz2 for compressing a tar, and .tar for decompressing.

Return Values

A PharData object is returned.

Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

Examples

Example #1 A PharData::compress() example

<?php
$p = new PharData('/path/to/my.tar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>

See Also

  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression

PharData::buildFromIterator
PharData::compressFiles
PharData


Compresses all files in the current tar/zip archive

PharData::compress
PharData::__construct
PharData
PHP Manual

PharData::compressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::compressFiles — Compresses all files in the current tar/zip archive

Description

bool PharData::compressFiles ( int $compression )

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress() to compress an entire tar-based archive.

For Zip-based archives, this method compresses all files in the archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing.

Parameters

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Examples

Example #1 A PharData::compressFiles() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

The above example will output:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::decompressFiles() - Decompresses all files in the current zip archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::decompress() - Decompresses the entire Phar archive

PharData::compress
PharData::__construct
PharData


Construct a non-executable tar or zip archive object

PharData::compressFiles
PharData::convertToData
PharData
PHP Manual

PharData::__construct

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::__construct — Construct a non-executable tar or zip archive object

Description

void PharData::__construct ( string $fname [, int $flags ] )

Parameters

fname

Path to an existing tar/zip archive or to-be-created archive

flags

Flags to pass to Phar parent class RecursiveDirectoryIterator.

Errors/Exceptions

Throws BadMethodCallException if called twice, UnexpectedValueException if the phar archive can't be opened.

Examples

Example #1 A PharData::__construct() example

<?php
try {
    $p = new PharData('/path/to/my.tar', CURRENT_AS_FILEINFO | KEY_AS_FILENAME);
} catch (UnexpectedValueException $e) {
    die('Could not open my.tar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}
echo file_get_contents('phar:///path/to/my.tar/example.txt');
?>

PharData::compressFiles
PharData::convertToData
PharData


Convert a phar archive to a non-executable tar or zip file

PharData::__construct
PharData::convertToExecutable
PharData
PHP Manual

PharData::convertToData

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::convertToData — Convert a phar archive to a non-executable tar or zip file

Description

PharData PharData::convertToData ([ int $format [, int $compression [, string $extension ]]] )

This method is used to convert a non-executable tar or zip archive to another non-executable format.

If no changes are specified, this method throws a BadMethodCallException. This method should be used to convert a tar archive to zip format or vice-versa. Although it is possible to simply change the compression of a tar archive using this method, it is better to use the PharData::compress() method for logical consistency.

If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parameters

format

This should be one of Phar::TAR or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.

If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.

Return Values

The method returns a PharData object on success and throws an exception on failure.

Errors/Exceptions

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), and a PharException if any problems are encountered during the phar creation process.

Examples

Example #1 A PharData::convertToData() example

Using PharData::convertToData():

<?php
try {
    $tarphar = new PharData('myphar.tar');
    // note that myphar.tar is *not* unlinked
    // convert it to the non-executable tar file format
    // creates myphar.zip
    $zip = $tarphar->convertToData(Phar::ZIP);
    // create myphar.tbz
    $tgz = $zip->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
    // creates myphar.phar.tgz
    $phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
    // handle the error here
}
?>

See Also

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive

PharData::__construct
PharData::convertToExecutable
PharData


Convert a non-executable tar/zip archive to an executable phar archive

PharData::convertToData
PharData::copy
PharData
PHP Manual

PharData::convertToExecutable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive

Description

Phar PharData::convertToExecutable ([ int $format [, int $compression [, string $extension ]]] )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method is used to convert a non-executable tar or zip archive to an executable phar archive. Any of the three executable file formats (phar, tar or zip) can be used, and whole-archive compression can also be performed.

If no changes are specified, this method throws a BadMethodCallException.

If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parameters

format

This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.

If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.

Return Values

The method returns a Phar object on success and throws an exception on failure.

Errors/Exceptions

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.

Examples

Example #1 A PharData::convertToExecutable() example

Using PharData::convertToExecutable():

<?php
try {
    $tarphar = new PharData('myphar.tar');
    // convert it to the phar file format
    // note that myphar.tar is *not* unlinked
    $phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
    $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
    // creates myphar.phar.tgz
    $compressed = $tarphar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
    // handle the error here
}
?>

See Also

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

PharData::convertToData
PharData::copy
PharData


Copy a file internal to the phar archive to another new file within the phar

PharData::convertToExecutable
PharData::decompress
PharData
PHP Manual

PharData::copy

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::copy — Copy a file internal to the phar archive to another new file within the phar

Description

bool PharData::copy ( string $oldfile , string $newfile )

Copy a file internal to the tar/zip archive to another new file within the same archive. This is an object-oriented alternative to using copy() with the phar stream wrapper.

Parameters

oldfile

newfile

Return Values

returns TRUE on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

Errors/Exceptions

throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.

Examples

Example #1 A PharData::copy() example

This example shows using PharData::copy() and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All PharData methods throw exceptions, whereas the stream wrapper uses trigger_error().

<?php
try {
    $phar = new PharData('myphar.tar');
    $phar['a'] = 'hi';
    $phar->copy('a', 'b');
    echo $phar['b']; // outputs "hi"
} catch (Exception $e) {
    // handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.tar/a', 'phar//myphar.tar/c');
echo file_get_contents('phar://myphar.tar/c'); // outputs "hi"
?>

PharData::convertToExecutable
PharData::decompress
PharData


Decompresses the entire Phar archive

PharData::copy
PharData::decompressFiles
PharData
PHP Manual

PharData::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::decompress — Decompresses the entire Phar archive

Description

object PharData::decompress ([ string $extension ] )

For tar-based archives, this method decompresses the entire archive.

For Zip-based archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression.

In addition, this method automatically renames the file extension of the archive, .tar by default. Alternatively, a file extension may be specified with the second parameter.

Parameters

extension

For decompressing, the default file extension is .phar.tar. Use this parameter to specify another file extension. Be aware that no non-executable archives cannot contain .phar in their filename.

Return Values

A PharData object is returned.

Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

Examples

Example #1 A PharData::decompress() example

<?php
$p = new PharData('/path/to/my.tar', 0, 'my.tar.gz');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p3 = $p2->decompress(); // creates /path/to/my.tar
?>

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compressFiles() - Compresses all files in the current tar/zip archive
  • PharData::decompressFiles() - Decompresses all files in the current zip archive

PharData::copy
PharData::decompressFiles
PharData


Decompresses all files in the current zip archive

PharData::decompress
PharData::delMetadata
PharData
PHP Manual

PharData::decompressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::decompressFiles — Decompresses all files in the current zip archive

Description

bool PharData::decompressFiles ( void )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress() to compress an entire tar-based archive.

For Zip-based archives, this method decompresses all files in the archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Examples

Example #1 A PharData::decompressFiles() example

<?php
$p = new PharData('/path/to/my.zip');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

The above example will output:

string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::compressFiles() - Compresses all files in the current tar/zip archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::decompress() - Decompresses the entire Phar archive

PharData::decompress
PharData::delMetadata
PharData


Delete a file within a tar/zip archive

PharData::delMetadata
PharData::extractTo
PharData
PHP Manual

PharData::delete

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::delete — Delete a file within a tar/zip archive

Description

int PharData::delete ( string $entry )

Delete a file within an archive. This is the functional equivalent of calling unlink() on the stream wrapper equivalent, as shown in the example below.

Parameters

entry

Path within an archive to the file to delete.

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A PharData::delete() example

<?php
try {
    $phar = new PharData('myphar.zip');
    $phar->delete('unlink/me.php');
    // this is equivalent to:
    unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • Phar::delete() - Delete a file within a phar archive

PharData::delMetadata
PharData::extractTo
PharData


Deletes the global metadata of a zip archive

PharData::decompressFiles
PharData::delete
PharData
PHP Manual

PharData::delMetadata

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::delMetadata — Deletes the global metadata of a zip archive

Description

int PharData::delMetadata ( void )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Deletes the global metadata of the zip archive

Parameters

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A PharData::delMetaData() example

<?php
try {
    $phar = new PharData('myphar.zip');
    var_dump($phar->getMetadata());
    $phar->setMetadata("hi there");
    var_dump($phar->getMetadata());
    $phar->delMetadata();
    var_dump($phar->getMetadata());
} catch (Exception $e) {
    // handle errors
}
?>

The above example will output:

NULL
string(8) "hi there"
NULL

See Also

  • Phar::delMetadata() - Deletes the global metadata of the phar

PharData::decompressFiles
PharData::delete
PharData


Extract the contents of a tar/zip archive to a directory

PharData::delete
PharData::isWritable
PharData
PHP Manual

PharData::extractTo

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::extractTo — Extract the contents of a tar/zip archive to a directory

Description

int PharData::extractTo ( string $pathto [, string|array $files [, bool $overwrite ]] )

Extract all files within a tar/zip archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo().

Parameters

pathto

Path within an archive to the file to delete.

files

The name of a file or directory to extract, or an array of files/directories to extract

overwrite

Set to TRUE to enable overwriting existing files

Return Values

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Errors/Exceptions

Throws PharException if errors occur while flushing changes to disk.

Examples

Example #1 A PharData::extractTo() example

<?php
try {
    $phar = new PharData('myphar.tar');
    $phar->extractTo('/full/path'); // extract all files
    $phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
    $phar->extractTo('/this/path',
        array('file1.txt', 'file2.txt')); // extract 2 files only
    $phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
    // handle errors
}
?>

See Also

  • Phar::extractTo() - Extract the contents of a phar archive to a directory

PharData::delete
PharData::isWritable
PharData


Returns true if the tar/zip archive can be modified

PharData::extractTo
PharData::offsetSet
PharData
PHP Manual

PharData::isWritable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::isWritable — Returns true if the tar/zip archive can be modified

Description

bool PharData::isWritable ( void )

This method returns TRUE if the tar/zip archive on disk is not read-only. Unlike Phar::isWritable(), data-only tar/zip archives can be modified even if phar.readonly is set to 1.

Parameters

No parameters.

Return Values

Returns TRUE if the tar/zip archive can be modified

See Also

  • Phar::canWrite() - Returns whether phar extension supports writing and creating phars
  • Phar::isWritable() - Returns true if the phar archive can be modified

PharData::extractTo
PharData::offsetSet
PharData


set the contents of a file within the tar/zip to those of an external file or string

PharData::isWritable
PharData::offsetUnset
PharData
PHP Manual

PharData::offsetSet

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::offsetSet — set the contents of a file within the tar/zip to those of an external file or string

Description

void PharData::offsetSet ( string $offset , string $value )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a tar/zip archive.

Parameters

offset

The filename (relative path) to modify in a tar or zip archive.

value

Content of the file.

Return Values

No return values.

Errors/Exceptions

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

Examples

Example #1 A PharData::offsetSet() example

offsetSet should not be accessed directly, but instead used via array access with the [] operator.

<?php
$p = new PharData('/path/to/my.tar');
try {
    // calls offsetSet
    $p['file.txt'] = 'Hi there';
} catch (Exception $e) {
    echo 'Could not modify file.txt:', $e;
}
?>

See Also

  • Phar::offsetSet() - set the contents of an internal file to those of an external file

PharData::isWritable
PharData::offsetUnset
PharData


remove a file from a tar/zip archive

PharData::offsetSet
PharData::setAlias
PharData
PHP Manual

PharData::offsetUnset

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::offsetUnset — remove a file from a tar/zip archive

Description

bool PharData::offsetUnset ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset() language construct.

Parameters

offset

The filename (relative path) to modify in the tar/zip archive.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

Examples

Example #1 A PharData::offsetUnset() example

<?php
$p = new PharData('/path/to/my.zip');
try {
    // deletes file.txt from my.zip by calling offsetUnset
    unset($p['file.txt']);
} catch (Exception $e) {
    echo 'Could not delete file.txt: ', $e;
}
?>

See Also

  • Phar::offsetUnset() - remove a file from a phar

PharData::offsetSet
PharData::setAlias
PharData


dummy function (Phar::setAlias is not valid for PharData)

PharData::offsetUnset
PharData::setDefaultStub
PharData
PHP Manual

PharData::setAlias

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setAlias — dummy function (Phar::setAlias is not valid for PharData)

Description

bool PharData::setAlias ( string $alias )

Non-executable tar/zip archives cannot have an alias, so this method simply throws an exception.

Parameters

alias

A shorthand string that this archive can be referred to in phar stream wrapper access. This parameter is ignored.

Return Values

Errors/Exceptions

Throws PharException on all method calls

See Also

  • Phar::setAlias() - Set the alias for the Phar archive

PharData::offsetUnset
PharData::setDefaultStub
PharData


dummy function (Phar::setDefaultStub is not valid for PharData)

PharData::setAlias
Phar::setMetadata
PharData
PHP Manual

PharData::setDefaultStub

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setDefaultStub — dummy function (Phar::setDefaultStub is not valid for PharData)

Description

void PharData::setDefaultStub ([ string $index [, string $webindex ]] )

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

Parameters

index

Relative path within the phar archive to run if accessed on the command-line

webindex

Relative path within the phar archive to run if accessed through a web browser

Return Values

No value is returned.

Errors/Exceptions

Throws PharException on all method calls

See Also

  • Phar::setDefaultStub() - Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

PharData::setAlias
Phar::setMetadata
PharData


Sets phar archive meta-data

PharData::setDefaultStub
Phar::setSignatureAlgorithm
PharData
PHP Manual

Phar::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setMetadata — Sets phar archive meta-data

Description

void Phar::setMetadata ( mixed $metadata )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

Phar::setMetadata() should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata() should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

Parameters

metadata

Any PHP variable containing information to store that describes the phar archive

Return Values

No value is returned.

Examples

Example #1 A Phar::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.php'] = '<?php echo "hello"';
    $p->setMetadata(array('bootstrap' => 'file.php'));
    var_dump($p->getMetadata());
} catch (Exception $e) {
    echo 'Could not create and/or modify phar:', $e;
}
?>

The above example will output:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

See Also

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

PharData::setDefaultStub
Phar::setSignatureAlgorithm
PharData


set the signature algorithm for a phar and apply it. The

Phar::setMetadata
PharData::setStub
PharData
PHP Manual

Phar::setSignatureAlgorithm

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it. The

Description

void Phar::setSignatureAlgorithm ( int $sigtype )

Note: This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

set the signature algorithm for a phar and apply it. The signature algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::PGP (pgp not yet supported and falls back to SHA-1).

Parameters

sigtype

    One of Phar::MD5,
Phar::SHA1, Phar::SHA256,
Phar::SHA512, or Phar::PGP

Return Values

No value is returned.

Errors/Exceptions

Throws UnexpectedValueException for many errors, BadMethodCallException if called for a zip- or a tar-based phar archive, and a PharException if any problems occur flushing changes to disk.

See Also

  • Phar::getSupportedSignatures() - Return array of supported signature types
  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Phar::setMetadata
PharData::setStub
PharData


dummy function (Phar::setStub is not valid for PharData)

Phar::setSignatureAlgorithm
PharFileInfo
PharData
PHP Manual

PharData::setStub

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setStub — dummy function (Phar::setStub is not valid for PharData)

Description

void PharData::setStub ( string $stub )

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

Parameters

stub

A string or an open stream handle to use as the executable stub for this phar archive. This parameter is ignored.

Return Values

No value is returned.

Errors/Exceptions

Throws PharException on all method calls

See Also

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive

Phar::setSignatureAlgorithm
PharFileInfo
PharData


The PharException class provides a phar-specific exception class for try/catch blocks.

PharException
Rar
PharException
PHP Manual

PharException

(Unknown)

PharException — The PharException class provides a phar-specific exception class for try/catch blocks.

Description

PharException
Rar
PharException
PHP Manual


Sets file-specific permission bits

PharFileInfo
PharFileInfo::compress
PharFileInfo
PHP Manual

PharFileInfo::chmod

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::chmod — Sets file-specific permission bits

Description

void PharFileInfo::chmod ( int $permissions )

PharFileInfo::chmod() allows setting of the executable file permissions bit, as well as read-only bits. Writeable bits are ignored, and set at runtime based on the phar.readonly INI variable. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Parameters

permissions

permissions (see chmod())

Return Values

No value is returned.

Examples

Example #1 A PharFileInfo::chmod() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar('brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.sh'] = '#!/usr/local/lib/php
    <?php echo "hi"; ?>';
    // set executable bit
    $p['file.sh']->chmod(0555);
    var_dump($p['file.sh']->isExecutable());
} catch (Exception $e) {
    echo 'Could not create/modify phar: ', $e;
}
?>

The above example will output:

bool(true)

PharFileInfo
PharFileInfo::compress
PharFileInfo


Compresses the current Phar entry with either zlib or bzip2 compression

PharFileInfo::chmod
PharFileInfo::__construct
PharFileInfo
PHP Manual

PharFileInfo::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression

Description

bool PharFileInfo::compress ( int $compression )

This method compresses the file inside the Phar archive using either bzip2 compression or zlib compression. The bzip2 or zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed, the respective extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

Examples

Example #1 A PharFileInfo::compress() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressed(Phar::BZ2));
    $p['myfile.txt']->compress(Phar::BZ2);
    var_dump($file->isCompressed(Phar::BZ2));
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

PharFileInfo::chmod
PharFileInfo::__construct
PharFileInfo


Construct a Phar entry object

PharFileInfo::compress
PharFileInfo::decompress
PharFileInfo
PHP Manual

PharFileInfo::__construct

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::__construct — Construct a Phar entry object

Description

void PharFileInfo::__construct ( string $entry )

This should not be called directly. Instead, a PharFileInfo object is initialized by calling Phar::offsetGet() through array access.

Parameters

entry

The full url to retrieve a file. If you wish to retrieve the information for the file my/file.php from the phar boo.phar, the entry should be phar://boo.phar/my/file.php.

Errors/Exceptions

Throws BadMethodCallException if __construct() is called twice. Throws UnexpectedValueException if the phar URL requested is malformed, the requested phar cannot be opened, or the file can't be found within the phar.

Examples

Example #1 A PharFileInfo::__construct() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['testfile.txt'] = "hi\nthere\ndude";
    $file = $p['testfile.txt'];
    foreach ($file as $line => $text) {
        echo "line number $line: $text";
    }
    // this also works
    $file = new PharFileInfo('phar:///path/to/my.phar/testfile.txt');
    foreach ($file as $line => $text) {
        echo "line number $line: $text";
    }
} catch (Exception $e) {
    echo 'Phar operations failed: ', $e;
}
?>

The above example will output:

line number 1: hi
line number 2: there
line number 3: dude
line number 1: hi
line number 2: there
line number 3: dude

PharFileInfo::compress
PharFileInfo::decompress
PharFileInfo


Decompresses the current Phar entry within the phar

PharFileInfo::__construct
PharFileInfo::delMetadata
PharFileInfo
PHP Manual

PharFileInfo::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharFileInfo::decompress — Decompresses the current Phar entry within the phar

Description

bool PharFileInfo::decompress ( void )

This method decompresses the file inside the Phar archive. Depending on how the file is compressed, the bzip2 or zlib extensions must be enabled to take advantage of this feature. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

Examples

Example #1 A PharFileInfo::decompress() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    $file->compress(Phar::GZ);
    var_dump($file->isCompressed());
    $p['myfile.txt']->decompress();
    var_dump($file->isCompressed());
} catch (Exception $e) {
    echo 'Create/modify failed for my.phar: ', $e;
}
?>

The above example will output:

int(4096)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

PharFileInfo::__construct
PharFileInfo::delMetadata
PharFileInfo


Deletes the metadata of the entry

PharFileInfo::decompress
PharFileInfo::getCRC32
PharFileInfo
PHP Manual

PharFileInfo::delMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

PharFileInfo::delMetadata — Deletes the metadata of the entry

Description

bool PharFileInfo::delMetadata ( void )

Deletes the metadata of the entry, if any.

Parameters

No parameters.

Return Values

Returns TRUE if successful, FALSE if the entry had no metadata. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Errors/Exceptions

Throws PharException if errors occurred while flushing changes to disk, and BadMethodCallException if write access is disabled.

Examples

Example #1 A PharFileInfo::delMetaData() example

<?php
try {
    $a = new Phar('myphar.phar');
    $a['hi'] = 'hi';
    var_dump($a['hi']->delMetadata());
    $a['hi']->setMetadata('there');
    var_dump($a['hi']->delMetadata());
    var_dump($a['hi']->delMetadata());
} catch (Exception $e) {
    // handle errors
}
?>

The above example will output:

bool(false)
bool(true)
bool(false)

See Also

  • PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

PharFileInfo::decompress
PharFileInfo::getCRC32
PharFileInfo


Returns the actual size of the file (with compression) inside the Phar archive

PharFileInfo::getCRC32
PharFileInfo::getMetaData
PharFileInfo
PHP Manual

PharFileInfo::getCompressedSize

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive

Description

int PharFileInfo::getCompressedSize ( void )

This returns the size of the file within the Phar archive. Uncompressed files will return the same value for getCompressedSize as they will with filesize()

Return Values

The size in bytes of the file within the Phar archive on disk.

Examples

Example #1 A PharFileInfo::getCompressedSize() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    echo $file->getCompressedSize();
} catch (Exception $e) {
    echo 'Write operations failed on my.phar: ', $e;
}
?>

The above example will output:

2

See Also

  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compressFiles() - Compresses all files in the current Phar archive

PharFileInfo::getCRC32
PharFileInfo::getMetaData
PharFileInfo


Returns CRC32 code or throws an exception if CRC has not been verified

PharFileInfo::delMetadata
PharFileInfo::getCompressedSize
PharFileInfo
PHP Manual

PharFileInfo::getCRC32

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified

Description

int PharFileInfo::getCRC32 ( void )

This returns the crc32() checksum of the file within the Phar archive.

Return Values

The crc32() checksum of the file within the Phar archive.

Errors/Exceptions

Throws BadMethodCallException if the file has not yet had its CRC32 verified. This should be impossible with normal use, as the CRC is verified upon opening the file for reading or writing.

Examples

Example #1 A PharFileInfo::getCRC32() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    echo $file->getCRC32();
} catch (Exception $e) {
    echo 'Write operations on my.phar.phar failed: ', $e;
}
?>

The above example will output:

3633523372

PharFileInfo::delMetadata
PharFileInfo::getCompressedSize
PharFileInfo


Returns file-specific meta-data saved with a file

PharFileInfo::getCompressedSize
PharFileInfo::getPharFlags
PharFileInfo
PHP Manual

PharFileInfo::getMetaData

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getMetaData — Returns file-specific meta-data saved with a file

Description

mixed PharFileInfo::getMetaData ( void )

Return meta-data that was saved in the Phar archive's manifest for this file.

Parameters

Return Values

any PHP variable that can be serialized and is stored as meta-data for the file, or NULL if no meta-data is stored.

Examples

Example #1 A PharFileInfo::getMetaData() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.txt'] = 'hello';
    $p['file.txt']->setMetaData(array('user' => 'bill', 'mime-type' => 'text/plain'));
    var_dump($p['file.txt']->getMetaData());
} catch (Exception $e) {
    echo 'Could not create/modify brandnewphar.phar: ', $e;
}
?>

The above example will output:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

See Also

  • PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

PharFileInfo::getCompressedSize
PharFileInfo::getPharFlags
PharFileInfo


Returns the Phar file entry flags

PharFileInfo::getMetaData
PharFileInfo::hasMetadata
PharFileInfo
PHP Manual

PharFileInfo::getPharFlags

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getPharFlags — Returns the Phar file entry flags

Description

int PharFileInfo::getPharFlags ( void )

This returns the flags set in the manifest for a Phar. This will always return 0 in the current implementation.

Return Values

The Phar flags (always 0 in the current implementation)

Examples

Example #1 A PharFileInfo::getPharFlags() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->getPharFlags());
} catch (Exception $e) {
    echo 'Could not create/modify my.phar: ', $e;
}
?>

The above example will output:

int(0)

PharFileInfo::getMetaData
PharFileInfo::hasMetadata
PharFileInfo


Returns the metadata of the entry

PharFileInfo::getPharFlags
PharFileInfo::isCRCChecked
PharFileInfo
PHP Manual

PharFileInfo::hasMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

PharFileInfo::hasMetadata — Returns the metadata of the entry

Description

bool PharFileInfo::hasMetadata ( void )

Returns the metadata of a file within a phar archive.

Parameters

No parameters.

Return Values

Returns FALSE if no metadata is set or is NULL, TRUE if metadata is not NULL

See Also

  • PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

PharFileInfo::getPharFlags
PharFileInfo::isCRCChecked
PharFileInfo


Returns whether the entry is compressed

PharFileInfo::isCRCChecked
PharFileInfo::isCompressedBZIP2
PharFileInfo
PHP Manual

PharFileInfo::isCompressed

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressed — Returns whether the entry is compressed

Description

bool PharFileInfo::isCompressed ([ int $compression_type = 9021976 ] )

This returns whether a file is compressed within a Phar archive with either Gzip or Bzip2 compression.

Parameters

compression_type

One of Phar::GZ or Phar::BZ2, defaults to any compression.

Return Values

TRUE if the file is compressed within the Phar archive, FALSE if not.

Examples

Example #1 A PharFileInfo::isCompressed() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile2.txt']->setCompressedGZ();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    var_dump($file->isCompressed());
    var_dump($file2->isCompressed());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compressFiles() - Compresses all files in the current Phar archive

PharFileInfo::isCRCChecked
PharFileInfo::isCompressedBZIP2
PharFileInfo


Returns whether the entry is compressed using bzip2

PharFileInfo::isCompressed
PharFileInfo::isCompressedGZ
PharFileInfo
PHP Manual

PharFileInfo::isCompressedBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2

Description

bool PharFileInfo::isCompressedBZIP2 ( void )

Note: This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

This returns whether a file is compressed within a Phar archive with Bzip2 compression.

Return Values

TRUE if the file is compressed within the Phar archive using Bzip2, FALSE if not.

Examples

Example #1 A PharFileInfo::isCompressedBZIP2() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile3.txt'] = 'hi';
    $p['myfile2.txt']->setCompressedGZ();
    $p['myfile3.txt']->setCompressedBZIP2();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    $file3 = $p['myfile3.txt'];
    var_dump($file->isCompressedBZIP2());
    var_dump($file2->isCompressedBZIP2());
    var_dump($file3->isCompressedBZIP2());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

PharFileInfo::isCompressed
PharFileInfo::isCompressedGZ
PharFileInfo


Returns whether the entry is compressed using gz

PharFileInfo::isCompressedBZIP2
PharFileInfo::setCompressedBZIP2
PharFileInfo
PHP Manual

PharFileInfo::isCompressedGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz

Description

bool PharFileInfo::isCompressedGZ ( void )

Note: This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

This returns whether a file is compressed within a Phar archive with Gzip compression.

Return Values

TRUE if the file is compressed within the Phar archive using Gzip, FALSE if not.

Examples

Example #1 A PharFileInfo::isCompressedGZ() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile3.txt'] = 'hi';
    $p['myfile2.txt']->setCompressedGZ();
    $p['myfile3.txt']->setCompressedBZIP2();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    $file3 = $p['myfile3.txt'];
    var_dump($file->isCompressedGZ());
    var_dump($file2->isCompressedGZ());
    var_dump($file3->isCompressedGZ());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(true)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

PharFileInfo::isCompressedBZIP2
PharFileInfo::setCompressedBZIP2
PharFileInfo


Returns whether file entry has had its CRC verified

PharFileInfo::hasMetadata
PharFileInfo::isCompressed
PharFileInfo
PHP Manual

PharFileInfo::isCRCChecked

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified

Description

bool PharFileInfo::isCRCChecked ( void )

This returns whether a file within a Phar archive has had its CRC verified.

Return Values

TRUE if the file has had its CRC verified, FALSE if not.

Examples

Example #1 A PharFileInfo::isCRCChecked() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCRCChecked());
} catch (Exception $e) {
    echo 'Create/modify operations failed on my.phar: ', $e;
}
?>

The above example will output:

bool(true)

PharFileInfo::hasMetadata
PharFileInfo::isCompressed
PharFileInfo


Compresses the current Phar entry within the phar using Bzip2 compression

PharFileInfo::isCompressedGZ
PharFileInfo::setCompressedGZ
PharFileInfo
PHP Manual

PharFileInfo::setCompressedBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setCompressedBZIP2 — Compresses the current Phar entry within the phar using Bzip2 compression

Description

bool PharFileInfo::setCompressedBZIP2 ( void )

Note: This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

This method compresses the file inside the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if the file is already compressed using gzip compression, the zlib extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2 extension is not available.

Examples

Example #1 A PharFileInfo::setCompressedBZIP2() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressedBZIP2());
    $p['myfile.txt']->setCompressedBZIP2();
    var_dump($file->isCompressedBZIP2());
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

PharFileInfo::isCompressedGZ
PharFileInfo::setCompressedGZ
PharFileInfo


Compresses the current Phar entry within the phar using gz compression

PharFileInfo::setCompressedBZIP2
PharFileInfo::setMetaData
PharFileInfo
PHP Manual

PharFileInfo::setCompressedGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setCompressedGZ — Compresses the current Phar entry within the phar using gz compression

Description

bool PharFileInfo::setCompressedGZ ( void )

Note: This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

This method compresses the file inside the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed using bzip2 compression, the bzip2 extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the zlib extension is not available.

Examples

Example #1 A PharFileInfo::setCompressedGZ() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressedGZ());
    $p['myfile.txt']->setCompressedGZ();
    var_dump($file->isCompressedGZ());
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?>

The above example will output:

bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

PharFileInfo::setCompressedBZIP2
PharFileInfo::setMetaData
PharFileInfo


Sets file-specific meta-data saved with a file

PharFileInfo::setCompressedGZ
PharFileInfo::setUncompressed
PharFileInfo
PHP Manual

PharFileInfo::setMetaData

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setMetaData — Sets file-specific meta-data saved with a file

Description

void PharFileInfo::setMetaData ( mixed $metadata )

PharFileInfo::setMetaData() should only be used to store customized data in a file that cannot be represented with existing information stored with a file. Meta-data can significantly slow down the performance of loading a phar archive if the data is large, or if there are many files containing meta-data. It is important to note that file permissions are natively supported inside a phar; it is possible to set them with the PharFileInfo::chmod() method. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Some possible uses for meta-data include passing a user/group that should be set when a file is extracted from the phar to disk. Other uses could include explicitly specifying a MIME type to return. However, any useful data that describes a file, but should not be contained inside of it may be stored.

Parameters

metadata

Any PHP variable containing information to store alongside a file

Return Values

No value is returned.

Examples

Example #1 A PharFileInfo::setMetaData() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.txt'] = 'hello';
    $p['file.txt']->setMetaData(array('user' => 'bill', 'mime-type' => 'text/plain'));
    var_dump($p['file.txt']->getMetaData());
} catch (Exception $e) {
    echo 'Could not create/modify phar: ', $e;
}
?>

The above example will output:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

See Also

  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

PharFileInfo::setCompressedGZ
PharFileInfo::setUncompressed
PharFileInfo


Uncompresses the current Phar entry within the phar, if it is compressed

PharFileInfo::setMetaData
PharException
PharFileInfo
PHP Manual

PharFileInfo::setUncompressed

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setUncompressed — Uncompresses the current Phar entry within the phar, if it is compressed

Description

bool PharFileInfo::setUncompressed ( void )

Note: This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

This method decompresses the file inside the Phar archive. Depending on how the file is compressed, the bzip2 or zlib extensions must be enabled to take advantage of this feature. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

Examples

Example #1 A PharFileInfo::setUncompressed() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    $file->setCompressedGZ();
    var_dump($file->isCompressed());
    $p['myfile.txt']->setUncompressed();
    var_dump($file->isCompressed());
} catch (Exception $e) {
    echo 'Create/modify failed for my.phar: ', $e;
}
?>

The above example will output:

bool(true)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

PharFileInfo::setMetaData
PharException
PharFileInfo


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

POSIX_F_OK (integer)
Check whether the file exists.
POSIX_R_OK (integer)
Check whether the file exists and has read permissions.
POSIX_W_OK (integer)
Check whether the file exists and has write permissions.
POSIX_X_OK (integer)
Check whether the file exists and has execute permissions.
POSIX_S_IFBLK (integer)
Block special file
POSIX_S_IFCHR (integer)
Character special file
POSIX_S_IFIFO (integer)
FIFO (named pipe) special file
POSIX_S_IFREG (integer)
Normal file
POSIX_S_IFSOCK (integer)
Socket

Note: These constants are available since PHP 5.1.0. Please also note that some of them may not be available in your system.

Resource Types
POSIX Functions
POSIX


Installation

POSIX functions are enabled by default. You can disable POSIX-like functions with --disable-posix.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
POSIX


Preface

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

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

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

Authors and Contributors

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

Authors and Editors

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

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

User Note Maintainers

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

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

PHP Manual
Getting Started


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The following two tables lists all constants defined by the ps extension.

Contants for line caps
Name | Meaning
ps_LINECAP_BUTT |
ps_LINECAP_ROUND |
ps_LINECAP_SQUARED |

Contants for line joins
Name | Meaning
ps_LINEJOIN_MITER |
ps_LINEJOIN_ROUND |
ps_LINEJOIN_BEVEL |

Resource Types
PS Functions
PS


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/ps.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You need at least PHP 4.3.0 and pslib >= 0.1.12. The ps library (pslib) is available at » http://pslib.sourceforge.net/.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension defines a PostScript document resource returned by ps_new().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
PS


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

PSPELL_FAST (integer)
PSPELL_NORMAL (integer)
PSPELL_BAD_SPELLERS (integer)
PSPELL_RUN_TOGETHER (integer)
Resource Types
Pspell Functions
Pspell


Installation

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.

Note: Note to Win32 Users
In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: aspell-15.dll from the bin folder of the aspell installation.
Win32 support is available only in PHP 4.3.3 and later versions. Also, at least aspell version 0.50 is required.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To compile PHP with pspell support, you need the aspell library, available from » http://aspell.sourceforge.net/.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Pspell


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

RADIUS_ACCESS_REQUEST ()
Authentication Request
RADIUS_ACCESS_ACCEPT ()
Access accepted
RADIUS_ACCESS_REJECT ()
Access rejected
RADIUS_ACCOUNTING_REQUEST ()
Accounting request
RADIUS_ACCOUNTING_RESPONSE ()
Accounting response
RADIUS_ACCESS_CHALLENGE ()
Accsess challenge
RADIUS_USER_NAME (string)
Username
RADIUS_USER_PASSWORD (string)
Password
RADIUS_CHAP_PASSWORD (string)
Chap Password: chappass = md5(ident + plaintextpass + challenge)
RADIUS_NAS_IP_ADDRESS (string)
NAS IP-Adress
RADIUS_NAS_PORT (int)
NAS Port
RADIUS_SERVICE_TYPE (int)

Type of Service, one of:

  • RADIUS_LOGIN
  • RADIUS_FRAMED
  • RADIUS_CALLBACK_LOGIN
  • RADIUS_CALLBACK_FRAMED
  • RADIUS_OUTBOUND
  • RADIUS_ADMINISTRATIVE
  • RADIUS_NAS_PROMPT
  • RADIUS_AUTHENTICATE_ONLY
  • RADIUS_CALLBACK_NAS_PROMPT

RADIUS_FRAMED_PROTOCOL (int)

Framed Protocol, one of:

  • RADIUS_PPP
  • RADIUS_SLIP
  • RADIUS_ARAP
  • RADIUS_GANDALF
  • RADIUS_XYLOGICS

RADIUS_FRAMED_IP_ADDRESS (string)
IP-Address
RADIUS_FRAMED_IP_NETMASK (string)
Netmask
RADIUS_FRAMED_ROUTING (int)
Routing
RADIUS_FILTER_ID (string)
Filter ID
RADIUS_FRAMED_MTU (int)
MTU
RADIUS_FRAMED_COMPRESSION (int)

Compression, one of:

  • RADIUS_COMP_NONE
  • RADIUS_COMP_VJ
  • RADIUS_COMP_IPXHDR

RADIUS_LOGIN_IP_HOST (string)
Login IP Host
RADIUS_LOGIN_SERVICE (int)
Login Service
RADIUS_LOGIN_TCP_PORT (int)
Login TCP Port
RADIUS_REPLY_MESSAGE (string)
Reply Message
RADIUS_CALLBACK_NUMBER (string)
Callback Number
RADIUS_CALLBACK_ID (string)
Callback ID
RADIUS_FRAMED_ROUTE (string)
Framed Route
RADIUS_FRAMED_IPX_NETWORK (string)
Framed IPX Network
RADIUS_STATE (string)
State
RADIUS_CLASS (int)
Class
RADIUS_VENDOR_SPECIFIC (int)
Vendor specific attribute
RADIUS_SESSION_TIMEOUT (int)
Session timeout
RADIUS_IDLE_TIMEOUT (int)
Idle timeout
RADIUS_TERMINATION_ACTION (int)
Termination action
RADIUS_CALLED_STATION_ID (int)
Called Station Id
RADIUS_CALLING_STATION_ID (string)
Calling Station Id
RADIUS_NAS_IDENTIFIER (int)
NAS ID
RADIUS_PROXY_STATE (int)
Proxy State
RADIUS_LOGIN_LAT_SERVICE (int)
Login LAT Service
RADIUS_LOGIN_LAT_NODE (int)
Login LAT Node
RADIUS_LOGIN_LAT_GROUP (int)
Login LAT Group
RADIUS_FRAMED_APPLETALK_LINK (int)
Framed Appletalk Link
RADIUS_FRAMED_APPLETALK_NETWORK (int)
Framed Appletalk Network
RADIUS_FRAMED_APPLETALK_ZONE (int)
Framed Appletalk Zone
RADIUS_CHAP_CHALLENGE (string)
Challenge
RADIUS_NAS_PORT_TYPE (int)

NAS port type, one of:

  • RADIUS_ASYNC
  • RADIUS_SYNC
  • RADIUS_ISDN_SYNC
  • RADIUS_ISDN_ASYNC_V120
  • RADIUS_ISDN_ASYNC_V110
  • RADIUS_VIRTUAL
  • RADIUS_PIAFS
  • RADIUS_HDLC_CLEAR_CHANNEL
  • RADIUS_X_25
  • RADIUS_X_75
  • RADIUS_G_3_FAX
  • RADIUS_SDSL
  • RADIUS_ADSL_CAP
  • RADIUS_ADSL_DMT
  • RADIUS_IDSL
  • RADIUS_ETHERNET
  • RADIUS_XDSL
  • RADIUS_CABLE
  • RADIUS_WIRELESS_OTHER
  • RADIUS_WIRELESS_IEEE_802_11

RADIUS_PORT_LIMIT (int)
Port Limit
RADIUS_LOGIN_LAT_PORT (int)
Login LAT Port
RADIUS_CONNECT_INFO (string)
Connect info
RADIUS_ACCT_STATUS_TYPE (int)

Accounting status type, one of:

  • RADIUS_START
  • RADIUS_STOP
  • RADIUS_ACCOUNTING_ON
  • RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (int)
Accounting delay time
RADIUS_ACCT_INPUT_OCTETS (int)
Accounting input bytes
RADIUS_ACCT_OUTPUT_OCTETS (int)
Accounting output bytes
RADIUS_ACCT_SESSION_ID (int)
Accounting session ID
RADIUS_ACCT_AUTHENTIC (int)

Accounting authentic, one of:

  • RADIUS_AUTH_RADIUS
  • RADIUS_AUTH_LOCAL
  • RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (int)
Accounting session time
RADIUS_ACCT_INPUT_PACKETS (int)
Accounting input packets
RADIUS_ACCT_OUTPUT_PACKETS (int)
Accounting output packets
RADIUS_ACCT_TERMINATE_CAUSE (int)

Accounting terminate cause, one of:

  • RADIUS_TERM_USER_REQUEST
  • RADIUS_TERM_LOST_CARRIER
  • RADIUS_TERM_LOST_SERVICE
  • RADIUS_TERM_IDLE_TIMEOUT
  • RADIUS_TERM_SESSION_TIMEOUT
  • RADIUS_TERM_ADMIN_RESET
  • RADIUS_TERM_ADMIN_REBOOT
  • RADIUS_TERM_PORT_ERROR
  • RADIUS_TERM_NAS_ERROR
  • RADIUS_TERM_NAS_REQUEST
  • RADIUS_TERM_NAS_REBOOT
  • RADIUS_TERM_PORT_UNNEEDED
  • RADIUS_TERM_PORT_PREEMPTED
  • RADIUS_TERM_PORT_SUSPENDED
  • RADIUS_TERM_SERVICE_UNAVAILABLE
  • RADIUS_TERM_CALLBACK
  • RADIUS_TERM_USER_ERROR
  • RADIUS_TERM_HOST_REQUEST

RADIUS_ACCT_MULTI_SESSION_ID (string)
Accounting multi session ID
RADIUS_ACCT_LINK_COUNT (int)
Accounting link count
RADIUS_VENDOR_MICROSOFT (int)

Microsoft specific vendor attributes (» RFC 2548), one of:

  • RADIUS_MICROSOFT_MS_CHAP_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP_ERROR
  • RADIUS_MICROSOFT_MS_CHAP_PW_1
  • RADIUS_MICROSOFT_MS_CHAP_PW_2
  • RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW
  • RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES
  • RADIUS_MICROSOFT_MS_RAS_VENDOR
  • RADIUS_MICROSOFT_MS_CHAP_DOMAIN
  • RADIUS_MICROSOFT_MS_CHAP_CHALLENGE
  • RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS
  • RADIUS_MICROSOFT_MS_BAP_USAGE
  • RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD
  • RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT
  • RADIUS_MICROSOFT_MS_MPPE_SEND_KEY
  • RADIUS_MICROSOFT_MS_MPPE_RECV_KEY
  • RADIUS_MICROSOFT_MS_RAS_VERSION
  • RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON
  • RADIUS_MICROSOFT_MS_FILTER
  • RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE
  • RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE
  • RADIUS_MICROSOFT_MS_CHAP2_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP2_SUCCESS
  • RADIUS_MICROSOFT_MS_CHAP2_PW
  • RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_ARAP_CHALLENGE

Resource Types
Examples
Radius


Examples

Howto start?

  • get a radius resource
  • configure the library
  • create the request
  • put attributes
  • send the request
  • receive attributes
  • close the radius resource (optional)

Take also a look at the examples in this package.

The package contains an example php script. This script demonstrates howto authenticate with radius using PAP or CHAP (md5). If you authenticate with Microsoft Radius servers then its not possible to use CHAP (md5). If you would like to authenticate with Microsoft Servers you have to use MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4, sha1 and des to generate the right data. The enclosed examples demonstrate all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the MS-CHAP to work you need the mcrypt and the mhash extension, starting with version 1.2 of the package, the mcrypt extension is no longer needed.

Predefined Constants
Radius Functions
Radius


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/radius.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Radius


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

RAR_HOST_MSDOS (integer)
Use RarEntry::HOST_MSDOS instead.
RAR_HOST_OS2 (integer)
Use RarEntry::HOST_OS2 instead.
RAR_HOST_WIN32 (integer)
Use RarEntry::HOST_WIN32 instead.
RAR_HOST_UNIX (integer)
Use RarEntry::HOST_UNIX instead.
RAR_HOST_BEOS (integer)
Use RarEntry::HOST_BEOS instead.
Resource Types
Examples
Rar


Examples

Example #1 On-the-fly decompression

<?php

if (!array_key_exists("i", $_GET) || !is_numeric($_GET["i"]))
    die("Index unspecified or non-numeric");
$index = (int) $_GET["i"];

$arch = RarArchive::open("example.rar");
if ($arch === FALSE)
    die("Cannot open example.rar");

$entries = $arch->list();
if ($entries === FALSE)
    die("Cannot retrieve entries");

if (!array_key_exists($index, $entries))
    die("No such index: $index");

$orfilename = $entries[$index]->getName(); //UTF-8 encoded

$filesize = $entries[$index]->getUnpackedSize();

/* you could check HTTP_IF_MODIFIED_SINCE here and compare with
 * $entries[$index]->getFileTime(). You could also send a
 * "Last modified" header */

$fp = $entries[$index]->getStream();
if ($fp === FALSE)
    die("Cannot open file with index $index insided the archive.");

$arch->close(); //no longer needed; stream is independent

function detectUserAgent() {
    if (!array_key_exists('HTTP_USER_AGENT', $_SERVER))
        return "Other";

    $uas = $_SERVER['HTTP_USER_AGENT'];
    if (preg_match("@Opera/@", $uas))
        return "Opera";
    if (preg_match("@Firefox/@", $uas))
        return "Firefox";
    if (preg_match("@Chrome/@", $uas))
        return "Chrome";
    if (preg_match("@MSIE ([0-9.]+);@", $uas, $matches)) {
        if (((float)$matches[1]) >= 7.0)
            return "IE";
    }

    return "Other";
}

/*
 * We have 3 options:
 * - For FF and Opera, which support RFC 2231, use that format.
 * - For IE and Chrome, use attwithfnrawpctenclong
 *   (http://greenbytes.de/tech/tc2231/#attwithfnrawpctenclong)
 * - For the others, convert to ISO-8859-1, if possible
 */
$formatRFC2231 = 'Content-Disposition: attachment; filename*=UTF-8\'\'%s';
$formatDef = 'Content-Disposition: attachment; filename="%s"';

switch (detectUserAgent()) {
    case "Opera":
    case "Firefox":
        $orfilename = rawurlencode($orfilename);
        $format = $formatRFC2231;
        break;

    case "IE":
    case "Chrome":
        $orfilename = rawurlencode($orfilename);
        $format = $formatDef;
        break;
    default:
        if (function_exists('iconv'))
            $orfilename =
                @iconv("UTF-8", "ISO-8859-1//TRANSLIT", $orfilename);
        $format = $formatDef;
}

header(sprintf($format, $orfilename));
//cannot send error messages from now on (headers already sent)

//replace by real content type, perhaps infering from the file extension
$contentType = "application/octet-stream";
header("Content-Type: $contentType");

header("Content-Transfer-Encoding: binary");

header("Content-Length: $filesize");

if ($_SERVER['REQUEST_METHOD'] == "HEAD")
    die();

while (!feof($fp)) {
    $s = @fread($fp, 8192);
    if ($s === false)
        break; //useless to send error messages

    echo $s;
}

This example opens a RAR file and presents the requested file inside the RAR archive for download to the client.

Example #2 RAR extension filesystem extraction example

<?php

$rar_file = rar_open('example.rar') or die("Can't open Rar archive");

$entries = rar_list($rar_file);

foreach ($entries as $entry) {
    echo 'Filename: ' . $entry->getName() . "\n";
    echo 'Packed size: ' . $entry->getPackedSize() . "\n";
    echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";

    $entry->extract('/dir/extract/to/');
}

rar_close($rar_file);

?>

This example opens a RAR file archive and extracts each entry to the specified directory.

Predefined Constants
RarArchive
Rar


Installation

Rar is currently available through PECL » http://pecl.php.net/package/rar.

Also you can use the PECL installer to install the Rar extension, using the following command: pecl -v install rar.

You can always download the tar.gz package and install Rar by hand:

Example #1 Rar installation

gunzip rar-xxx.tgz
tar -xvf rar-xxx.tar
cd rar-xxx
phpize
./configure && make && make install

Windows users will enable php_rar.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Resource Types

This extension registers two internal classes: The archive representations returned by rar_open() and the entry representations returned by rar_list() and rar_entry_get().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Rar


Close RAR archive and free all resources.

RarArchive
RarArchive::getComment
RarArchive
PHP Manual

RarArchive::close

rar_close

(PECL rar >= 2.0.0)

RarArchive::close -- rar_close — Close RAR archive and free all resources.

Description

Object oriented style (method):

public bool RarArchive::close ( void )

Procedural style:

bool rar_close ( RarArchive $rarfile )

Close RAR archive and free all allocated resources.

Parameters

rarfile

A RarArchive object, opened with rar_open().

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
2.0.0 | The RAR entries returned by RarArchive::getEntry and RarArchive::list are now invalidated when calling this method. This means that all instance methods called for such entries and not guaranteed to succeed.

Examples

Example #1 Object oriented style

<?php
$rar_arch = RarArchive::open('latest_winrar.rar');
echo $rar_arch."\n";
$rar_arch->close();
echo $rar_arch."\n";
?>

The above example will output something similar to:

RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)

Example #2 Procedural style

<?php
$rar_arch = rar_open('latest_winrar.rar');
echo $rar_arch."\n";
rar_close($rar_arch);
echo $rar_arch."\n";
?>

RarArchive
RarArchive::getComment
RarArchive


Get comment text from the RAR archive.

RarArchive::close
RarArchive::getEntry
RarArchive
PHP Manual

RarArchive::getComment

rar_comment_get

(PECL rar >= 2.0.0)

RarArchive::getComment -- rar_comment_get — Get comment text from the RAR archive.

Description

Object oriented style (method):

public string RarArchive::getComment ( void )

Procedural style:

string rar_comment_get ( RarArchive $rarfile )

Get the (global) comment stored in the RAR archive. It may be up to 64 KiB long.

Note: This extension does not support comments at the entry level.

Parameters

rarfile

A RarArchive object, opened with rar_open().

Return Values

Returns the comment or NULL if there is none.

Note: RAR has currently no support for unicode comments. The encoding of the result of this function is not specified, but it will probably be Windows-1252.

Examples

Example #1 Object oriented style

<?php
$rar_arch = RarArchive::open('commented.rar');
echo $rar_arch->getComment();
?>

The above example will output something similar to:

This is the comment of the file commented.rar.

Example #2 Procedural style

<?php
$rar_arch = rar_open('commented.rar');
echo rar_comment_get($rar_arch);
?>

RarArchive::close
RarArchive::getEntry
RarArchive


Get entry object from the RAR archive.

RarArchive::getComment
RarArchive::isSolid
RarArchive
PHP Manual

RarArchive::getEntry

rar_entry_get

(PECL rar >= 2.0.0)

RarArchive::getEntry -- rar_entry_get — Get entry object from the RAR archive.

Description

Object oriented style (method):

public RarEntry RarArchive::getEntry ( string $entryname )

Procedural style:

RarEntry rar_entry_get ( RarArchive $rarfile , string $entryname )

Get entry object (file or directory) from the RAR archive.

Note: You can also get entry objects using RarArchive::list.

Parameters

rarfile

A RarArchive object, opened with rar_open().

entryname

Path to the entry within the RAR archive.

Note: The path must be the same returned by RarEntry::getName.

Return Values

Returns the matching RarEntry object or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$rar_arch = RarArchive::open('solid.rar');
if ($rar_arch === FALSE)
    die("Could not open RAR archive.");
$rar_entry = $rar_arch->getEntry('tese.txt');
if ($rar_entry === FALSE)
    die("Could get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
$rar_arch->close();
?>

The above example will output something similar to:

RarEntry
RarEntry for file "tese.txt" (23b93a7a)

Example #2 Procedural style

<?php
$rar_arch = rar_open('solid.rar');
if ($rar_arch === FALSE)
    die("Could not open RAR archive.");
$rar_entry = rar_entry_get($rar_arch, 'tese.txt');
if ($rar_entry === FALSE)
    die("Could get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
rar_close($rar_arch);
?>

RarArchive::getComment
RarArchive::isSolid
RarArchive


Check whether the RAR archive is solid.

RarArchive::getEntry
RarArchive::list
RarArchive
PHP Manual

RarArchive::isSolid

rar_solid_is

(PECL rar >= 2.0.0)

RarArchive::isSolid -- rar_solid_is — Check whether the RAR archive is solid.

Description

Object oriented style (method):

public bool RarArchive::isSolid ( void )

Procedural style:

bool rar_solid_is ( RarArchive $rarfile )

Check whether the RAR archive is solid. Individual file extraction is slower on solid archives.

Parameters

rarfile

A RarArchive object, opened with rar_open().

Return Values

Returns TRUE if the archive is solid, FALSE otherwise.

Examples

Example #1 Object oriented style

<?php
$arch1 = RarArchive::open("store_method.rar");
$arch2 = RarArchive::open("solid.rar");
echo "$arch1: " . ($arch1->isSolid()?'yes':'no') ."\n";
echo "$arch2: " . ($arch2->isSolid()?'yes':'no') . "\n";
?>

The above example will output something similar to:

RAR Archive "C:\php_rar\trunk\tests\store_method.rar": no
RAR Archive "C:\php_rar\trunk\tests\solid.rar": yes

Example #2 Procedural style

<?php
$arch1 = rar_open("store_method.rar");
$arch2 = rar_open("solid.rar");
echo "$arch1: " . (rar_solid_is($arch1)?'yes':'no') ."\n";
echo "$arch2: " . (rar_solid_is($arch2)?'yes':'no') . "\n";
?>

RarArchive::getEntry
RarArchive::list
RarArchive


Get entries full list from the RAR archive.

RarArchive::isSolid
RarArchive::open
RarArchive
PHP Manual

RarArchive::list

rar_list

(PECL rar >= 2.0.0)

RarArchive::list -- rar_list — Get entries full list from the RAR archive.

Description

Object oriented style (method):

public array RarArchive::list ( void )

Procedural style:

array rar_list ( RarArchive $rarfile )

Get entries list (files and directories) from the RAR archive.

Parameters

rarfile

A RarArchive object, opened with rar_open().

Return Values

rar_list() returns array of RarEntry objects or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$rar_arch = RarArchive::open('solid.rar');
if ($rar_arch === FALSE)
    die("Could not open RAR archive.");

$rar_entries = $rar_arch->list();
if ($rar_entries === FALSE)
    die("Could retrieve entries.");

echo "Found " . count($rar_entries) . " entries.\n";

foreach ($rar_entries as $e) {
    echo $e;
    echo "\n";
}
$rar_arch->close();
?>

The above example will output something similar to:

Found 2 entries.
RarEntry for file "tese.txt" (23b93a7a)
RarEntry for file "unrardll.txt" (2ed64b6e)

Example #2 Procedural style

<?php
$rar_arch = rar_open('solid.rar');
if ($rar_arch === FALSE)
    die("Could not open RAR archive.");

$rar_entries = rar_list($rar_arch);
if ($rar_entries === FALSE)
    die("Could retrieve entries.");

echo "Found " . count($rar_entries) . " entries.\n";

foreach ($rar_entries as $e) {
    echo $e;
    echo "\n";
}
rar_close($rar_arch);
?>

RarArchive::isSolid
RarArchive::open
RarArchive


Open RAR archive.

RarArchive::list
RarArchive::__toString
RarArchive
PHP Manual

RarArchive::open

rar_open

(PECL rar >= 2.0.0)

RarArchive::open -- rar_open — Open RAR archive.

Description

Object oriented style (method):

public static RarArchive RarArchive::open ( string $filename [, string $password ] )

Procedural style:

RarArchive rar_open ( string $filename [, string $password ] )

Open specified RAR archive and return RarArchive instance representing it.

Note: If opening a multi-volume archive, the path of the first volume should be passed as the first parameter. Otherwise, not all files will be shown. This is by design.

Parameters

filename

Path to the Rar archive.

password

A plain password, if needed to decrypt the headers. It will also be used by default if encrypted files are found. Note that the files may have different passwords in respect to the headers and among them.

Warning

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

Return Values

Returns the requested RarArchive instance or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$rar_arch = RarArchive::open('encrypted_headers.rar', 'samplepassword');
if ($rar_arch === FALSE)
    die("Failed opening file");

$entries = $rar_arch->list();
if ($entries === FALSE)
    die("Failed fetching entries");

echo "Found " . count($entries) . " files.\n";

if (empty($entries))
    die("No valid entries found.");

$stream = reset($entries)->getStream();
if ($stream === FALSE)
    die("Failed opening first file");

$rar_arch->close();

echo "Content of first one follows:\n";
echo stream_get_contents($stream);

fclose($stream);
?>

The above example will output something similar to:

Found 2 files.
Content of first one follows:
Encrypted file 1 contents.

Example #2 Procedural style

<?php
$rar_arch = rar_open('encrypted_headers.rar', 'samplepassword');
if ($rar_arch === FALSE)
    die("Failed opening file");

$entries = rar_list($rar_arch);
if ($entries === FALSE)
    die("Failed fetching entries");

echo "Found " . count($entries) . " files.\n";

if (empty($entries))
    die("No valid entries found.");

$stream = reset($entries)->getStream();
if ($stream === FALSE)
    die("Failed opening first file");

rar_close($rar_arch);

echo "Content of first one follows:\n";
echo stream_get_contents($stream);

fclose($stream);
?>

RarArchive::list
RarArchive::__toString
RarArchive


Get text representation.

RarArchive::open
RarEntry
RarArchive
PHP Manual

RarArchive::__toString

(PECL rar >= 2.0.0)

RarArchive::__toString — Get text representation.

Description

public void RarArchive::__toString ( void )

Provides a string representation for this RarArchive object. It currently shows the full path name of the archive volume that was opened and whether the resource is valid or was already closed through a call to RarArchive::close.

This method may be used only for debugging purposes, as there are no guarantees as to which information the result contains or how it is formatted.

Parameters

This function has no parameters.

Return Values

A textual representation of this RarArchive object. The content of this representation is unspecified.

Examples

Example #1 RarArchive::__toString example

<?php
$rar_arch = RarArchive::open('latest_winrar.rar');
echo $rar_arch."\n";
$rar_arch->close();
echo $rar_arch."\n";
?>

The above example will output something similar to:

RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)

RarArchive::open
RarEntry
RarArchive


Extract entry from the archive.

RarEntry
RarEntry::getAttr
RarEntry
PHP Manual

RarEntry::extract

(PECL rar >= 0.1)

RarEntry::extract — Extract entry from the archive.

Description

public bool extract ( string $dir [, string $filepath [, string $password ]] )

RarEntry::extract extracts the entry's data. It will create new file in the specified dir with the name identical to the entry's name, unless the second argument is specified. See below for more information.

Parameters

dir

Path to the directory where files should be extracted. This parameter is considered if and only if filepath is not. If both parameters are empty an extraction to the current directory will be attempted.

filepath

Path (relative or absolute) containing the directory and filename of the extracted file. This parameter overrides both the parameter dir and the original file name.

password

The password used to encrypt this entry. If the entry is not encrypted, this value will not be used and can be omitted. If this parameter is omitted and the entry is encrypted, the password given to rar_open(), if any, will be used. If a wrong password is given, either explicitly or implicitly via rar_open(), CRC checking will fail and this method will fail and return FALSE. If no password is given and one is required, this method will fail and return FALSE. You can check whether an entry is encrypted with RarEntry::isEncrypted.

Warning

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 RarEntry::extract example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

$entry->extract('/dir/to'); // create /dir/to/Dir/file.txt
$entry->extract(false, '/dir/to/new_name.txt'); // create /dir/to/new_name.txt

?>

Example #2 How to extract all files in archive:

<?php

/* example by Erik Jenssen aka erix */

$filename = "foobar.rar";
$filepath = "/home/foo/bar/";

$rar_file = rar_open($filepath.$filename);
$list = rar_list($rar_file);
foreach($list as $file) {
    $entry = rar_entry_get($rar_file, $file);
    $entry->extract("."); // extract to the current dir
}
rar_close($rar_file);

?>

See Also

  • RarEntry::getStream - Get file handler for entry.

RarEntry
RarEntry::getAttr
RarEntry


Get attributes of the entry.

RarEntry::extract
RarEntry::getCrc
RarEntry
PHP Manual

RarEntry::getAttr

(PECL rar >= 0.1)

RarEntry::getAttr — Get attributes of the entry.

Description

public int getAttr ( void )

Returns the OS-dependent attributes of the archive entry.

Parameters

This function has no parameters.

Return Values

Returns the attributes or FALSE on error.

Examples

Example #1 RarEntry::getAttr example

<?php

$rar_file = rar_open('example.rar') or die("Can't open Rar archive");

$entry = rar_entry_get($rar_file, 'dir/in/the/archive') or die("Can't find such entry");

$host_os = $entry->getHostOs();
$attr = $entry->getAttr();

switch($host_os) {
    case RAR_HOST_MSDOS:
    case RAR_HOST_OS2:
    case RAR_HOST_WIN32:
    case RAR_HOST_MACOS:
        printf("%c%c%c%c%c%c\n",
                ($attr & 0x08) ? 'V' : '.',
                ($attr & 0x10) ? 'D' : '.',
                ($attr & 0x01) ? 'R' : '.',
                ($attr & 0x02) ? 'H' : '.',
                ($attr & 0x04) ? 'S' : '.',
                ($attr & 0x20) ? 'A' : '.');
        break;
    case RAR_HOST_UNIX:
    case RAR_HOST_BEOS:
        switch ($attr & 0xF000)
        {
            case 0x4000:
                printf("d");
                break;
            case 0xA000:
                printf("l");
                break;
            default:
                printf("-");
                break;
        }
        printf("%c%c%c%c%c%c%c%c%c\n",
                ($attr & 0x0100) ? 'r' : '-',
                ($attr & 0x0080) ? 'w' : '-',
                ($attr & 0x0040) ? (($attr & 0x0800) ? 's':'x'):(($attr & 0x0800) ? 'S':'-'),
                ($attr & 0x0020) ? 'r' : '-',
                ($attr & 0x0010) ? 'w' : '-',
                ($attr & 0x0008) ? (($attr & 0x0400) ? 's':'x'):(($attr & 0x0400) ? 'S':'-'),
                ($attr & 0x0004) ? 'r' : '-',
                ($attr & 0x0002) ? 'w' : '-',
                ($attr & 0x0001) ? 'x' : '-');
        break;
}

rar_close($rar_file);

?>

See Also

  • RarEntry::getHostOs - Get entry host OS.
  • The constants in RarEntry

RarEntry::extract
RarEntry::getCrc
RarEntry


Get CRC of the entry.

RarEntry::getAttr
RarEntry::getFileTime
RarEntry
PHP Manual

RarEntry::getCrc

(PECL rar >= 0.1)

RarEntry::getCrc — Get CRC of the entry.

Description

public string getCrc ( void )

Returns an hexadecimal string representation of the CRC of the archive entry.

Parameters

This function has no parameters.

Return Values

Returns the CRC of the archive entry or FALSE on error.

Changelog

Version | Description
2.0.0 | This method now returns correct values for multiple volume archives.

RarEntry::getAttr
RarEntry::getFileTime
RarEntry


Get entry last modification time.

RarEntry::getCrc
RarEntry::getHostOs
RarEntry
PHP Manual

RarEntry::getFileTime

(PECL rar >= 0.1)

RarEntry::getFileTime — Get entry last modification time.

Description

public string getFileTime ( void )

Gets entry last modification time.

Parameters

This function has no parameters.

Return Values

Returns entry last modification time as string in format YYYY-MM-DD HH:II:SS, or FALSE on error.

RarEntry::getCrc
RarEntry::getHostOs
RarEntry


Get entry host OS.

RarEntry::getFileTime
RarEntry::getMethod
RarEntry
PHP Manual

RarEntry::getHostOs

(PECL rar >= 0.1)

RarEntry::getHostOs — Get entry host OS.

Description

public int getHostOs ( void )

Returns the code of the host OS of the archive entry.

Parameters

This function has no parameters.

Return Values

Returns the code of the host OS, or FALSE on error.

Examples

Example #1 RarEntry::getHostOs example (version >= 2.0.0)

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

switch ($entry->getHostOs()) {
    case RarEntry::HOST_MSDOS:
        echo "MS-DOS\n";
        break;
    case RarEntry::HOST_OS2:
        echo "OS2\n";
        break;
    case RarEntry::HOST_WIN32:
        echo "Win32\n";
        break;
    case RarEntry::HOST_MACOS:
        echo "MacOS\n";
        break;
    case RarEntry::HOST_UNIX:
        echo "Unix/Linux\n";
        break;
    case RarEntry::HOST_BEOS:
        echo "BeOS\n";
        break;
}

?>

Example #2 RarEntry::getHostOs example (version <= 1.0.0)

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

switch ($entry->getHostOs()) {
    case RAR_HOST_MSDOS:
        echo "MS-DOS\n";
        break;
    case RAR_HOST_OS2:
        echo "OS2\n";
        break;
    case RAR_HOST_WIN32:
        echo "Win32\n";
        break;
    case RAR_HOST_MACOS:
        echo "MacOS\n";
        break;
    case RAR_HOST_UNIX:
        echo "Unix/Linux\n";
        break;
    case RAR_HOST_BEOS:
        echo "BeOS\n";
        break;
}

?>

See Also

  • RarEntry::extract - Extract entry from the archive.

RarEntry::getFileTime
RarEntry::getMethod
RarEntry


Get pack method of the entry.

RarEntry::getHostOs
RarEntry::getName
RarEntry
PHP Manual

RarEntry::getMethod

(PECL rar >= 0.1)

RarEntry::getMethod — Get pack method of the entry.

Description

public int getMethod ( void )

RarEntry::getMethod returns number of the method used when adding current archive entry.

Parameters

This function has no parameters.

Return Values

Returns the method number or FALSE on error.

Examples

Example #1 RarEntry::getMethod example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Method number: " . $entry->getMethod();

?>

RarEntry::getHostOs
RarEntry::getName
RarEntry


Get name of the entry.

RarEntry::getMethod
RarEntry::getPackedSize
RarEntry
PHP Manual

RarEntry::getName

(PECL rar >= 0.1)

RarEntry::getName — Get name of the entry.

Description

public string getName ( void )

Returns the name (with path) of the archive entry.

Parameters

This function has no parameters.

Return Values

Returns the entry name as a string, or FALSE on error.

Changelog

Version | Description
2.0.0 | As of version 2.0.0, the returned string is encoded in Unicode/UTF-8.

Examples

Example #1 RarEntry::getName example

<?php

//this example is safe even in pages not encoded in UTF-8
//for those encoded in UTF-8, the call to mb_convert_encoding is unnecessary

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Entry name: " . mb_convert_encoding(
    htmlentities(
        $entry->getName(),
        ENT_COMPAT,
        "UTF-8"
    ),
    "HTML-ENTITIES",
    "UTF-8"
);

?>

RarEntry::getMethod
RarEntry::getPackedSize
RarEntry


Get packed size of the entry.

RarEntry::getName
RarEntry::getStream
RarEntry
PHP Manual

RarEntry::getPackedSize

(PECL rar >= 0.1)

RarEntry::getPackedSize — Get packed size of the entry.

Description

public int getPackedSize ( void )

Get packed size of the archive entry.

Note: Note that on platforms with 32-bit longs (that includes Windows x64), the maximum size returned is capped at 2 GiB. Check the constant PHP_INT_MAX.

Parameters

This function has no parameters.

Return Values

Returns the packed size, or FALSE on error.

Changelog

Version | Description
2.0.0 | This method now returns correct values of packed sizes bigger than 2 GiB on platforms with 64-bit integers and never returns negative values on other platforms.

Examples

Example #1 RarEntry::getPackedSize example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Packed size of " . $entry->getName() . " = " . $entry->getPackedSize() . " bytes";

?>

RarEntry::getName
RarEntry::getStream
RarEntry


Get file handler for entry.

RarEntry::getPackedSize
RarEntry::getUnpackedSize
RarEntry
PHP Manual

RarEntry::getStream

(PECL rar >= 2.0.0)

RarEntry::getStream — Get file handler for entry.

Description

public resource RarEntry::getStream ([ string $password ] )

Returns a file handler that supports read operations. This handler provides on-the-fly decompression for this entry.

The handler is not invalidated by calling rar_close().

Warning

The resulting stream has no integrity verification. In particular, file corruption and decryption with a wrong a key will not be detected. It is the programmer's responsability to use the entry's CRC to check for integrity, if he so wishes.

Parameters

password

The password used to encrypt this entry. If the entry is not encrypted, this value will not be used and can be omitted. If this parameter is omitted and the entry is encrypted, the password given to rar_open(), if any, will be used. If a wrong password is given, either explicitly or implicitly via rar_open(), this method's resulting stream will produce wrong output. If no password is given and one is required, this method will fail and return FALSE. You can check whether an entry is encrypted with RarEntry::isEncrypted.

Return Values

The file handler or FALSE on failure.

Examples

Example #1 RarEntry::getStream example

<?php

$rar_file = rar_open('example.rar');
if ($rar_file === false)
    die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt');
if ($entry === false)
    die("Failed to find such entry");

$stream = $entry->getStream();
if ($stream === false)
    die("Failed to obtain stream.");

rar_close($rar_file); //stream is independent from file

while (!feof($stream)) {
    $buff = fread($stream, 8192);
    if ($buff !== false)
        echo $buff;
    else
        break; //fread error
}

fclose($stream);

?>

See Also

  • RarEntry::extract - Extract entry from the archive.

RarEntry::getPackedSize
RarEntry::getUnpackedSize
RarEntry


Get unpacked size of the entry.

RarEntry::getStream
RarEntry::getVersion
RarEntry
PHP Manual

RarEntry::getUnpackedSize

(PECL rar >= 0.1)

RarEntry::getUnpackedSize — Get unpacked size of the entry.

Description

public int getUnpackedSize ( void )

Get unpacked size of the archive entry.

Note: Note that on platforms with 32-bit longs (that includes Windows x64), the maximum size returned is capped at 2 GiB. Check the constant PHP_INT_MAX.

Parameters

This function has no parameters.

Return Values

Returns the unpacked size, or FALSE on error.

Changelog

Version | Description
2.0.0 | This method now returns correct values of unpacked sizes bigger than 2 GiB on platforms with 64-bit integers and never returns negative values on other platforms.

Return Values

Example #1 RarEntry::getUnpackedSize example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Unpacked size of " . $entry->getName() . " = " . $entry->getPackedSize() . " bytes";

?>

RarEntry::getStream
RarEntry::getVersion
RarEntry


Get minimum version of RAR program required to unpack the entry.

RarEntry::getUnpackedSize
RarEntry::isDirectory
RarEntry
PHP Manual

RarEntry::getVersion

(PECL rar >= 0.1)

RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry.

Description

public int getVersion ( void )

Returns minimum version of RAR program (e.g. WinRAR) required to unpack the entry. It is encoded as 10 * major version + minor version.

Parameters

This function has no parameters.

Return Values

Returns the version or FALSE on error.

Examples

Example #1 RarEntry::getVersion example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Rar version required for unpacking: " . $entry->getVersion();

?>

RarEntry::getUnpackedSize
RarEntry::isDirectory
RarEntry


Test whether an entry represents a directory.

RarEntry::getVersion
RarEntry::isEncrypted
RarEntry
PHP Manual

RarEntry::isDirectory

(PECL rar >= 2.0.0)

RarEntry::isDirectory — Test whether an entry represents a directory.

Description

public bool isDirectory ( void )

Tests whether the current entry is a directory.

Parameters

This function has no parameters.

Return Values

Returns TRUE if this entry is a directory and FALSE otherwise.

Notes

This function is only available starting with version 2.0.0, but one can also test whether an entry is a directory by checking the entry attributes, like this (only works for files compressed in RAR for Windows or Unix):

<?php
//...
//Open file, get entry and store in variable $e...
//...

$isDirectory = (bool) ((($e->getHostOs() == RAR_HOST_WIN32) && ($e->getAttr() & 0x10)) ||
    (($e->getHostOs() == RAR_HOST_UNIX) && (($e->getAttr() & 0xf000) == 0x4000)));

RarEntry::getVersion
RarEntry::isEncrypted
RarEntry


Test whether an entry is encrypted.

RarEntry::isDirectory
RarEntry::__toString
RarEntry
PHP Manual

RarEntry::isEncrypted

(PECL rar >= 2.0.0)

RarEntry::isEncrypted — Test whether an entry is encrypted.

Description

public bool RarEntry::isEncrypted ( void )

Tests whether the current entry contents are encrypted.

Note: The password used may differ between files inside the same RAR archive.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current entry is encrypted and FALSE otherwise.

RarEntry::isDirectory
RarEntry::__toString
RarEntry


Get text representation of entry.

RarEntry::isEncrypted
RarException
RarEntry
PHP Manual

RarEntry::__toString

(PECL rar >= 2.0.0)

RarEntry::__toString — Get text representation of entry.

Description

public string RarEntry::__toString ( void )

RarEntry::__toString returns a textual representation for this entry. It includes whether the entry is a file or a directory (symbolic links and other special objects will be treated as files), the UTF-8 name of the entry and its CRC. The form and content of this representation may be changed in the future, so they cannot be relied upon.

Parameters

This function has no parameters.

Return Values

A textual representation for the entry.

RarEntry::isEncrypted
RarException
RarEntry


Check whether error handling with exceptions is in use.

RarException
RarException::setUsingExceptions
RarException
PHP Manual

RarException::isUsingExceptions

(PECL rar >= 2.0.0)

RarException::isUsingExceptions — Check whether error handling with exceptions is in use.

Description

public static bool RarException::isUsingExceptions ( void )

Checks whether the RAR functions will emit warnings and return error values or whether they will throw exceptions in most of the circumstances (does not include some programmatic errors such as passing the wrong type of arguments).

Parameters

This function has no parameters.

Return Values

Returns TRUE if exceptions are being used, FALSE otherwise.

Examples

Example #1 RarException::isUsingExceptions() example

<?php
//The default is not to use exceptions
var_dump(RarException::isUsingExceptions());
?>

The above example will output something similar to:

bool(false)

See Also

  • RarException::setUsingExceptions - Activate and deactivate error handling with exceptions.

RarException
RarException::setUsingExceptions
RarException


Activate and deactivate error handling with exceptions.

RarException::isUsingExceptions
Zip
RarException
PHP Manual

RarException::setUsingExceptions

(PECL rar >= 2.0.0)

RarException::setUsingExceptions — Activate and deactivate error handling with exceptions.

Description

public static void RarException::setUsingExceptions ( bool $using_exceptions )

If and only if the argument is TRUE, then, instead of emitting warnings and returning a special value indicating error when the UnRAR library encounters an error, an exception of type RarException will be thrown.

Exceptions will also be thrown for the following errors, which occur outside the library (their error code will be -1):

  • attempting some operations on a closed RarArchive object or a RarEntry object relative to the first;
  • attempting to get an entry that does not exist with RarArchive::getEntry.

Parameters

using_exceptions

Should be TRUE to activate exception throwing, FALSE to deactivate (the default).

Examples

Example #1 RarException::setUsingExceptions() example

<?php
var_dump(RarException::isUsingExceptions());
$arch = RarArchive::open("does_not_exist.rar");
var_dump($arch);

RarException::setUsingExceptions(true);
var_dump(RarException::isUsingExceptions());
$arch = RarArchive::open("does_not_exist.rar");
var_dump($arch); //not reached
?>

The above example will output something similar to:

bool(false)

Warning: RarArchive::open(): Failed to open does_not_exist.rar: ERAR_EOPEN (file open error) in C:\php_rar\trunk\tests\test.php on line 3
bool(false)
bool(true)

Fatal error: Uncaught exception 'RarException' with message 'unRAR internal error: Failed to open does_not_exist.rar: ERAR_EOPEN (file open error)' in C:\php_rar\trunk\tests\test.php:8
Stack trace:
#0 C:\php_rar\trunk\tests\test.php(8): RarArchive::open('does_not_exist....')
#1 {main}
  thrown in C:\php_rar\trunk\tests\test.php on line 8

See Also

  • RarException::isUsingExceptions - Check whether error handling with exceptions is in use.

RarException::isUsingExceptions
Zip
RarException


Predefined Constants

This extension has no constants defined.

Resource Types
Readline Functions
Readline


Installation

To use these functions you must compile the CGI or CLI version of PHP with readline support. You need to configure PHP --with-readline[=DIR]. In order you want to use the libedit readline replacement, configure PHP --with-libedit[=DIR].

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To use the readline functions, you need to install libreadline. You can find libreadline on the home page of the GNU Readline project, at » http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. It's maintained by Chet Ramey, who's also the author of Bash.

You can also use these functions with the libedit library, a non-GPL replacement for the readline library. The libedit library is BSD licensed and available for download from » http://www.thrysoee.dk/editline/.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Readline


Predefined Constants

This extension has no constants defined.

Resource Types
Recode Functions
Recode


Installation

To be able to use the functions defined in this module you must compile your PHP interpreter using the --with-recode[=DIR] option.

Warning

Crashes and startup problems of PHP may be encountered when loading the recode as extension after loading any extension of mysql or imap. Loading the recode before those extension has proved to fix the problem. This is due a technical problem that both the c-client library used by imap and recode have their own hash_lookup() function and both mysql and recode have their own hash_insert function.

Warning

The IMAP, recode, YAZ and Cyrus extensions cannot be used in conjuction, because they share the same internal symbols. Note: Yaz 2.0 and above does not suffer from this problem.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You must have GNU Recode 3.5 or higher installed on your system. You can download the package from » http://directory.fsf.org/All_GNU_Packages/recode.html.

Warning

The Recode library version 3.6 adds weird characters behind converted strings under certain circumstances. Thus it's safer to use Recode v3.5 or one of the available alternatives like the iconv or mbstring extension.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Recode


APC Functions

Table of Contents

  • apc_add — Cache a variable in the data store
  • apc_cache_info — Retrieves cached information from APC's data store
  • apc_clear_cache — Clears the APC cache
  • apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.
  • apc_define_constants — Defines a set of constants for retrieval and mass-definition
  • apc_delete — Removes a stored variable from the cache
  • apc_fetch — Fetch a stored variable from the cache
  • apc_load_constants — Loads a set of constants from the cache
  • apc_sma_info — Retrieves APC's Shared Memory Allocation information
  • apc_store — Cache a variable in the data store
Predefined Constants
apc_add
APC


APD Functions

Contact information

If you have comments, bugfixes, enhancements or want to help developing this beast, you can send an mail to » apd@mail.communityconnect.com. Any help is very welcome.

Table of Contents

  • apd_breakpoint — Stops the interpreter and waits on a CR from the socket
  • apd_callstack — Returns the current call stack as an array
  • apd_clunk — Throw a warning and a callstack
  • apd_continue — Restarts the interpreter
  • apd_croak — Throw an error, a callstack and then exit
  • apd_dump_function_table — Outputs the current function table
  • apd_dump_persistent_resources — Return all persistent resources as an array
  • apd_dump_regular_resources — Return all current regular resources as an array
  • apd_echo — Echo to the debugging socket
  • apd_get_active_symbols — Get an array of the current variables names in the local scope
  • apd_set_pprof_trace — Starts the session debugging
  • apd_set_session_trace_socket — Starts the remote session debugging
  • apd_set_session_trace — Starts the session debugging
  • apd_set_session — Changes or sets the current debugging level
  • override_function — Overrides built-in functions
  • rename_function — Renames orig_name to new_name in the global function table
How to use PHP-APD in your scripts
apd_breakpoint
APD


BC Math Functions

Table of Contents

  • bcadd — Add two arbitrary precision numbers
  • bccomp — Compare two arbitrary precision numbers
  • bcdiv — Divide two arbitrary precision numbers
  • bcmod — Get modulus of an arbitrary precision number
  • bcmul — Multiply two arbitrary precision number
  • bcpow — Raise an arbitrary precision number to another
  • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
  • bcscale — Set default scale parameter for all bc math functions
  • bcsqrt — Get the square root of an arbitrary precision number
  • bcsub — Subtract one arbitrary precision number from another
Predefined Constants
bcadd
BC Math


bcompiler Functions

Contact Information

If you have comments, bugfixes, enhancements or want to help developing this beast, you can drop me a mail at » alan_k@php.net. Any help is very welcome.

Table of Contents

  • bcompiler_load_exe — Reads and creates classes from a bcompiler exe file
  • bcompiler_load — Reads and creates classes from a bz compressed file
  • bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function
  • bcompiler_read — Reads and creates classes from a filehandle
  • bcompiler_write_class — Writes an defined class as bytecodes
  • bcompiler_write_constant — Writes a defined constant as bytecodes
  • bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file
  • bcompiler_write_file — Writes a php source file as bytecodes
  • bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data
  • bcompiler_write_function — Writes an defined function as bytecodes
  • bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
  • bcompiler_write_header — Writes the bcompiler header
  • bcompiler_write_included_filename — Writes an included file as bytecodes
Predefined Constants
bcompiler_load_exe
bcompiler


Bzip2 Functions

Table of Contents

  • bzclose — Close a bzip2 file
  • bzcompress — Compress a string into bzip2 encoded data
  • bzdecompress — Decompresses bzip2 encoded data
  • bzerrno — Returns a bzip2 error number
  • bzerror — Returns the bzip2 error number and error string in an array
  • bzerrstr — Returns a bzip2 error string
  • bzflush — Force a write of all buffered data
  • bzopen — Opens a bzip2 compressed file
  • bzread — Binary safe bzip2 file read
  • bzwrite — Binary safe bzip2 file write
Examples
bzclose
Bzip2


Cairo Functions

Table of Contents

  • cairo_create — Description
  • cairo_font_face_get_type — Description
  • cairo_font_face_status — Description
  • cairo_font_options_create — Description
  • cairo_font_options_equal — Description
  • cairo_font_options_get_antialias — Description
  • cairo_font_options_get_hint_metrics — Description
  • cairo_font_options_get_hint_style — Description
  • cairo_font_options_get_subpixel_order — Description
  • cairo_font_options_hash — Description
  • cairo_font_options_merge — Description
  • cairo_font_options_set_antialias — Description
  • cairo_font_options_set_hint_metrics — Description
  • cairo_font_options_set_hint_style — Description
  • cairo_font_options_set_subpixel_order — Description
  • cairo_font_options_status — Description
  • cairo_format_stride_for_width — Description
  • cairo_image_surface_create_for_data — Description
  • cairo_image_surface_create_from_png — Description
  • cairo_image_surface_create — Description
  • cairo_image_surface_get_data — Description
  • cairo_image_surface_get_format — Description
  • cairo_image_surface_get_height — Description
  • cairo_image_surface_get_stride — Description
  • cairo_image_surface_get_width — Description
  • cairo_matrix_create_scale — Alias of CairoMatrix::initScale
  • cairo_matrix_create_translate — Alias of CairoMatrix::initTranslate
  • cairo_matrix_invert — Description
  • cairo_matrix_multiply — Description
  • cairo_matrix_rotate — Description
  • cairo_matrix_transform_distance — Description
  • cairo_matrix_transform_point — Description
  • cairo_matrix_translate — Description
  • cairo_pattern_add_color_stop_rgb — Description
  • cairo_pattern_add_color_stop_rgba — Description
  • cairo_pattern_create_for_surface — Description
  • cairo_pattern_create_linear — Description
  • cairo_pattern_create_radial — Description
  • cairo_pattern_create_rgb — Description
  • cairo_pattern_create_rgba — Description
  • cairo_pattern_get_color_stop_count — Description
  • cairo_pattern_get_color_stop_rgba — Description
  • cairo_pattern_get_extend — Description
  • cairo_pattern_get_filter — Description
  • cairo_pattern_get_linear_points — Description
  • cairo_pattern_get_matrix — Description
  • cairo_pattern_get_radial_circles — Description
  • cairo_pattern_get_rgba — Description
  • cairo_pattern_get_surface — Description
  • cairo_pattern_get_type — Description
  • cairo_pattern_set_extend — Description
  • cairo_pattern_set_filter — Description
  • cairo_pattern_set_matrix — Description
  • cairo_pattern_status — Description
  • cairo_pdf_surface_create — Description
  • cairo_pdf_surface_set_size — Description
  • cairo_ps_get_levels — Description
  • cairo_ps_level_to_string — Description
  • cairo_ps_surface_create — Description
  • cairo_ps_surface_dsc_begin_page_setup — Description
  • cairo_ps_surface_dsc_begin_setup — Description
  • cairo_ps_surface_dsc_comment — Description
  • cairo_ps_surface_get_eps — Description
  • cairo_ps_surface_restrict_to_level — Description
  • cairo_ps_surface_set_eps — Description
  • cairo_ps_surface_set_size — Description
  • cairo_scaled_font_create — Description
  • cairo_scaled_font_extents — Description
  • cairo_scaled_font_get_ctm — Description
  • cairo_scaled_font_get_font_face — Description
  • cairo_scaled_font_get_font_matrix — Description
  • cairo_scaled_font_get_font_options — Description
  • cairo_scaled_font_get_scale_matrix — Description
  • cairo_scaled_font_get_type — Description
  • cairo_scaled_font_glyph_extents — Description
  • cairo_scaled_font_status — Description
  • cairo_scaled_font_text_extents — Description
  • cairo_surface_copy_page — Description
  • cairo_surface_create_similar — Description
  • cairo_surface_finish — Description
  • cairo_surface_flush — Description
  • cairo_surface_get_content — Description
  • cairo_surface_get_device_offset — Description
  • cairo_surface_get_font_options — Description
  • cairo_surface_get_type — Description
  • cairo_surface_mark_dirty_rectangle — Description
  • cairo_surface_mark_dirty — Description
  • cairo_surface_set_device_offset — Description
  • cairo_surface_set_fallback_resolution — Description
  • cairo_surface_show_page — Description
  • cairo_surface_status — Description
  • cairo_surface_write_to_png — Description
  • cairo_svg_surface_create — Description
  • cairo_svg_surface_restrict_to_version — Description
  • cairo_svg_version_to_string — Description
Examples
cairo_create
Cairo


Calendar Functions

Table of Contents

  • cal_days_in_month — Return the number of days in a month for a given year and calendar
  • cal_from_jd — Converts from Julian Day Count to a supported calendar
  • cal_info — Returns information about a particular calendar
  • cal_to_jd — Converts from a supported calendar to Julian Day Count
  • easter_date — Get Unix timestamp for midnight on Easter of a given year
  • easter_days — Get number of days after March 21 on which Easter falls for a given year
  • FrenchToJD — Converts a date from the French Republican Calendar to a Julian Day Count
  • GregorianToJD — Converts a Gregorian date to Julian Day Count
  • JDDayOfWeek — Returns the day of the week
  • JDMonthName — Returns a month name
  • JDToFrench — Converts a Julian Day Count to the French Republican Calendar
  • JDToGregorian — Converts Julian Day Count to Gregorian date
  • jdtojewish — Converts a Julian day count to a Jewish calendar date
  • JDToJulian — Converts a Julian Day Count to a Julian Calendar Date
  • jdtounix — Convert Julian Day to Unix timestamp
  • JewishToJD — Converts a date in the Jewish Calendar to Julian Day Count
  • JulianToJD — Converts a Julian Calendar date to Julian Day Count
  • unixtojd — Convert Unix timestamp to Julian Day
Predefined Constants
cal_days_in_month
Calendar


Crack Functions

Table of Contents

  • crack_check — Performs an obscure check with the given password
  • crack_closedict — Closes an open CrackLib dictionary
  • crack_getlastmessage — Returns the message from the last obscure check
  • crack_opendict — Opens a new CrackLib dictionary
Examples
crack_check
Crack


Cyrus Functions

Table of Contents

  • cyrus_authenticate — Authenticate against a Cyrus IMAP server
  • cyrus_bind — Bind callbacks to a Cyrus IMAP connection
  • cyrus_close — Close connection to a Cyrus IMAP server
  • cyrus_connect — Connect to a Cyrus IMAP server
  • cyrus_query — Send a query to a Cyrus IMAP server
  • cyrus_unbind — Unbind ...
Predefined Constants
cyrus_authenticate
Cyrus


Date/Time Functions

Table of Contents

  • checkdate — Validate a Gregorian date
  • date_add — Alias of DateTime::add
  • date_create_from_format — Alias of DateTime::createFromFormat
  • date_create — Returns new DateTime object
  • date_date_set — Alias of DateTime::setDate
  • date_default_timezone_get — Gets the default timezone used by all date/time functions in a script
  • date_default_timezone_set — Sets the default timezone used by all date/time functions in a script
  • date_diff — Alias of DateTime::diff
  • date_format — Alias of DateTime::format
  • date_get_last_errors — Alias of DateTime::getLastErrors
  • date_interval_create_from_date_string — Alias of DateInterval::createFromDateString
  • date_interval_format — Alias of DateInterval::format
  • date_isodate_set — Alias of DateTime::setISODate
  • date_modify — Alias of DateTime::modify
  • date_offset_get — Alias of DateTime::getOffset
  • date_parse_from_format — Get info about given date
  • date_parse — Returns associative array with detailed info about given date
  • date_sub — Alias of DateTime::sub
  • date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
  • date_sunrise — Returns time of sunrise for a given day and location
  • date_sunset — Returns time of sunset for a given day and location
  • date_time_set — Alias of DateTime::setTime
  • date_timestamp_get — Alias of DateTime::getTimestamp
  • date_timestamp_set — Alias of DateTime::setTimestamp
  • date_timezone_get — Alias of DateTime::getTimezone
  • date_timezone_set — Alias of DateTime::setTimezone
  • date — Format a local time/date
  • getdate — Get date/time information
  • gettimeofday — Get current time
  • gmdate — Format a GMT/UTC date/time
  • gmmktime — Get Unix timestamp for a GMT date
  • gmstrftime — Format a GMT/UTC time/date according to locale settings
  • idate — Format a local time/date as integer
  • localtime — Get the local time
  • microtime — Return current Unix timestamp with microseconds
  • mktime — Get Unix timestamp for a date
  • strftime — Format a local time/date according to locale settings
  • strptime — Parse a time/date generated with strftime
  • strtotime — Parse about any English textual datetime description into a Unix timestamp
  • time — Return current Unix timestamp
  • timezone_abbreviations_list — Alias of DateTimeZone::listAbbreviations
  • timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers
  • timezone_location_get — Alias of DateTimeZone::getLocation
  • timezone_name_from_abbr — Returns the timezone name from abbreviation
  • timezone_name_get — Alias of DateTimeZone::getName
  • timezone_offset_get — Alias of DateTimeZone::getOffset
  • timezone_open — Returns new DateTimeZone object
  • timezone_transitions_get — Alias of DateTimeZone::getTransitions
  • timezone_version_get — Gets the version of the timezonedb
DatePeriod::__construct
checkdate
Date/Time


DBA Functions

Table of Contents

  • dba_close — Close a DBA database
  • dba_delete — Delete DBA entry specified by key
  • dba_exists — Check whether key exists
  • dba_fetch — Fetch data specified by key
  • dba_firstkey — Fetch first key
  • dba_handlers — List all the handlers available
  • dba_insert — Insert entry
  • dba_key_split — Splits a key in string representation into array representation
  • dba_list — List all open database files
  • dba_nextkey — Fetch next key
  • dba_open — Open database
  • dba_optimize — Optimize database
  • dba_popen — Open database persistently
  • dba_replace — Replace or insert entry
  • dba_sync — Synchronize database
Basic usage
dba_close
DBA


dBase Functions

Examples

Many examples in this reference require a dBase database. We will use /tmp/test.dbf that will be created in the example of dbase_create().

Table of Contents

  • dbase_add_record — Adds a record to a database
  • dbase_close — Closes a database
  • dbase_create — Creates a database
  • dbase_delete_record — Deletes a record from a database
  • dbase_get_header_info — Gets the header info of a database
  • dbase_get_record_with_names — Gets a record from a database as an associative array
  • dbase_get_record — Gets a record from a database as an indexed array
  • dbase_numfields — Gets the number of fields of a database
  • dbase_numrecords — Gets the number of records in a database
  • dbase_open — Opens a database
  • dbase_pack — Packs a database
  • dbase_replace_record — Replaces a record in a database
Predefined Constants
dbase_add_record
dBase


DB++ Functions

Table of Contents

  • dbplus_add — Add a tuple to a relation
  • dbplus_aql — Perform AQL query
  • dbplus_chdir — Get/Set database virtual current directory
  • dbplus_close — Close a relation
  • dbplus_curr — Get current tuple from relation
  • dbplus_errcode — Get error string for given errorcode or last error
  • dbplus_errno — Get error code for last operation
  • dbplus_find — Set a constraint on a relation
  • dbplus_first — Get first tuple from relation
  • dbplus_flush — Flush all changes made on a relation
  • dbplus_freealllocks — Free all locks held by this client
  • dbplus_freelock — Release write lock on tuple
  • dbplus_freerlocks — Free all tuple locks on given relation
  • dbplus_getlock — Get a write lock on a tuple
  • dbplus_getunique — Get an id number unique to a relation
  • dbplus_info — Get information about a relation
  • dbplus_last — Get last tuple from relation
  • dbplus_lockrel — Request write lock on relation
  • dbplus_next — Get next tuple from relation
  • dbplus_open — Open relation file
  • dbplus_prev — Get previous tuple from relation
  • dbplus_rchperm — Change relation permissions
  • dbplus_rcreate — Creates a new DB++ relation
  • dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices
  • dbplus_rcrtlike — Creates an empty copy of a relation with default indices
  • dbplus_resolve — Resolve host information for relation
  • dbplus_restorepos — Restore position
  • dbplus_rkeys — Specify new primary key for a relation
  • dbplus_ropen — Open relation file local
  • dbplus_rquery — Perform local (raw) AQL query
  • dbplus_rrename — Rename a relation
  • dbplus_rsecindex — Create a new secondary index for a relation
  • dbplus_runlink — Remove relation from filesystem
  • dbplus_rzap — Remove all tuples from relation
  • dbplus_savepos — Save position
  • dbplus_setindex — Set index
  • dbplus_setindexbynumber — Set index by number
  • dbplus_sql — Perform SQL query
  • dbplus_tcl — Execute TCL code on server side
  • dbplus_tremove — Remove tuple and return new current tuple
  • dbplus_undo — Undo
  • dbplus_undoprepare — Prepare undo
  • dbplus_unlockrel — Give up write lock on relation
  • dbplus_unselect — Remove a constraint from relation
  • dbplus_update — Update specified tuple in relation
  • dbplus_xlockrel — Request exclusive lock on relation
  • dbplus_xunlockrel — Free exclusive lock on relation
db++ error codes
dbplus_add
DB++


dbx Functions

Table of Contents

  • dbx_close — Close an open connection/database
  • dbx_compare — Compare two rows for sorting purposes
  • dbx_connect — Open a connection/database
  • dbx_error — Report the error message of the latest function call in the module
  • dbx_escape_string — Escape a string so it can safely be used in an sql-statement
  • dbx_fetch_row — Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
  • dbx_query — Send a query and fetch all results (if any)
  • dbx_sort — Sort a result from a dbx_query by a custom sort function
Predefined Constants
dbx_close
dbx


Direct IO Functions

Table of Contents

  • dio_close — Closes the file descriptor given by fd
  • dio_fcntl — Performs a c library fcntl on fd
  • dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.
  • dio_read — Reads bytes from a file descriptor
  • dio_seek — Seeks to pos on fd from whence
  • dio_stat — Gets stat information about the file descriptor fd
  • dio_tcsetattr — Sets terminal attributes and baud rate for a serial port
  • dio_truncate — Truncates file descriptor fd to offset bytes
  • dio_write — Writes data to fd with optional truncation at length
Predefined Constants
dio_close
Direct IO


Directory Functions

See Also

For related functions such as dirname(),
is_dir(), mkdir(), and
rmdir(), see the
Filesystem section.

Table of Contents

  • chdir — Change directory
  • chroot — Change the root directory
  • dir — Return an instance of the Directory class
  • closedir — Close directory handle
  • getcwd — Gets the current working directory
  • opendir — Open directory handle
  • readdir — Read entry from directory handle
  • rewinddir — Rewind directory handle
  • scandir — List files and directories inside the specified path
Predefined Constants
chdir
Directories


Enchant Functions

Table of Contents

  • enchant_broker_describe — Enumerates the Enchant providers
  • enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict — Free a dictionary resource
  • enchant_broker_free — Free the broker resource and its dictionnaries
  • enchant_broker_get_error — Returns the last error of the broker
  • enchant_broker_init — create a new broker object capable of requesting
  • enchant_broker_list_dicts — Returns a list of available dictionaries
  • enchant_broker_request_dict — create a new dictionary using a tag
  • enchant_broker_request_pwl_dict — creates a dictionary using a PWL file
  • enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language
  • enchant_dict_add_to_personal — add a word to personal word list
  • enchant_dict_add_to_session — add 'word' to this spell-checking session
  • enchant_dict_check — Check whether a word is correctly spelled or not
  • enchant_dict_describe — Describes an individual dictionary
  • enchant_dict_get_error — Returns the last error of the current spelling-session
  • enchant_dict_is_in_session — whether or not 'word' exists in this spelling-session
  • enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions
  • enchant_dict_store_replacement — Add a correction for a word
  • enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met
Examples
enchant_broker_describe
Enchant


Error Handling Functions

See Also

See also syslog().

Table of Contents

  • debug_backtrace — Generates a backtrace
  • debug_print_backtrace — Prints a backtrace
  • error_get_last — Get the last occurred error
  • error_log — Send an error message somewhere
  • error_reporting — Sets which PHP errors are reported
  • restore_error_handler — Restores the previous error handler function
  • restore_exception_handler — Restores the previously defined exception handler function
  • set_error_handler — Sets a user-defined error handler function
  • set_exception_handler — Sets a user-defined exception handler function
  • trigger_error — Generates a user-level error/warning/notice message
  • user_error — Alias of trigger_error
Examples
debug_backtrace
Error Handling


Program execution Functions

Notes

Warning

Open files with lock (especially open sessions) should be closed before executing a program in the background.

See Also

These functions are also closely related to the backtick operator. Also, while in safe mode you must consider the safe_mode_exec_dir directive.

Table of Contents

  • escapeshellarg — Escape a string to be used as a shell argument
  • escapeshellcmd — Escape shell metacharacters
  • exec — Execute an external program
  • passthru — Execute an external program and display raw output
  • proc_close — Close a process opened by proc_open and return the exit code of that process
  • proc_get_status — Get information about a process opened by proc_open
  • proc_nice — Change the priority of the current process
  • proc_open — Execute a command and open file pointers for input/output
  • proc_terminate — Kills a process opened by proc_open
  • shell_exec — Execute command via shell and return the complete output as a string
  • system — Execute an external program and display the output
Predefined Constants
escapeshellarg
Program execution


Exif Functions

Table of Contents

  • exif_imagetype — Determine the type of an image
  • exif_read_data — Reads the EXIF headers from JPEG or TIFF
  • exif_tagname — Get the header name for an index
  • exif_thumbnail — Retrieve the embedded thumbnail of a TIFF or JPEG image
  • read_exif_data — Alias of exif_read_data
Predefined Constants
exif_imagetype
Exif


Expect Functions

Table of Contents

  • expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
  • expect_popen — Execute command via Bourne shell, and open the PTY stream to the process
Expect Usage Examples
expect_expectl
Expect


FrontBase Functions

Table of Contents

  • fbsql_affected_rows — Get number of affected rows in previous FrontBase operation
  • fbsql_autocommit — Enable or disable autocommit
  • fbsql_blob_size — Get the size of a BLOB
  • fbsql_change_user — Change logged in user of the active connection
  • fbsql_clob_size — Get the size of a CLOB
  • fbsql_close — Close FrontBase connection
  • fbsql_commit — Commits a transaction to the database
  • fbsql_connect — Open a connection to a FrontBase Server
  • fbsql_create_blob — Create a BLOB
  • fbsql_create_clob — Create a CLOB
  • fbsql_create_db — Create a FrontBase database
  • fbsql_data_seek — Move internal result pointer
  • fbsql_database_password — Sets or retrieves the password for a FrontBase database
  • fbsql_database — Get or set the database name used with a connection
  • fbsql_db_query — Send a FrontBase query
  • fbsql_db_status — Get the status for a given database
  • fbsql_drop_db — Drop (delete) a FrontBase database
  • fbsql_errno — Returns the error number from previous operation
  • fbsql_error — Returns the error message from previous operation
  • fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_assoc — Fetch a result row as an associative array
  • fbsql_fetch_field — Get column information from a result and return as an object
  • fbsql_fetch_lengths — Get the length of each output in a result
  • fbsql_fetch_object — Fetch a result row as an object
  • fbsql_fetch_row — Get a result row as an enumerated array
  • fbsql_field_flags — Get the flags associated with the specified field in a result
  • fbsql_field_len — Returns the length of the specified field
  • fbsql_field_name — Get the name of the specified field in a result
  • fbsql_field_seek — Set result pointer to a specified field offset
  • fbsql_field_table — Get name of the table the specified field is in
  • fbsql_field_type — Get the type of the specified field in a result
  • fbsql_free_result — Free result memory
  • fbsql_get_autostart_info — Description
  • fbsql_hostname — Get or set the host name used with a connection
  • fbsql_insert_id — Get the id generated from the previous INSERT operation
  • fbsql_list_dbs — List databases available on a FrontBase server
  • fbsql_list_fields — List FrontBase result fields
  • fbsql_list_tables — List tables in a FrontBase database
  • fbsql_next_result — Move the internal result pointer to the next result
  • fbsql_num_fields — Get number of fields in result
  • fbsql_num_rows — Get number of rows in result
  • fbsql_password — Get or set the user password used with a connection
  • fbsql_pconnect — Open a persistent connection to a FrontBase Server
  • fbsql_query — Send a FrontBase query
  • fbsql_read_blob — Read a BLOB from the database
  • fbsql_read_clob — Read a CLOB from the database
  • fbsql_result — Get result data
  • fbsql_rollback — Rollback a transaction to the database
  • fbsql_rows_fetched — Get the number of rows affected by the last statement
  • fbsql_select_db — Select a FrontBase database
  • fbsql_set_characterset — Change input/output character set
  • fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set
  • fbsql_set_password — Change the password for a given user
  • fbsql_set_transaction — Set the transaction locking and isolation
  • fbsql_start_db — Start a database on local or remote server
  • fbsql_stop_db — Stop a database on local or remote server
  • fbsql_table_name — Get table name of field
  • fbsql_tablename — Alias of of fbsql_table_name
  • fbsql_username — Get or set the username for the connection
  • fbsql_warnings — Enable or disable FrontBase warnings
Predefined Constants
fbsql_affected_rows
FrontBase


FDF Functions

Table of Contents

  • fdf_add_doc_javascript — Adds javascript code to the FDF document
  • fdf_add_template — Adds a template into the FDF document
  • fdf_close — Close an FDF document
  • fdf_create — Create a new FDF document
  • fdf_enum_values — Call a user defined function for each document value
  • fdf_errno — Return error code for last fdf operation
  • fdf_error — Return error description for FDF error code
  • fdf_get_ap — Get the appearance of a field
  • fdf_get_attachment — Extracts uploaded file embedded in the FDF
  • fdf_get_encoding — Get the value of the /Encoding key
  • fdf_get_file — Get the value of the /F key
  • fdf_get_flags — Gets the flags of a field
  • fdf_get_opt — Gets a value from the opt array of a field
  • fdf_get_status — Get the value of the /STATUS key
  • fdf_get_value — Get the value of a field
  • fdf_get_version — Gets version number for FDF API or file
  • fdf_header — Sets FDF-specific output headers
  • fdf_next_field_name — Get the next field name
  • fdf_open_string — Read a FDF document from a string
  • fdf_open — Open a FDF document
  • fdf_remove_item — Sets target frame for form
  • fdf_save_string — Returns the FDF document as a string
  • fdf_save — Save a FDF document
  • fdf_set_ap — Set the appearance of a field
  • fdf_set_encoding — Sets FDF character encoding
  • fdf_set_file — Set PDF document to display FDF data in
  • fdf_set_flags — Sets a flag of a field
  • fdf_set_javascript_action — Sets an javascript action of a field
  • fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF
  • fdf_set_opt — Sets an option of a field
  • fdf_set_status — Set the value of the /STATUS key
  • fdf_set_submit_form_action — Sets a submit form action of a field
  • fdf_set_target_frame — Set target frame for form display
  • fdf_set_value — Set the value of a field
  • fdf_set_version — Sets version number for a FDF file
Examples
fdf_add_doc_javascript
FDF


Fileinfo Functions

Table of Contents

  • finfo_buffer — Return information about a string buffer
  • finfo_close — Close fileinfo resource
  • finfo_file — Return information about a file
  • finfo_open — Create a new fileinfo resource
  • finfo_set_flags — Set libmagic configuration options
  • mime_content_type — Detect MIME Content-type for a file (deprecated)
Predefined Constants
finfo_buffer
Fileinfo


filePro Functions

Table of Contents

  • filepro_fieldcount — Find out how many fields are in a filePro database
  • filepro_fieldname — Gets the name of a field
  • filepro_fieldtype — Gets the type of a field
  • filepro_fieldwidth — Gets the width of a field
  • filepro_retrieve — Retrieves data from a filePro database
  • filepro_rowcount — Find out how many rows are in a filePro database
  • filepro — Read and verify the map file
Predefined Constants
filepro_fieldcount
filePro


Filesystem Functions

See Also

For related functions, see also the Directory and Program Execution sections.

For a list and explanation of the various URL wrappers that can be used as remote files, see also List of Supported Protocols/Wrappers.

Table of Contents

  • basename — Returns filename component of path
  • chgrp — Changes file group
  • chmod — Changes file mode
  • chown — Changes file owner
  • clearstatcache — Clears file status cache
  • copy — Copies file
  • delete — See unlink or unset
  • dirname — Returns directory name component of path
  • disk_free_space — Returns available space in directory
  • disk_total_space — Returns the total size of a directory
  • diskfreespace — Alias of disk_free_space
  • fclose — Closes an open file pointer
  • feof — Tests for end-of-file on a file pointer
  • fflush — Flushes the output to a file
  • fgetc — Gets character from file pointer
  • fgetcsv — Gets line from file pointer and parse for CSV fields
  • fgets — Gets line from file pointer
  • fgetss — Gets line from file pointer and strip HTML tags
  • file_exists — Checks whether a file or directory exists
  • file_get_contents — Reads entire file into a string
  • file_put_contents — Write a string to a file
  • file — Reads entire file into an array
  • fileatime — Gets last access time of file
  • filectime — Gets inode change time of file
  • filegroup — Gets file group
  • fileinode — Gets file inode
  • filemtime — Gets file modification time
  • fileowner — Gets file owner
  • fileperms — Gets file permissions
  • filesize — Gets file size
  • filetype — Gets file type
  • flock — Portable advisory file locking
  • fnmatch — Match filename against a pattern
  • fopen — Opens file or URL
  • fpassthru — Output all remaining data on a file pointer
  • fputcsv — Format line as CSV and write to file pointer
  • fputs — Alias of fwrite
  • fread — Binary-safe file read
  • fscanf — Parses input from a file according to a format
  • fseek — Seeks on a file pointer
  • fstat — Gets information about a file using an open file pointer
  • ftell — Returns the current position of the file read/write pointer
  • ftruncate — Truncates a file to a given length
  • fwrite — Binary-safe file write
  • glob — Find pathnames matching a pattern
  • is_dir — Tells whether the filename is a directory
  • is_executable — Tells whether the filename is executable
  • is_file — Tells whether the filename is a regular file
  • is_link — Tells whether the filename is a symbolic link
  • is_readable — Tells whether a file exists and is readable
  • is_uploaded_file — Tells whether the file was uploaded via HTTP POST
  • is_writable — Tells whether the filename is writable
  • is_writeable — Alias of is_writable
  • lchgrp — Changes group ownership of symlink
  • lchown — Changes user ownership of symlink
  • link — Create a hard link
  • linkinfo — Gets information about a link
  • lstat — Gives information about a file or symbolic link
  • mkdir — Makes directory
  • move_uploaded_file — Moves an uploaded file to a new location
  • parse_ini_file — Parse a configuration file
  • parse_ini_string — Parse a configuration string
  • pathinfo — Returns information about a file path
  • pclose — Closes process file pointer
  • popen — Opens process file pointer
  • readfile — Outputs a file
  • readlink — Returns the target of a symbolic link
  • realpath_cache_get — Get realpath cache entries
  • realpath_cache_size — Get realpath cache size
  • realpath — Returns canonicalized absolute pathname
  • rename — Renames a file or directory
  • rewind — Rewind the position of a file pointer
  • rmdir — Removes directory
  • set_file_buffer — Alias of stream_set_write_buffer
  • stat — Gives information about a file
  • symlink — Creates a symbolic link
  • tempnam — Create file with unique file name
  • tmpfile — Creates a temporary file
  • touch — Sets access and modification time of file
  • umask — Changes the current umask
  • unlink — Deletes a file
Predefined Constants
basename
Filesystem


FriBiDi Functions

Table of Contents

  • fribidi_log2vis — Convert a logical string to a visual one
Predefined Constants
fribidi_log2vis
FriBiDi


GeoIP Functions

Table of Contents

  • geoip_continent_code_by_name — Get the two letter continent code
  • geoip_country_code_by_name — Get the two letter country code
  • geoip_country_code3_by_name — Get the three letter country code
  • geoip_country_name_by_name — Get the full country name
  • geoip_database_info — Get GeoIP Database information
  • geoip_db_avail — Determine if GeoIP Database is available
  • geoip_db_filename — Returns the filename of the corresponding GeoIP Database
  • geoip_db_get_all_info — Returns detailed information about all GeoIP database types
  • geoip_id_by_name — Get the Internet connection speed
  • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
  • geoip_org_by_name — Get the organization name
  • geoip_record_by_name — Returns the detailed City information found in the GeoIP Database
  • geoip_region_by_name — Get the country code and region
  • geoip_region_name_by_code — Returns the region name for some country and region code combo
  • geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo
Predefined Constants
geoip_continent_code_by_name
GeoIP


Gettext Functions

Table of Contents

  • bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
  • bindtextdomain — Sets the path for a domain
  • dcgettext — Overrides the domain for a single lookup
  • dcngettext — Plural version of dcgettext
  • dgettext — Override the current domain
  • dngettext — Plural version of dgettext
  • gettext — Lookup a message in the current domain
  • ngettext — Plural version of gettext
  • textdomain — Sets the default domain
Predefined Constants
bind_textdomain_codeset
Gettext


GMP Functions

See Also

More mathematical functions can be found in the Mathematical Extensions section

Table of Contents

  • gmp_abs — Absolute value
  • gmp_add — Add numbers
  • gmp_and — Bitwise AND
  • gmp_clrbit — Clear bit
  • gmp_cmp — Compare numbers
  • gmp_com — Calculates one's complement
  • gmp_div_q — Divide numbers
  • gmp_div_qr — Divide numbers and get quotient and remainder
  • gmp_div_r — Remainder of the division of numbers
  • gmp_div — Alias of gmp_div_q
  • gmp_divexact — Exact division of numbers
  • gmp_fact — Factorial
  • gmp_gcd — Calculate GCD
  • gmp_gcdext — Calculate GCD and multipliers
  • gmp_hamdist — Hamming distance
  • gmp_init — Create GMP number
  • gmp_intval — Convert GMP number to integer
  • gmp_invert — Inverse by modulo
  • gmp_jacobi — Jacobi symbol
  • gmp_legendre — Legendre symbol
  • gmp_mod — Modulo operation
  • gmp_mul — Multiply numbers
  • gmp_neg — Negate number
  • gmp_nextprime — Find next prime number
  • gmp_or — Bitwise OR
  • gmp_perfect_square — Perfect square check
  • gmp_popcount — Population count
  • gmp_pow — Raise number into power
  • gmp_powm — Raise number into power with modulo
  • gmp_prob_prime — Check if number is "probably prime"
  • gmp_random — Random number
  • gmp_scan0 — Scan for 0
  • gmp_scan1 — Scan for 1
  • gmp_setbit — Set bit
  • gmp_sign — Sign of number
  • gmp_sqrt — Calculate square root
  • gmp_sqrtrem — Square root with remainder
  • gmp_strval — Convert GMP number to string
  • gmp_sub — Subtract numbers
  • gmp_testbit — Tests if a bit is set
  • gmp_xor — Bitwise XOR
Examples
gmp_abs
GMP


GnuPG Functions

Notes

This extension makes use of the keyring of the current user. This keyring is normally located in ~./.gnupg/. To specify a custom location, store the path to the keyring in the environment variable GNUPGHOME. See putenv for more information how to do this.

Some functions require the specification of a key. This specification can be anything that refers to a unique key (userid, key-id, fingerprint, ...). This documentation uses the fingerprint in all examples.

Table of Contents

  • gnupg_adddecryptkey — Add a key for decryption
  • gnupg_addencryptkey — Add a key for encryption
  • gnupg_addsignkey — Add a key for signing
  • gnupg_cleardecryptkeys — Removes all keys which were set for decryption before
  • gnupg_clearencryptkeys — Removes all keys which were set for encryption before
  • gnupg_clearsignkeys — Removes all keys which were set for signing before
  • gnupg_decrypt — Decrypts a given text
  • gnupg_decryptverify — Decrypts and verifies a given text
  • gnupg_encrypt — Encrypts a given text
  • gnupg_encryptsign — Encrypts and signs a given text
  • gnupg_export — Exports a key
  • gnupg_geterror — Returns the errortext, if a function fails
  • gnupg_getprotocol — Returns the currently active protocol for all operations
  • gnupg_import — Imports a key
  • gnupg_init — Initialize a connection
  • gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern
  • gnupg_setarmor — Toggle armored output
  • gnupg_seterrormode — Sets the mode for error_reporting
  • gnupg_setsignmode — Sets the mode for signing
  • gnupg_sign — Signs a given text
  • gnupg_verify — Verifies a signed text
Clearsign text
gnupg_adddecryptkey
GnuPG


Hash Functions

Table of Contents

  • hash_algos — Return a list of registered hashing algorithms
  • hash_copy — Copy hashing context
  • hash_file — Generate a hash value using the contents of a given file
  • hash_final — Finalize an incremental hash and return resulting digest
  • hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file
  • hash_hmac — Generate a keyed hash value using the HMAC method
  • hash_init — Initialize an incremental hashing context
  • hash_update_file — Pump data into an active hashing context from a file
  • hash_update_stream — Pump data into an active hashing context from an open stream
  • hash_update — Pump data into an active hashing context
  • hash — Generate a hash value (message digest)
Predefined Constants
hash_algos
Hash


i18n Functions

Table of Contents

  • locale_get_default — Get the default Locale
  • locale_set_default — Set the default Locale
Predefined Constants
locale_get_default
i18n


Firebird/InterBase Functions

Table of Contents

  • ibase_add_user — Add a user to a security database (only for IB6 or later)
  • ibase_affected_rows — Return the number of rows that were affected by the previous query
  • ibase_backup — Initiates a backup task in the service manager and returns immediately
  • ibase_blob_add — Add data into a newly created blob
  • ibase_blob_cancel — Cancel creating blob
  • ibase_blob_close — Close blob
  • ibase_blob_create — Create a new blob for adding data
  • ibase_blob_echo — Output blob contents to browser
  • ibase_blob_get — Get len bytes data from open blob
  • ibase_blob_import — Create blob, copy file in it, and close it
  • ibase_blob_info — Return blob length and other useful info
  • ibase_blob_open — Open blob for retrieving data parts
  • ibase_close — Close a connection to an InterBase database
  • ibase_commit_ret — Commit a transaction without closing it
  • ibase_commit — Commit a transaction
  • ibase_connect — Open a connection to an InterBase database
  • ibase_db_info — Request statistics about a database
  • ibase_delete_user — Delete a user from a security database (only for IB6 or later)
  • ibase_drop_db — Drops a database
  • ibase_errcode — Return an error code
  • ibase_errmsg — Return error messages
  • ibase_execute — Execute a previously prepared query
  • ibase_fetch_assoc — Fetch a result row from a query as an associative array
  • ibase_fetch_object — Get an object from a InterBase database
  • ibase_fetch_row — Fetch a row from an InterBase database
  • ibase_field_info — Get information about a field
  • ibase_free_event_handler — Cancels a registered event handler
  • ibase_free_query — Free memory allocated by a prepared query
  • ibase_free_result — Free a result set
  • ibase_gen_id — Increments the named generator and returns its new value
  • ibase_maintain_db — Execute a maintenance command on the database server
  • ibase_modify_user — Modify a user to a security database (only for IB6 or later)
  • ibase_name_result — Assigns a name to a result set
  • ibase_num_fields — Get the number of fields in a result set
  • ibase_num_params — Return the number of parameters in a prepared query
  • ibase_param_info — Return information about a parameter in a prepared query
  • ibase_pconnect — Open a persistent connection to an InterBase database
  • ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
  • ibase_query — Execute a query on an InterBase database
  • ibase_restore — Initiates a restore task in the service manager and returns immediately
  • ibase_rollback_ret — Roll back a transaction without closing it
  • ibase_rollback — Roll back a transaction
  • ibase_server_info — Request information about a database server
  • ibase_service_attach — Connect to the service manager
  • ibase_service_detach — Disconnect from the service manager
  • ibase_set_event_handler — Register a callback function to be called when events are posted
  • ibase_timefmt — Sets the format of timestamp, date and time type columns returned from queries
  • ibase_trans — Begin a transaction
  • ibase_wait_event — Wait for an event to be posted by the database
Predefined Constants
ibase_add_user
Firebird/InterBase


IBM DB2 Functions

Table of Contents

  • db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection
  • db2_bind_param — Binds a PHP variable to an SQL statement parameter
  • db2_client_info — Returns an object with properties that describe the DB2 database client
  • db2_close — Closes a database connection
  • db2_column_privileges — Returns a result set listing the columns and associated privileges for a table
  • db2_columns — Returns a result set listing the columns and associated metadata for a table
  • db2_commit — Commits a transaction
  • db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg — Returns the last connection error message and SQLCODE value
  • db2_connect — Returns a connection to a database
  • db2_cursor_type — Returns the cursor type used by a statement resource
  • db2_escape_string — Used to escape certain characters
  • db2_exec — Executes an SQL statement directly
  • db2_execute — Executes a prepared SQL statement
  • db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object — Returns an object with properties representing columns in the fetched row
  • db2_fetch_row — Sets the result set pointer to the next row or requested row
  • db2_field_display_size — Returns the maximum number of bytes required to display a column
  • db2_field_name — Returns the name of the column in the result set
  • db2_field_num — Returns the position of the named column in a result set
  • db2_field_precision — Returns the precision of the indicated column in a result set
  • db2_field_scale — Returns the scale of the indicated column in a result set
  • db2_field_type — Returns the data type of the indicated column in a result set
  • db2_field_width — Returns the width of the current value of the indicated column in a result set
  • db2_foreign_keys — Returns a result set listing the foreign keys for a table
  • db2_free_result — Frees resources associated with a result set
  • db2_free_stmt — Frees resources associated with the indicated statement resource
  • db2_get_option — Retrieves an option value for a statement resource or a connection resource
  • db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection
  • db2_lob_read — Gets a user defined size of LOB files with each invocation
  • db2_next_result — Requests the next result set from a stored procedure
  • db2_num_fields — Returns the number of fields contained in a result set
  • db2_num_rows — Returns the number of rows affected by an SQL statement
  • db2_pclose — Closes a persistent database connection
  • db2_pconnect — Returns a persistent connection to a database
  • db2_prepare — Prepares an SQL statement to be executed
  • db2_primary_keys — Returns a result set listing primary keys for a table
  • db2_procedure_columns — Returns a result set listing stored procedure parameters
  • db2_procedures — Returns a result set listing the stored procedures registered in a database
  • db2_result — Returns a single column from a row in the result set
  • db2_rollback — Rolls back a transaction
  • db2_server_info — Returns an object with properties that describe the DB2 database server
  • db2_set_option — Set options for connection or statement resources
  • db2_special_columns — Returns a result set listing the unique row identifier columns for a table
  • db2_statistics — Returns a result set listing the index and statistics for a table
  • db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg — Returns a string containing the last SQL statement error message
  • db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
  • db2_tables — Returns a result set listing the tables and associated metadata in a database
Predefined Constants
db2_autocommit
IBM DB2


iconv Functions

See Also

See also GNU Recode functions.

Table of Contents

  • iconv_get_encoding — Retrieve internal configuration variables of iconv extension
  • iconv_mime_decode_headers — Decodes multiple MIME header fields at once
  • iconv_mime_decode — Decodes a MIME header field
  • iconv_mime_encode — Composes a MIME header field
  • iconv_set_encoding — Set current setting for character encoding conversion
  • iconv_strlen — Returns the character count of string
  • iconv_strpos — Finds position of first occurrence of a needle within a haystack
  • iconv_strrpos — Finds the last occurrence of a needle within a haystack
  • iconv_substr — Cut out part of a string
  • iconv — Convert string to requested character encoding
  • ob_iconv_handler — Convert character encoding as output buffer handler
Predefined Constants
iconv_get_encoding
iconv


ID3 Functions

Table of Contents

  • id3_get_frame_long_name — Get the long name of an ID3v2 frame
  • id3_get_frame_short_name — Get the short name of an ID3v2 frame
  • id3_get_genre_id — Get the id for a genre
  • id3_get_genre_list — Get all possible genre values
  • id3_get_genre_name — Get the name for a genre id
  • id3_get_tag — Get all information stored in an ID3 tag
  • id3_get_version — Get version of an ID3 tag
  • id3_remove_tag — Remove an existing ID3 tag
  • id3_set_tag — Update information stored in an ID3 tag
Predefined Constants
id3_get_frame_long_name
ID3


Informix Functions

Table of Contents

  • ifx_affected_rows — Get number of rows affected by a query
  • ifx_blobinfile_mode — Set the default blob mode for all select queries
  • ifx_byteasvarchar — Set the default byte mode
  • ifx_close — Close Informix connection
  • ifx_connect — Open Informix server connection
  • ifx_copy_blob — Duplicates the given blob object
  • ifx_create_blob — Creates an blob object
  • ifx_create_char — Creates an char object
  • ifx_do — Execute a previously prepared SQL-statement
  • ifx_error — Returns error code of last Informix call
  • ifx_errormsg — Returns error message of last Informix call
  • ifx_fetch_row — Get row as an associative array
  • ifx_fieldproperties — List of SQL fieldproperties
  • ifx_fieldtypes — List of Informix SQL fields
  • ifx_free_blob — Deletes the blob object
  • ifx_free_char — Deletes the char object
  • ifx_free_result — Releases resources for the query
  • ifx_get_blob — Return the content of a blob object
  • ifx_get_char — Return the content of the char object
  • ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query
  • ifx_htmltbl_result — Formats all rows of a query into a HTML table
  • ifx_nullformat — Sets the default return value on a fetch row
  • ifx_num_fields — Returns the number of columns in the query
  • ifx_num_rows — Count the rows already fetched from a query
  • ifx_pconnect — Open persistent Informix connection
  • ifx_prepare — Prepare an SQL-statement for execution
  • ifx_query — Send Informix query
  • ifx_textasvarchar — Set the default text mode
  • ifx_update_blob — Updates the content of the blob object
  • ifx_update_char — Updates the content of the char object
  • ifxus_close_slob — Deletes the slob object
  • ifxus_create_slob — Creates an slob object and opens it
  • ifxus_free_slob — Deletes the slob object
  • ifxus_open_slob — Opens an slob object
  • ifxus_read_slob — Reads nbytes of the slob object
  • ifxus_seek_slob — Sets the current file or seek position
  • ifxus_tell_slob — Returns the current file or seek position
  • ifxus_write_slob — Writes a string into the slob object
Predefined Constants
ifx_affected_rows
Informix


GD and Image Functions

Table of Contents

  • gd_info — Retrieve information about the currently installed GD library
  • getimagesize — Get the size of an image
  • image_type_to_extension — Get file extension for image type
  • image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
  • image2wbmp — Output image to browser or file
  • imagealphablending — Set the blending mode for an image
  • imageantialias — Should antialias functions be used or not
  • imagearc — Draws an arc
  • imagechar — Draw a character horizontally
  • imagecharup — Draw a character vertically
  • imagecolorallocate — Allocate a color for an image
  • imagecolorallocatealpha — Allocate a color for an image
  • imagecolorat — Get the index of the color of a pixel
  • imagecolorclosest — Get the index of the closest color to the specified color
  • imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha
  • imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness
  • imagecolordeallocate — De-allocate a color for an image
  • imagecolorexact — Get the index of the specified color
  • imagecolorexactalpha — Get the index of the specified color + alpha
  • imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version
  • imagecolorresolve — Get the index of the specified color or its closest possible alternative
  • imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative
  • imagecolorset — Set the color for the specified palette index
  • imagecolorsforindex — Get the colors for an index
  • imagecolorstotal — Find out the number of colors in an image's palette
  • imagecolortransparent — Define a color as transparent
  • imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset
  • imagecopy — Copy part of an image
  • imagecopymerge — Copy and merge part of an image
  • imagecopymergegray — Copy and merge part of an image with gray scale
  • imagecopyresampled — Copy and resize part of an image with resampling
  • imagecopyresized — Copy and resize part of an image
  • imagecreate — Create a new palette based image
  • imagecreatefromgd2 — Create a new image from GD2 file or URL
  • imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL
  • imagecreatefromgd — Create a new image from GD file or URL
  • imagecreatefromgif — Create a new image from file or URL
  • imagecreatefromjpeg — Create a new image from file or URL
  • imagecreatefrompng — Create a new image from file or URL
  • imagecreatefromstring — Create a new image from the image stream in the string
  • imagecreatefromwbmp — Create a new image from file or URL
  • imagecreatefromxbm — Create a new image from file or URL
  • imagecreatefromxpm — Create a new image from file or URL
  • imagecreatetruecolor — Create a new true color image
  • imagedashedline — Draw a dashed line
  • imagedestroy — Destroy an image
  • imageellipse — Draw an ellipse
  • imagefill — Flood fill
  • imagefilledarc — Draw a partial arc and fill it
  • imagefilledellipse — Draw a filled ellipse
  • imagefilledpolygon — Draw a filled polygon
  • imagefilledrectangle — Draw a filled rectangle
  • imagefilltoborder — Flood fill to specific color
  • imagefilter — Applies a filter to an image
  • imagefontheight — Get font height
  • imagefontwidth — Get font width
  • imageftbbox — Give the bounding box of a text using fonts via freetype2
  • imagefttext — Write text to the image using fonts using FreeType 2
  • imagegammacorrect — Apply a gamma correction to a GD image
  • imagegd2 — Output GD2 image to browser or file
  • imagegd — Output GD image to browser or file
  • imagegif — Output image to browser or file
  • imagegrabscreen — Captures the whole screen
  • imagegrabwindow — Captures a window
  • imageinterlace — Enable or disable interlace
  • imageistruecolor — Finds whether an image is a truecolor image
  • imagejpeg — Output image to browser or file
  • imagelayereffect — Set the alpha blending flag to use the bundled libgd layering effects
  • imageline — Draw a line
  • imageloadfont — Load a new font
  • imagepalettecopy — Copy the palette from one image to another
  • imagepng — Output a PNG image to either the browser or a file
  • imagepolygon — Draws a polygon
  • imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts
  • imagepsencodefont — Change the character encoding vector of a font
  • imagepsextendfont — Extend or condense a font
  • imagepsfreefont — Free memory used by a PostScript Type 1 font
  • imagepsloadfont — Load a PostScript Type 1 font from file
  • imagepsslantfont — Slant a font
  • imagepstext — Draws a text over an image using PostScript Type1 fonts
  • imagerectangle — Draw a rectangle
  • imagerotate — Rotate an image with a given angle
  • imagesavealpha — Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images
  • imagesetbrush — Set the brush image for line drawing
  • imagesetpixel — Set a single pixel
  • imagesetstyle — Set the style for line drawing
  • imagesetthickness — Set the thickness for line drawing
  • imagesettile — Set the tile image for filling
  • imagestring — Draw a string horizontally
  • imagestringup — Draw a string vertically
  • imagesx — Get image width
  • imagesy — Get image height
  • imagetruecolortopalette — Convert a true color image to a palette image
  • imagettfbbox — Give the bounding box of a text using TrueType fonts
  • imagettftext — Write text to the image using TrueType fonts
  • imagetypes — Return the image types supported by this PHP build
  • imagewbmp — Output image to browser or file
  • imagexbm — Output XBM image to browser or file
  • iptcembed — Embeds binary IPTC data into a JPEG image
  • iptcparse — Parse a binary IPTC block into single tags.
  • jpeg2wbmp — Convert JPEG image file to WBMP image file
  • png2wbmp — Convert PNG image file to WBMP image file
Using imagecopymerge to create a translucent watermark
gd_info
GD


IMAP Functions

See Also

This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:

  • » RFC2821: Simple Mail Transfer Protocol (SMTP).
  • » RFC2822: Standard for ARPA internet text messages.
  • » RFC2060: Internet Message Access Protocol (IMAP) Version 4rev1.
  • » RFC1939: Post Office Protocol Version 3 (POP3).
  • » RFC977: Network News Transfer Protocol (NNTP).
  • » RFC2076: Common Internet Message Headers.
  • » RFC2045 , » RFC2046 , » RFC2047 , » RFC2048 & » RFC2049: Multipurpose Internet Mail Extensions (MIME).

A detailed overview is also available in the books » Programming Internet Email by David Wood and » Managing IMAP by Dianna Mullet & Kevin Mullet.

Table of Contents

  • imap_8bit — Convert an 8bit string to a quoted-printable string
  • imap_alerts — Returns all IMAP alert messages that have occurred
  • imap_append — Append a string message to a specified mailbox
  • imap_base64 — Decode BASE64 encoded text
  • imap_binary — Convert an 8bit string to a base64 string
  • imap_body — Read the message body
  • imap_bodystruct — Read the structure of a specified body section of a specific message
  • imap_check — Check current mailbox
  • imap_clearflag_full — Clears flags on messages
  • imap_close — Close an IMAP stream
  • imap_createmailbox — Create a new mailbox
  • imap_delete — Mark a message for deletion from current mailbox
  • imap_deletemailbox — Delete a mailbox
  • imap_errors — Returns all of the IMAP errors that have occured
  • imap_expunge — Delete all messages marked for deletion
  • imap_fetch_overview — Read an overview of the information in the headers of the given message
  • imap_fetchbody — Fetch a particular section of the body of the message
  • imap_fetchheader — Returns header for a message
  • imap_fetchstructure — Read the structure of a particular message
  • imap_gc — Clears IMAP cache
  • imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
  • imap_get_quotaroot — Retrieve the quota settings per user
  • imap_getacl — Gets the ACL for a given mailbox
  • imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
  • imap_getsubscribed — List all the subscribed mailboxes
  • imap_header — Alias of imap_headerinfo
  • imap_headerinfo — Read the header of the message
  • imap_headers — Returns headers for all messages in a mailbox
  • imap_last_error — Gets the last IMAP error that occurred during this page request
  • imap_list — Read the list of mailboxes
  • imap_listmailbox — Alias of imap_list
  • imap_listscan — Returns the list of mailboxes that matches the given text
  • imap_listsubscribed — Alias of imap_lsub
  • imap_lsub — List all the subscribed mailboxes
  • imap_mail_compose — Create a MIME message based on given envelope and body sections
  • imap_mail_copy — Copy specified messages to a mailbox
  • imap_mail_move — Move specified messages to a mailbox
  • imap_mail — Send an email message
  • imap_mailboxmsginfo — Get information about the current mailbox
  • imap_mime_header_decode — Decode MIME header elements
  • imap_msgno — Gets the message sequence number for the given UID
  • imap_num_msg — Gets the number of messages in the current mailbox
  • imap_num_recent — Gets the number of recent messages in current mailbox
  • imap_open — Open an IMAP stream to a mailbox
  • imap_ping — Check if the IMAP stream is still active
  • imap_qprint — Convert a quoted-printable string to an 8 bit string
  • imap_renamemailbox — Rename an old mailbox to new mailbox
  • imap_reopen — Reopen IMAP stream to new mailbox
  • imap_rfc822_parse_adrlist — Parses an address string
  • imap_rfc822_parse_headers — Parse mail headers from a string
  • imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info
  • imap_savebody — Save a specific body section to a file
  • imap_scanmailbox — Alias of imap_listscan
  • imap_search — This function returns an array of messages matching the given search criteria
  • imap_set_quota — Sets a quota for a given mailbox
  • imap_setacl — Sets the ACL for a giving mailbox
  • imap_setflag_full — Sets flags on messages
  • imap_sort — Gets and sort messages
  • imap_status — Returns status information on a mailbox
  • imap_subscribe — Subscribe to a mailbox
  • imap_thread — Returns a tree of threaded message
  • imap_timeout — Set or fetch imap timeout
  • imap_uid — This function returns the UID for the given message sequence number
  • imap_undelete — Unmark the message which is marked deleted
  • imap_unsubscribe — Unsubscribe from a mailbox
  • imap_utf7_decode — Decodes a modified UTF-7 encoded string
  • imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text
  • imap_utf8 — Converts MIME-encoded text to UTF-8
Predefined Constants
imap_8bit
IMAP


inclued Functions

Table of Contents

  • inclued_get_data — Get the inclued data
Example that implements inclued into an application
inclued_get_data
inclued


PHP Options/Info Functions

Table of Contents

  • assert_options — Set/get the various assert flags
  • assert — Checks if assertion is FALSE
  • dl — Loads a PHP extension at runtime
  • extension_loaded — Find out whether an extension is loaded
  • gc_collect_cycles — Forces collection of any existing garbage cycles
  • gc_disable — Deactivates the circular reference collector
  • gc_enable — Activates the circular reference collector
  • gc_enabled — Returns status of the circular reference collector
  • get_cfg_var — Gets the value of a PHP configuration option
  • get_current_user — Gets the name of the owner of the current PHP script
  • get_defined_constants — Returns an associative array with the names of all the constants and their values
  • get_extension_funcs — Returns an array with the names of the functions of a module
  • get_include_path — Gets the current include_path configuration option
  • get_included_files — Returns an array with the names of included or required files
  • get_loaded_extensions — Returns an array with the names of all modules compiled and loaded
  • get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc
  • get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime
  • get_required_files — Alias of get_included_files
  • getenv — Gets the value of an environment variable
  • getlastmod — Gets time of last page modification
  • getmygid — Get PHP script owner's GID
  • getmyinode — Gets the inode of the current script
  • getmypid — Gets PHP's process ID
  • getmyuid — Gets PHP script owner's UID
  • getopt — Gets options from the command line argument list
  • getrusage — Gets the current resource usages
  • ini_alter — Alias of ini_set
  • ini_get_all — Gets all configuration options
  • ini_get — Gets the value of a configuration option
  • ini_restore — Restores the value of a configuration option
  • ini_set — Sets the value of a configuration option
  • magic_quotes_runtime — Alias of set_magic_quotes_runtime
  • main — Dummy for main
  • memory_get_peak_usage — Returns the peak of memory allocated by PHP
  • memory_get_usage — Returns the amount of memory allocated to PHP
  • php_ini_loaded_file — Retrieve a path to the loaded php.ini file
  • php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir
  • php_logo_guid — Gets the logo guid
  • php_sapi_name — Returns the type of interface between web server and PHP
  • php_uname — Returns information about the operating system PHP is running on
  • phpcredits — Prints out the credits for PHP
  • phpinfo — Outputs lots of PHP information
  • phpversion — Gets the current PHP version
  • putenv — Sets the value of an environment variable
  • restore_include_path — Restores the value of the include_path configuration option
  • set_include_path — Sets the include_path configuration option
  • set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime
  • set_time_limit — Limits the maximum execution time
  • sys_get_temp_dir — Returns directory path used for temporary files
  • version_compare — Compares two "PHP-standardized" version number strings
  • zend_logo_guid — Gets the Zend guid
  • zend_thread_id — Returns a unique identifier for the current thread
  • zend_version — Gets the version of the current Zend engine
Predefined Constants
assert_options
PHP Options/Info


Ingres Functions

Table of Contents

  • ingres_autocommit_state — Test if the connection is using autocommit
  • ingres_autocommit — Switch autocommit on or off
  • ingres_charset — Returns the installation character set
  • ingres_close — Close an Ingres database connection
  • ingres_commit — Commit a transaction
  • ingres_connect — Open a connection to an Ingres database
  • ingres_cursor — Get a cursor name for a given result resource
  • ingres_errno — Get the last Ingres error number generated
  • ingres_error — Get a meaningful error message for the last error generated
  • ingres_errsqlstate — Get the last SQLSTATE error code generated
  • ingres_escape_string — Escape special characters for use in a query
  • ingres_execute — Execute a prepared query
  • ingres_fetch_array — Fetch a row of result into an array
  • ingres_fetch_assoc — Fetch a row of result into an associative array
  • ingres_fetch_object — Fetch a row of result into an object
  • ingres_fetch_proc_return — Get the return value from a procedure call
  • ingres_fetch_row — Fetch a row of result into an enumerated array
  • ingres_field_length — Get the length of a field
  • ingres_field_name — Get the name of a field in a query result
  • ingres_field_nullable — Test if a field is nullable
  • ingres_field_precision — Get the precision of a field
  • ingres_field_scale — Get the scale of a field
  • ingres_field_type — Get the type of a field in a query result
  • ingres_free_result — Free the resources associated with a result identifier
  • ingres_next_error — Get the next Ingres error
  • ingres_num_fields — Get the number of fields returned by the last query
  • ingres_num_rows — Get the number of rows affected or returned by a query
  • ingres_pconnect — Open a persistent connection to an Ingres database
  • ingres_prepare — Prepare a query for later execution
  • ingres_query — Send an SQL query to Ingres
  • ingres_result_seek — Set the row position before fetching data
  • ingres_rollback — Roll back a transaction
  • ingres_set_environment — Set environment features controlling output options
  • ingres_unbuffered_query — Send an unbuffered SQL query to Ingres
Simple Ingres Example
ingres_autocommit_state
Ingres


Inotify Functions

Table of Contents

  • inotify_add_watch — Add a watch to an initialized inotify instance
  • inotify_init — Initialize an inotify instance
  • inotify_queue_len — Return a number upper than zero if there are pending events
  • inotify_read — Read events from an inotify instance
  • inotify_rm_watch — Remove an existing watch from an inotify instance
Predefined Constants
inotify_add_watch
Inotify


intl Functions

Table of Contents

  • intl_error_name — Get symbolic name for a given error code
  • intl_get_error_code — Get the last error code
  • intl_get_error_message — Get description of the last error
  • intl_is_failure — Check whether the given error code indicates failure
idn_to_utf8
intl_error_name
intl


Grapheme Functions

Table of Contents

  • grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
  • grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strlen — Get string length in grapheme units
  • grapheme_strpos — Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • grapheme_substr — Return part of a string
ResourceBundle::getLocales
grapheme_extract
intl


IDN Functions

Table of Contents

  • idn_to_ascii — Convert domain name to IDNA ASCII form.
  • idn_to_unicode — Alias of idn_to_utf8
  • idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.
grapheme_substr
idn_to_ascii
intl


JSON Functions

Table of Contents

  • json_decode — Decodes a JSON string
  • json_encode — Returns the JSON representation of a value
  • json_last_error — Returns the last error occurred
Predefined Constants
json_decode
JSON


KADM5 Functions

Table of Contents

  • kadm5_chpass_principal — Changes the principal's password
  • kadm5_create_principal — Creates a kerberos principal with the given parameters
  • kadm5_delete_principal — Deletes a kerberos principal
  • kadm5_destroy — Closes the connection to the admin server and releases all related resources
  • kadm5_flush — Flush all changes to the Kerberos database
  • kadm5_get_policies — Gets all policies from the Kerberos database
  • kadm5_get_principal — Gets the principal's entries from the Kerberos database
  • kadm5_get_principals — Gets all principals from the Kerberos database
  • kadm5_init_with_password — Opens a connection to the KADM5 library
  • kadm5_modify_principal — Modifies a kerberos principal with the given parameters
KADM5 extension overview example
kadm5_chpass_principal
KADM5


Libevent Functions

Table of Contents

  • event_add — Add an event to the set of monitored events
  • event_base_free — Destroy event base
  • event_base_loop — Handle events
  • event_base_loopbreak — Abort event loop
  • event_base_loopexit — Exit loop after a time
  • event_base_new — Create and initialize new event base
  • event_base_priority_init — Set the number of event priority levels
  • event_base_set — Associate event base with an event
  • event_buffer_base_set — Associate buffered event with an event base
  • event_buffer_disable — Disable a buffered event
  • event_buffer_enable — Enable a buffered event
  • event_buffer_fd_set — Change a buffered event file descriptor
  • event_buffer_free — Destroy buffered event
  • event_buffer_new — Create new buffered event
  • event_buffer_priority_set — Assign a priority to a buffered event
  • event_buffer_read — Read data from a buffered event
  • event_buffer_timeout_set — Set read and write timeouts for a buffered event
  • event_buffer_watermark_set — Set the watermarks for read and write events
  • event_buffer_write — Write data to a buffered event
  • event_del — Remove an event from the set of monitored events
  • event_free — Free event resource
  • event_new — Create new event
  • event_set — Prepare an event
Examples
event_add
Libevent


LZF Functions

Table of Contents

  • lzf_compress — LZF compression
  • lzf_decompress — LZF decompression
  • lzf_optimized_for — Determines what LZF extension was optimized for
Predefined Constants
lzf_compress
LZF


Mail Functions

Table of Contents

  • ezmlm_hash — Calculate the hash value needed by EZMLM
  • mail — Send mail
Predefined Constants
ezmlm_hash
Mail


Mailparse Functions

Table of Contents

  • mailparse_determine_best_xfer_encoding — Gets the best way of encoding
  • mailparse_msg_create — Create a mime mail resource
  • mailparse_msg_extract_part_file — Extracts/decodes a message section
  • mailparse_msg_extract_part — Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding
  • mailparse_msg_free — Frees a MIME resource
  • mailparse_msg_get_part_data — Returns an associative array of info about the message
  • mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
  • mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
  • mailparse_msg_parse_file — Parses a file
  • mailparse_msg_parse — Incrementally parse data into buffer
  • mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses
  • mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp
  • mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file
Predefined Constants
mailparse_determine_best_xfer_encoding
Mailparse


Math Functions

Table of Contents

  • abs — Absolute value
  • acos — Arc cosine
  • acosh — Inverse hyperbolic cosine
  • asin — Arc sine
  • asinh — Inverse hyperbolic sine
  • atan2 — Arc tangent of two variables
  • atan — Arc tangent
  • atanh — Inverse hyperbolic tangent
  • base_convert — Convert a number between arbitrary bases
  • bindec — Binary to decimal
  • ceil — Round fractions up
  • cos — Cosine
  • cosh — Hyperbolic cosine
  • decbin — Decimal to binary
  • dechex — Decimal to hexadecimal
  • decoct — Decimal to octal
  • deg2rad — Converts the number in degrees to the radian equivalent
  • exp — Calculates the exponent of e
  • expm1 — Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
  • floor — Round fractions down
  • fmod — Returns the floating point remainder (modulo) of the division of the arguments
  • getrandmax — Show largest possible random value
  • hexdec — Hexadecimal to decimal
  • hypot — Calculate the length of the hypotenuse of a right-angle triangle
  • is_finite — Finds whether a value is a legal finite number
  • is_infinite — Finds whether a value is infinite
  • is_nan — Finds whether a value is not a number
  • lcg_value — Combined linear congruential generator
  • log10 — Base-10 logarithm
  • log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
  • log — Natural logarithm
  • max — Find highest value
  • min — Find lowest value
  • mt_getrandmax — Show largest possible random value
  • mt_rand — Generate a better random value
  • mt_srand — Seed the better random number generator
  • octdec — Octal to decimal
  • pi — Get value of pi
  • pow — Exponential expression
  • rad2deg — Converts the radian number to the equivalent number in degrees
  • rand — Generate a random integer
  • round — Rounds a float
  • sin — Sine
  • sinh — Hyperbolic sine
  • sqrt — Square root
  • srand — Seed the random number generator
  • tan — Tangent
  • tanh — Hyperbolic tangent
Predefined Constants
abs
Math


MaxDB extension overview example
maxdb_affected_rows
MaxDB
PHP Manual

MaxDB Functions

Predefined Classes

maxdb

Represents a connection between PHP and a MaxDB database.

Constructor

  • maxdb - construct a new maxdb object

Methods

  • autocommit - turns on or off auto-commiting database modifications

  • change_user - changes the user of the specified database connection

  • character_set_name - returns the default character set for the database connection

  • close - closes a previously opened connection

  • commit - commits the current transaction

  • connect - opens a new connection to MaxDB database server

  • debug - performs debugging operations

  • dump_debug_info - dumps debug information

  • get_client_info - returns client version

  • get_host_info - returns type of connection used

  • get_server_info - returns version of the MaxDB server

  • get_server_version - returns version of the MaxDB server

  • init - initializes maxdb object

  • info - retrieves information about the most recently executed query

  • kill - asks the server to kill a MaxDB thread

  • multi_query - performs multiple queries

  • more_results - check if more results exist from currently executed multi-query

  • next_result - reads next result from currently executed multi-query

  • options - set options

  • ping - pings a server connection or reconnects if there is no connection

  • prepare - prepares a SQL query

  • query - performs a query

  • real_connect - attempts to open a connection to MaxDB database server

  • escape_string - escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

  • rollback - rolls back the current transaction

  • select_db - selects the default database

  • ssl_set - sets ssl parameters

  • stat - gets the current system status

  • stmt_init- initializes a statement for use with maxdb_stmt_prepare

  • store_result - transfers a resultset from last query

  • use_result - transfers an unbuffered resultset from last query

  • thread-safe - returns whether thread safety is given or not

Properties

  • affected_rows - gets the number of affected rows in a previous MaxDB operation

  • client_info - returns the MaxDB client version as a string

  • client_version - returns the MaxDB client version as an integer

  • errno - returns the error code for the most recent function call

  • error - returns the error string for the most recent function call

  • field_count - returns the number of columns for the most recent query

  • host_info - returns a string representing the type of connection used

  • info - retrieves information about the most recently executed query

  • insert_id - returns the auto generated id used in the last query

  • protocol_version - returns the version of the MaxDB protocol used

  • sqlstate - returns a string containing the SQLSTATE error code for the last error

  • thread_id - returns the thread ID for the current connection

  • warning_count - returns the number of warnings generated during execution of the previous SQL statement

maxdb_stmt

Represents a prepared statement.

Methods

  • bind_param - binds variables to a prepared statement

  • bind_result - binds variables to a prepared statement for result storage

  • close - closes a prepared statement

  • data-seek - seeks to an arbitrary row in a statement result set

  • execute - executes a prepared statement

  • fetch - fetches result from a prepared statement into bound variables

  • free_result - frees stored result memory for the given statement handle

  • result_metadata - retrieves a resultset from a prepared statement for metadata information

  • prepare - prepares a SQL query

  • send_long_data - sends data in chunks

  • close_long_data - end sending long data

  • reset - resets a prepared statement

  • store_result - buffers complete resultset from a prepared statement

Properties

  • affected_rows - returns affected rows from last statement execution

  • errno - returns errorcode for last statement function

  • errno - returns errormessage for last statement function

  • param_count - returns number of parameter for a given prepare statement

  • sqlstate - returns a string containing the SQLSTATE error code for the last statement function

maxdb_result

Represents the result set obtained from a query against the database.

Methods

  • close - closes resultset

  • data_seek - moves internal result pointer

  • fetch_field - gets column information from a resultset

  • fetch_fields - gets information for all columns from a resulset

  • fetch_field_direct - gets column information for specified column

  • fetch_array - fetches a result row as an associative array, a numeric array, or both.

  • fetch_assoc - fetches a result row as an associative array

  • fetch_object - fetches a result row as an object

  • fetch_row - gets a result row as an enumerated array

  • close - frees result memory

  • field_seek - set result pointer to a specified field offset

Properties

  • current_field - returns offset of current fieldpointer

  • field_count - returns number of fields in resultset

  • lengths - returns an array of columnlengths

  • num_rows - returns number of rows in resultset

Table of Contents

  • maxdb_affected_rows — Gets the number of affected rows in a previous MaxDB operation
  • maxdb_autocommit — Turns on or off auto-commiting database modifications
  • maxdb_bind_param — Alias of maxdb_stmt_bind_param
  • maxdb_bind_result — Alias of maxdb_stmt_bind_result
  • maxdb_change_user — Changes the user of the specified database connection
  • maxdb_character_set_name — Returns the default character set for the database connection
  • maxdb_client_encoding — Alias of maxdb_character_set_name
  • maxdb_close_long_data — Alias of maxdb_stmt_close_long_data
  • maxdb_close — Closes a previously opened database connection
  • maxdb_commit — Commits the current transaction
  • maxdb_connect_errno — Returns the error code from last connect call
  • maxdb_connect_error — Returns a string description of the last connect error
  • maxdb_connect — Open a new connection to the MaxDB server
  • maxdb_data_seek — Adjusts the result pointer to an arbitary row in the result
  • maxdb_debug — Performs debugging operations
  • maxdb_disable_reads_from_master — Disable reads from master
  • maxdb_disable_rpl_parse — Disable RPL parse
  • maxdb_dump_debug_info — Dump debugging information into the log
  • maxdb_embedded_connect — Open a connection to an embedded MaxDB server
  • maxdb_enable_reads_from_master — Enable reads from master
  • maxdb_enable_rpl_parse — Enable RPL parse
  • maxdb_errno — Returns the error code for the most recent function call
  • maxdb_error — Returns a string description of the last error
  • maxdb_escape_string — Alias of maxdb_real_escape_string
  • maxdb_execute — Alias of maxdb_stmt_execute
  • maxdb_fetch_array — Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_assoc — Fetch a result row as an associative array
  • maxdb_fetch_field_direct — Fetch meta-data for a single field
  • maxdb_fetch_field — Returns the next field in the result set
  • maxdb_fetch_fields — Returns an array of resources representing the fields in a result set
  • maxdb_fetch_lengths — Returns the lengths of the columns of the current row in the result set
  • maxdb_fetch_object — Returns the current row of a result set as an object
  • maxdb_fetch_row — Get a result row as an enumerated array
  • maxdb_fetch — Alias of maxdb_stmt_fetch
  • maxdb_field_count — Returns the number of columns for the most recent query
  • maxdb_field_seek — Set result pointer to a specified field offset
  • maxdb_field_tell — Get current field offset of a result pointer
  • maxdb_free_result — Frees the memory associated with a result
  • maxdb_get_client_info — Returns the MaxDB client version as a string
  • maxdb_get_client_version — Get MaxDB client info
  • maxdb_get_host_info — Returns a string representing the type of connection used
  • maxdb_get_metadata — Alias of maxdb_stmt_result_metadata
  • maxdb_get_proto_info — Returns the version of the MaxDB protocol used
  • maxdb_get_server_info — Returns the version of the MaxDB server
  • maxdb_get_server_version — Returns the version of the MaxDB server as an integer
  • maxdb_info — Retrieves information about the most recently executed query
  • maxdb_init — Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_insert_id — Returns the auto generated id used in the last query
  • maxdb_kill — Disconnects from a MaxDB server
  • maxdb_master_query — Enforce execution of a query on the master in a master/slave setup
  • maxdb_more_results — Check if there any more query results from a multi query
  • maxdb_multi_query — Performs a query on the database
  • maxdb_next_result — Prepare next result from multi_query
  • maxdb_num_fields — Get the number of fields in a result
  • maxdb_num_rows — Gets the number of rows in a result
  • maxdb_options — Set options
  • maxdb_param_count — Alias of maxdb_stmt_param_count
  • maxdb_ping — Pings a server connection, or tries to reconnect if the connection has gone down
  • maxdb_prepare — Prepare a SQL statement for execution
  • maxdb_query — Performs a query on the database
  • maxdb_real_connect — Opens a connection to a MaxDB server
  • maxdb_real_escape_string — Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
  • maxdb_real_query — Execute an SQL query
  • maxdb_report — Enables or disables internal report functions
  • maxdb_rollback — Rolls back current transaction
  • maxdb_rpl_parse_enabled — Check if RPL parse is enabled
  • maxdb_rpl_probe — RPL probe
  • maxdb_rpl_query_type — Returns RPL query type
  • maxdb_select_db — Selects the default database for database queries
  • maxdb_send_long_data — Alias of maxdb_stmt_send_long_data
  • maxdb_send_query — Send the query and return
  • maxdb_server_end — Shut down the embedded server
  • maxdb_server_init — Initialize embedded server
  • maxdb_set_opt — Alias of maxdb_options
  • maxdb_sqlstate — Returns the SQLSTATE error from previous MaxDB operation
  • maxdb_ssl_set — Used for establishing secure connections using SSL
  • maxdb_stat — Gets the current system status
  • maxdb_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • maxdb_stmt_bind_param — Binds variables to a prepared statement as parameters
  • maxdb_stmt_bind_result — Binds variables to a prepared statement for result storage
  • maxdb_stmt_close_long_data — Ends a sequence of maxdb_stmt_send_long_data
  • maxdb_stmt_close — Closes a prepared statement
  • maxdb_stmt_data_seek — Seeks to an arbitray row in statement result set
  • maxdb_stmt_errno — Returns the error code for the most recent statement call
  • maxdb_stmt_error — Returns a string description for last statement error
  • maxdb_stmt_execute — Executes a prepared Query
  • maxdb_stmt_fetch — Fetch results from a prepared statement into the bound variables
  • maxdb_stmt_free_result — Frees stored result memory for the given statement handle
  • maxdb_stmt_init — Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_num_rows — Return the number of rows in statements result set
  • maxdb_stmt_param_count — Returns the number of parameter for the given statement
  • maxdb_stmt_prepare — Prepare a SQL statement for execution
  • maxdb_stmt_reset — Resets a prepared statement
  • maxdb_stmt_result_metadata — Returns result set metadata from a prepared statement
  • maxdb_stmt_send_long_data — Send data in blocks
  • maxdb_stmt_sqlstate — Returns SQLSTATE error from previous statement operation
  • maxdb_stmt_store_result — Transfers a result set from a prepared statement
  • maxdb_store_result — Transfers a result set from the last query
  • maxdb_thread_id — Returns the thread ID for the current connection
  • maxdb_thread_safe — Returns whether thread safety is given or not
  • maxdb_use_result — Initiate a result set retrieval
  • maxdb_warning_count — Returns the number of warnings from the last query for the given link
MaxDB extension overview example
maxdb_affected_rows
MaxDB
PHP Manual


Multibyte String Functions

References

Multibyte character encoding schemes and their related issues are fairly complicated, and are beyond the scope of this documentation. Please refer to the following URLs and other resources for further information regarding these topics.

  • Unicode materials

    » http://www.unicode.org/

  • Japanese/Korean/Chinese character information

    » http://examples.oreilly.com/cjkvinfo/doc/cjk.inf

Table of Contents

  • mb_check_encoding — Check if the string is valid for the specified encoding
  • mb_convert_case — Perform case folding on a string
  • mb_convert_encoding — Convert character encoding
  • mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
  • mb_convert_variables — Convert character code in variable(s)
  • mb_decode_mimeheader — Decode string in MIME header field
  • mb_decode_numericentity — Decode HTML numeric string reference to character
  • mb_detect_encoding — Detect character encoding
  • mb_detect_order — Set/Get character encoding detection order
  • mb_encode_mimeheader — Encode string for MIME header
  • mb_encode_numericentity — Encode character to HTML numeric string reference
  • mb_ereg_match — Regular expression match for multibyte string
  • mb_ereg_replace — Replace regular expression with multibyte support
  • mb_ereg_search_getpos — Returns start point for next regular expression match
  • mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match
  • mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match
  • mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
  • mb_ereg_search_regs — Returns the matched part of a multibyte regular expression
  • mb_ereg_search_setpos — Set start point of next regular expression match
  • mb_ereg_search — Multibyte regular expression match for predefined multibyte string
  • mb_ereg — Regular expression match with multibyte support
  • mb_eregi_replace — Replace regular expression with multibyte support ignoring case
  • mb_eregi — Regular expression match ignoring case with multibyte support
  • mb_get_info — Get internal settings of mbstring
  • mb_http_input — Detect HTTP input character encoding
  • mb_http_output — Set/Get HTTP output character encoding
  • mb_internal_encoding — Set/Get internal character encoding
  • mb_language — Set/Get current language
  • mb_list_encodings — Returns an array of all supported encodings
  • mb_output_handler — Callback function converts character encoding in output buffer
  • mb_parse_str — Parse GET/POST/COOKIE data and set global variable
  • mb_preferred_mime_name — Get MIME charset string
  • mb_regex_encoding — Returns current encoding for multibyte regex as string
  • mb_regex_set_options — Set/Get the default options for mbregex functions
  • mb_send_mail — Send encoded mail
  • mb_split — Split multibyte string using regular expression
  • mb_strcut — Get part of string
  • mb_strimwidth — Get truncated string with specified width
  • mb_stripos — Finds position of first occurrence of a string within another, case insensitive
  • mb_stristr — Finds first occurrence of a string within another, case insensitive
  • mb_strlen — Get string length
  • mb_strpos — Find position of first occurrence of string in a string
  • mb_strrchr — Finds the last occurrence of a character in a string within another
  • mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive
  • mb_strripos — Finds position of last occurrence of a string within another, case insensitive
  • mb_strrpos — Find position of last occurrence of a string in a string
  • mb_strstr — Finds first occurrence of a string within another
  • mb_strtolower — Make a string lowercase
  • mb_strtoupper — Make a string uppercase
  • mb_strwidth — Return width of string
  • mb_substitute_character — Set/Get substitution character
  • mb_substr_count — Count the number of substring occurrences
  • mb_substr — Get part of string
PHP Character Encoding Requirements
mb_check_encoding
Multibyte String


Mcrypt Functions

Table of Contents

  • mcrypt_cbc — Encrypt/decrypt data in CBC mode
  • mcrypt_cfb — Encrypt/decrypt data in CFB mode
  • mcrypt_create_iv — Create an initialization vector (IV) from a random source
  • mcrypt_decrypt — Decrypts crypttext with given parameters
  • mcrypt_ecb — Deprecated: Encrypt/decrypt data in ECB mode
  • mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm
  • mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm
  • mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm
  • mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode
  • mcrypt_enc_get_modes_name — Returns the name of the opened mode
  • mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
  • mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks
  • mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm
  • mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks
  • mcrypt_enc_self_test — Runs a self test on the opened module
  • mcrypt_encrypt — Encrypts plaintext with given parameters
  • mcrypt_generic_deinit — This function deinitializes an encryption module
  • mcrypt_generic_end — This function terminates encryption
  • mcrypt_generic_init — This function initializes all buffers needed for encryption
  • mcrypt_generic — This function encrypts data
  • mcrypt_get_block_size — Get the block size of the specified cipher
  • mcrypt_get_cipher_name — Get the name of the specified cipher
  • mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination
  • mcrypt_get_key_size — Get the key size of the specified cipher
  • mcrypt_list_algorithms — Get an array of all supported ciphers
  • mcrypt_list_modes — Get an array of all supported modes
  • mcrypt_module_close — Close the mcrypt module
  • mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm
  • mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode
  • mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
  • mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not
  • mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm
  • mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not
  • mcrypt_module_open — Opens the module of the algorithm and the mode to be used
  • mcrypt_module_self_test — This function runs a self test on the specified module
  • mcrypt_ofb — Encrypt/decrypt data in OFB mode
  • mdecrypt_generic — Decrypt data
Examples
mcrypt_cbc
Mcrypt


MCVE Functions

See Also

Additional documentation about MCVE/Monetra's PHP API can be found at » http://www.mainstreetsoftworks.com/documentation.html. Main Street's documentation is complete and should be the primary reference for functions.

Table of Contents

  • m_checkstatus — Check to see if a transaction has completed
  • m_completeauthorizations — Number of complete authorizations in queue, returning an array of their identifiers
  • m_connect — Establish the connection to MCVE
  • m_connectionerror — Get a textual representation of why a connection failed
  • m_deletetrans — Delete specified transaction from MCVE_CONN structure
  • m_destroyconn — Destroy the connection and MCVE_CONN structure
  • m_destroyengine — Free memory associated with IP/SSL connectivity
  • m_getcell — Get a specific cell from a comma delimited response by column name
  • m_getcellbynum — Get a specific cell from a comma delimited response by column number
  • m_getcommadelimited — Get the RAW comma delimited data returned from MCVE
  • m_getheader — Get the name of the column in a comma-delimited response
  • m_initconn — Create and initialize an MCVE_CONN structure
  • m_initengine — Ready the client for IP/SSL Communication
  • m_iscommadelimited — Checks to see if response is comma delimited
  • m_maxconntimeout — The maximum amount of time the API will attempt a connection to MCVE
  • m_monitor — Perform communication with MCVE (send/receive data) Non-blocking
  • m_numcolumns — Number of columns returned in a comma delimited response
  • m_numrows — Number of rows returned in a comma delimited response
  • m_parsecommadelimited — Parse the comma delimited response so m_getcell, etc will work
  • m_responsekeys — Returns array of strings which represents the keys that can be used for response parameters on this transaction
  • m_responseparam — Get a custom response parameter
  • m_returnstatus — Check to see if the transaction was successful
  • m_setblocking — Set blocking/non-blocking mode for connection
  • m_setdropfile — Set the connection method to Drop-File
  • m_setip — Set the connection method to IP
  • m_setssl_cafile — Set SSL CA (Certificate Authority) file for verification of server certificate
  • m_setssl_files — Set certificate key files and certificates if server requires client certificate verification
  • m_setssl — Set the connection method to SSL
  • m_settimeout — Set maximum transaction time (per trans)
  • m_sslcert_gen_hash — Generate hash for SSL client certificate verification
  • m_transactionssent — Check to see if outgoing buffer is clear
  • m_transinqueue — Number of transactions in client-queue
  • m_transkeyval — Add key/value pair to a transaction. Replaces deprecated transparam()
  • m_transnew — Start a new transaction
  • m_transsend — Finalize and send the transaction
  • m_uwait — Wait x microsecs
  • m_validateidentifier — Whether or not to validate the passed identifier on any transaction it is passed to
  • m_verifyconnection — Set whether or not to PING upon connect to verify connection
  • m_verifysslcert — Set whether or not to verify the server ssl certificate
Predefined Constants
m_checkstatus
MCVE


Mhash Functions

Table of Contents

  • mhash_count — Get the highest available hash id
  • mhash_get_block_size — Get the block size of the specified hash
  • mhash_get_hash_name — Get the name of the specified hash
  • mhash_keygen_s2k — Generates a key
  • mhash — Compute hash
Examples
mhash_count
Mhash


Ming Functions

Table of Contents

  • ming_keypress — Returns the action flag for keyPress(char)
  • ming_setcubicthreshold — Set cubic threshold
  • ming_setscale — Set the global scaling factor.
  • ming_setswfcompression — Sets the SWF output compression
  • ming_useconstants — Use constant pool
  • ming_useswfversion — Sets the SWF version
SWFSPrite basic examples
ming_keypress
Ming


Misc. Functions

Table of Contents

  • connection_aborted — Check whether client disconnected
  • connection_status — Returns connection status bitfield
  • connection_timeout — Check if the script timed out
  • constant — Returns the value of a constant
  • define — Defines a named constant
  • defined — Checks whether a given named constant exists
  • die — Equivalent to exit
  • eval — Evaluate a string as PHP code
  • exit — Output a message and terminate the current script
  • get_browser — Tells what the user's browser is capable of
  • __halt_compiler — Halts the compiler execution
  • highlight_file — Syntax highlighting of a file
  • highlight_string — Syntax highlighting of a string
  • ignore_user_abort — Set whether a client disconnect should abort script execution
  • pack — Pack data into binary string
  • php_check_syntax — Check the PHP syntax of (and execute) the specified file
  • php_strip_whitespace — Return source with stripped comments and whitespace
  • show_source — Alias of highlight_file
  • sleep — Delay execution
  • sys_getloadavg — Gets system load average
  • time_nanosleep — Delay for a number of seconds and nanoseconds
  • time_sleep_until — Make the script sleep until the specified time
  • uniqid — Generate a unique ID
  • unpack — Unpack data from binary string
  • usleep — Delay execution in microseconds
Predefined Constants
connection_aborted
Misc.


Mongo Functions

Table of Contents

  • bson_decode — Deserializes a BSON object into a PHP array
  • bson_encode — Serializes a PHP variable into a BSON string
Functions
bson_decode
Functions


mSQL Functions

Table of Contents

  • msql_affected_rows — Returns number of affected rows
  • msql_close — Close mSQL connection
  • msql_connect — Open mSQL connection
  • msql_create_db — Create mSQL database
  • msql_createdb — Alias of msql_create_db
  • msql_data_seek — Move internal row pointer
  • msql_db_query — Send mSQL query
  • msql_dbname — Alias of msql_result
  • msql_drop_db — Drop (delete) mSQL database
  • msql_error — Returns error message of last msql call
  • msql_fetch_array — Fetch row as array
  • msql_fetch_field — Get field information
  • msql_fetch_object — Fetch row as object
  • msql_fetch_row — Get row as enumerated array
  • msql_field_flags — Get field flags
  • msql_field_len — Get field length
  • msql_field_name — Get the name of the specified field in a result
  • msql_field_seek — Set field offset
  • msql_field_table — Get table name for field
  • msql_field_type — Get field type
  • msql_fieldflags — Alias of msql_field_flags
  • msql_fieldlen — Alias of msql_field_len
  • msql_fieldname — Alias of msql_field_name
  • msql_fieldtable — Alias of msql_field_table
  • msql_fieldtype — Alias of msql_field_type
  • msql_free_result — Free result memory
  • msql_list_dbs — List mSQL databases on server
  • msql_list_fields — List result fields
  • msql_list_tables — List tables in an mSQL database
  • msql_num_fields — Get number of fields in result
  • msql_num_rows — Get number of rows in result
  • msql_numfields — Alias of msql_num_fields
  • msql_numrows — Alias of msql_num_rows
  • msql_pconnect — Open persistent mSQL connection
  • msql_query — Send mSQL query
  • msql_regcase — Alias of sql_regcase
  • msql_result — Get result data
  • msql_select_db — Select mSQL database
  • msql_tablename — Alias of msql_result
  • msql — Alias of msql_db_query
mSQL usage example
msql_affected_rows
mSQL


Mssql Functions

Table of Contents

  • mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_close — Close MS SQL Server connection
  • mssql_connect — Open MS SQL server connection
  • mssql_data_seek — Moves internal row pointer
  • mssql_execute — Executes a stored procedure on a MS SQL server database
  • mssql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_assoc — Returns an associative array of the current row in the result
  • mssql_fetch_batch — Returns the next batch of records
  • mssql_fetch_field — Get field information
  • mssql_fetch_object — Fetch row as object
  • mssql_fetch_row — Get row as enumerated array
  • mssql_field_length — Get the length of a field
  • mssql_field_name — Get the name of a field
  • mssql_field_seek — Seeks to the specified field offset
  • mssql_field_type — Gets the type of a field
  • mssql_free_result — Free result memory
  • mssql_free_statement — Free statement memory
  • mssql_get_last_message — Returns the last message from the server
  • mssql_guid_string — Converts a 16 byte binary GUID to a string
  • mssql_init — Initializes a stored procedure or a remote stored procedure
  • mssql_min_error_severity — Sets the minimum error severity
  • mssql_min_message_severity — Sets the minimum message severity
  • mssql_next_result — Move the internal result pointer to the next result
  • mssql_num_fields — Gets the number of fields in result
  • mssql_num_rows — Gets the number of rows in result
  • mssql_pconnect — Open persistent MS SQL connection
  • mssql_query — Send MS SQL query
  • mssql_result — Get result data
  • mssql_rows_affected — Returns the number of records affected by the query
  • mssql_select_db — Select MS SQL database
Predefined Constants
mssql_bind
Mssql


MySQL Functions

Notes

Note: Most MySQL functions accept link_identifier as the last optional parameter. If it is not provided, last opened connection is used. If it doesn't exist, connection is tried to establish with default parameters defined in php.ini. If it is not successful, functions return FALSE.

Table of Contents

  • mysql_affected_rows — Get number of affected rows in previous MySQL operation
  • mysql_client_encoding — Returns the name of the character set
  • mysql_close — Close MySQL connection
  • mysql_connect — Open a connection to a MySQL Server
  • mysql_create_db — Create a MySQL database
  • mysql_data_seek — Move internal result pointer
  • mysql_db_name — Get result data
  • mysql_db_query — Send a MySQL query
  • mysql_drop_db — Drop (delete) a MySQL database
  • mysql_errno — Returns the numerical value of the error message from previous MySQL operation
  • mysql_error — Returns the text of the error message from previous MySQL operation
  • mysql_escape_string — Escapes a string for use in a mysql_query
  • mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • mysql_fetch_assoc — Fetch a result row as an associative array
  • mysql_fetch_field — Get column information from a result and return as an object
  • mysql_fetch_lengths — Get the length of each output in a result
  • mysql_fetch_object — Fetch a result row as an object
  • mysql_fetch_row — Get a result row as an enumerated array
  • mysql_field_flags — Get the flags associated with the specified field in a result
  • mysql_field_len — Returns the length of the specified field
  • mysql_field_name — Get the name of the specified field in a result
  • mysql_field_seek — Set result pointer to a specified field offset
  • mysql_field_table — Get name of the table the specified field is in
  • mysql_field_type — Get the type of the specified field in a result
  • mysql_free_result — Free result memory
  • mysql_get_client_info — Get MySQL client info
  • mysql_get_host_info — Get MySQL host info
  • mysql_get_proto_info — Get MySQL protocol info
  • mysql_get_server_info — Get MySQL server info
  • mysql_info — Get information about the most recent query
  • mysql_insert_id — Get the ID generated in the last query
  • mysql_list_dbs — List databases available on a MySQL server
  • mysql_list_fields — List MySQL table fields
  • mysql_list_processes — List MySQL processes
  • mysql_list_tables — List tables in a MySQL database
  • mysql_num_fields — Get number of fields in result
  • mysql_num_rows — Get number of rows in result
  • mysql_pconnect — Open a persistent connection to a MySQL server
  • mysql_ping — Ping a server connection or reconnect if there is no connection
  • mysql_query — Send a MySQL query
  • mysql_real_escape_string — Escapes special characters in a string for use in a SQL statement
  • mysql_result — Get result data
  • mysql_select_db — Select a MySQL database
  • mysql_set_charset — Sets the client character set
  • mysql_stat — Get current system status
  • mysql_tablename — Get table name of field
  • mysql_thread_id — Return the current thread ID
  • mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows.
MySQL extension overview example
mysql_affected_rows
MySQL


Aliases and deprecated Mysqli Functions

Table of Contents

  • mysqli_bind_param — Alias for mysqli_stmt_bind_param
  • mysqli_bind_result — Alias for mysqli_stmt_bind_result
  • mysqli_client_encoding — Alias of mysqli_character_set_name
  • mysqli_disable_reads_from_master — Disable reads from master
  • mysqli_disable_rpl_parse — Disable RPL parse
  • mysqli_enable_reads_from_master — Enable reads from master
  • mysqli_enable_rpl_parse — Enable RPL parse
  • mysqli_escape_string — Alias of mysqli_real_escape_string
  • mysqli_execute — Alias for mysqli_stmt_execute
  • mysqli_fetch — Alias for mysqli_stmt_fetch
  • mysqli_get_cache_stats — Returns client Zval cache statistics
  • mysqli_get_client_stats — Returns client per-process statistics
  • mysqli_get_metadata — Alias for mysqli_stmt_result_metadata
  • mysqli_master_query — Enforce execution of a query on the master in a master/slave setup
  • mysqli_param_count — Alias for mysqli_stmt_param_count
  • mysqli_report — Enables or disables internal report functions
  • mysqli_rpl_parse_enabled — Check if RPL parse is enabled
  • mysqli_rpl_probe — RPL probe
  • mysqli_rpl_query_type — Returns RPL query type
  • mysqli_send_long_data — Alias for mysqli_stmt_send_long_data
  • mysqli_send_query — Send the query and return
  • mysqli_set_opt — Alias of mysqli_options
  • mysqli_slave_query — Force execution of a query on a slave in a master/slave setup
mysqli_warning::next
mysqli_bind_param
Mysqli


Ncurses Functions

Table of Contents

  • ncurses_addch — Add character at current position and advance cursor
  • ncurses_addchnstr — Add attributed string with specified length at current position
  • ncurses_addchstr — Add attributed string at current position
  • ncurses_addnstr — Add string with specified length at current position
  • ncurses_addstr — Output text at current position
  • ncurses_assume_default_colors — Define default colors for color 0
  • ncurses_attroff — Turn off the given attributes
  • ncurses_attron — Turn on the given attributes
  • ncurses_attrset — Set given attributes
  • ncurses_baudrate — Returns baudrate of terminal
  • ncurses_beep — Let the terminal beep
  • ncurses_bkgd — Set background property for terminal screen
  • ncurses_bkgdset — Control screen background
  • ncurses_border — Draw a border around the screen using attributed characters
  • ncurses_bottom_panel — Moves a visible panel to the bottom of the stack
  • ncurses_can_change_color — Checks if terminal color definitions can be changed
  • ncurses_cbreak — Switch of input buffering
  • ncurses_clear — Clear screen
  • ncurses_clrtobot — Clear screen from current position to bottom
  • ncurses_clrtoeol — Clear screen from current position to end of line
  • ncurses_color_content — Retrieves RGB components of a color
  • ncurses_color_set — Set active foreground and background colors
  • ncurses_curs_set — Set cursor state
  • ncurses_def_prog_mode — Saves terminals (program) mode
  • ncurses_def_shell_mode — Saves terminals (shell) mode
  • ncurses_define_key — Define a keycode
  • ncurses_del_panel — Remove panel from the stack and delete it (but not the associated window)
  • ncurses_delay_output — Delay output on terminal using padding characters
  • ncurses_delch — Delete character at current position, move rest of line left
  • ncurses_deleteln — Delete line at current position, move rest of screen up
  • ncurses_delwin — Delete a ncurses window
  • ncurses_doupdate — Write all prepared refreshes to terminal
  • ncurses_echo — Activate keyboard input echo
  • ncurses_echochar — Single character output including refresh
  • ncurses_end — Stop using ncurses, clean up the screen
  • ncurses_erase — Erase terminal screen
  • ncurses_erasechar — Returns current erase character
  • ncurses_filter — Set LINES for iniscr() and newterm() to 1
  • ncurses_flash — Flash terminal screen (visual bell)
  • ncurses_flushinp — Flush keyboard input buffer
  • ncurses_getch — Read a character from keyboard
  • ncurses_getmaxyx — Returns the size of a window
  • ncurses_getmouse — Reads mouse event
  • ncurses_getyx — Returns the current cursor position for a window
  • ncurses_halfdelay — Put terminal into halfdelay mode
  • ncurses_has_colors — Checks if terminal has color capabilities
  • ncurses_has_ic — Check for insert- and delete-capabilities
  • ncurses_has_il — Check for line insert- and delete-capabilities
  • ncurses_has_key — Check for presence of a function key on terminal keyboard
  • ncurses_hide_panel — Remove panel from the stack, making it invisible
  • ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long
  • ncurses_inch — Get character and attribute at current position
  • ncurses_init_color — Define a terminal color
  • ncurses_init_pair — Define a color pair
  • ncurses_init — Initialize ncurses
  • ncurses_insch — Insert character moving rest of line including character at current position
  • ncurses_insdelln — Insert lines before current line scrolling down (negative numbers delete and scroll up)
  • ncurses_insertln — Insert a line, move rest of screen down
  • ncurses_insstr — Insert string at current position, moving rest of line right
  • ncurses_instr — Reads string from terminal screen
  • ncurses_isendwin — Ncurses is in endwin mode, normal screen output may be performed
  • ncurses_keyok — Enable or disable a keycode
  • ncurses_keypad — Turns keypad on or off
  • ncurses_killchar — Returns current line kill character
  • ncurses_longname — Returns terminals description
  • ncurses_meta — Enables/Disable 8-bit meta key information
  • ncurses_mouse_trafo — Transforms coordinates
  • ncurses_mouseinterval — Set timeout for mouse button clicks
  • ncurses_mousemask — Sets mouse options
  • ncurses_move_panel — Moves a panel so that its upper-left corner is at [startx, starty]
  • ncurses_move — Move output position
  • ncurses_mvaddch — Move current position and add character
  • ncurses_mvaddchnstr — Move position and add attributed string with specified length
  • ncurses_mvaddchstr — Move position and add attributed string
  • ncurses_mvaddnstr — Move position and add string with specified length
  • ncurses_mvaddstr — Move position and add string
  • ncurses_mvcur — Move cursor immediately
  • ncurses_mvdelch — Move position and delete character, shift rest of line left
  • ncurses_mvgetch — Move position and get character at new position
  • ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long
  • ncurses_mvinch — Move position and get attributed character at new position
  • ncurses_mvvline — Set new position and draw a vertical line using an attributed character and max. n characters long
  • ncurses_mvwaddstr — Add string at new position in window
  • ncurses_napms — Sleep
  • ncurses_new_panel — Create a new panel and associate it with window
  • ncurses_newpad — Creates a new pad (window)
  • ncurses_newwin — Create a new window
  • ncurses_nl — Translate newline and carriage return / line feed
  • ncurses_nocbreak — Switch terminal to cooked mode
  • ncurses_noecho — Switch off keyboard input echo
  • ncurses_nonl — Do not translate newline and carriage return / line feed
  • ncurses_noqiflush — Do not flush on signal characters
  • ncurses_noraw — Switch terminal out of raw mode
  • ncurses_pair_content — Retrieves foreground and background colors of a color pair
  • ncurses_panel_above — Returns the panel above panel
  • ncurses_panel_below — Returns the panel below panel
  • ncurses_panel_window — Returns the window associated with panel
  • ncurses_pnoutrefresh — Copies a region from a pad into the virtual screen
  • ncurses_prefresh — Copies a region from a pad into the virtual screen
  • ncurses_putp — Apply padding information to the string and output it
  • ncurses_qiflush — Flush on signal characters
  • ncurses_raw — Switch terminal into raw mode
  • ncurses_refresh — Refresh screen
  • ncurses_replace_panel — Replaces the window associated with panel
  • ncurses_reset_prog_mode — Resets the prog mode saved by def_prog_mode
  • ncurses_reset_shell_mode — Resets the shell mode saved by def_shell_mode
  • ncurses_resetty — Restores saved terminal state
  • ncurses_savetty — Saves terminal state
  • ncurses_scr_dump — Dump screen content to file
  • ncurses_scr_init — Initialize screen from file dump
  • ncurses_scr_restore — Restore screen from file dump
  • ncurses_scr_set — Inherit screen from file dump
  • ncurses_scrl — Scroll window content up or down without changing current position
  • ncurses_show_panel — Places an invisible panel on top of the stack, making it visible
  • ncurses_slk_attr — Returns current soft label key attribute
  • ncurses_slk_attroff — Turn off the given attributes for soft function-key labels
  • ncurses_slk_attron — Turn on the given attributes for soft function-key labels
  • ncurses_slk_attrset — Set given attributes for soft function-key labels
  • ncurses_slk_clear — Clears soft labels from screen
  • ncurses_slk_color — Sets color for soft label keys
  • ncurses_slk_init — Initializes soft label key functions
  • ncurses_slk_noutrefresh — Copies soft label keys to virtual screen
  • ncurses_slk_refresh — Copies soft label keys to screen
  • ncurses_slk_restore — Restores soft label keys
  • ncurses_slk_set — Sets function key labels
  • ncurses_slk_touch — Forces output when ncurses_slk_noutrefresh is performed
  • ncurses_standend — Stop using 'standout' attribute
  • ncurses_standout — Start using 'standout' attribute
  • ncurses_start_color — Initializes color functionality
  • ncurses_termattrs — Returns a logical OR of all attribute flags supported by terminal
  • ncurses_termname — Returns terminals (short)-name
  • ncurses_timeout — Set timeout for special key sequences
  • ncurses_top_panel — Moves a visible panel to the top of the stack
  • ncurses_typeahead — Specify different filedescriptor for typeahead checking
  • ncurses_ungetch — Put a character back into the input stream
  • ncurses_ungetmouse — Pushes mouse event to queue
  • ncurses_update_panels — Refreshes the virtual screen to reflect the relations between panels in the stack
  • ncurses_use_default_colors — Assign terminal default colors to color id -1
  • ncurses_use_env — Control use of environment information about terminal size
  • ncurses_use_extended_names — Control use of extended names in terminfo descriptions
  • ncurses_vidattr — Display the string on the terminal in the video attribute mode
  • ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long
  • ncurses_waddch — Adds character at current position in a window and advance cursor
  • ncurses_waddstr — Outputs text at current postion in window
  • ncurses_wattroff — Turns off attributes for a window
  • ncurses_wattron — Turns on attributes for a window
  • ncurses_wattrset — Set the attributes for a window
  • ncurses_wborder — Draws a border around the window using attributed characters
  • ncurses_wclear — Clears window
  • ncurses_wcolor_set — Sets windows color pairings
  • ncurses_werase — Erase window contents
  • ncurses_wgetch — Reads a character from keyboard (window)
  • ncurses_whline — Draws a horizontal line in a window at current position using an attributed character and max. n characters long
  • ncurses_wmouse_trafo — Transforms window/stdscr coordinates
  • ncurses_wmove — Moves windows output position
  • ncurses_wnoutrefresh — Copies window to virtual screen
  • ncurses_wrefresh — Refresh window on terminal screen
  • ncurses_wstandend — End standout mode for a window
  • ncurses_wstandout — Enter standout mode for a window
  • ncurses_wvline — Draws a vertical line in a window at current position using an attributed character and max. n characters long
Mouse
ncurses_addch
Ncurses


Newt Functions

Table of Contents

  • newt_bell — Send a beep to the terminal
  • newt_button_bar — This function returns a grid containing the buttons created.
  • newt_button — Create a new button
  • newt_centered_window — Open a centered window of the specified size
  • newt_checkbox_get_value — Retreives value of checkox resource
  • newt_checkbox_set_flags — Configures checkbox resource
  • newt_checkbox_set_value — Sets the value of the checkbox
  • newt_checkbox_tree_add_item — Adds new item to the checkbox tree
  • newt_checkbox_tree_find_item — Finds an item in the checkbox tree
  • newt_checkbox_tree_get_current — Returns checkbox tree selected item
  • newt_checkbox_tree_get_entry_value — Description
  • newt_checkbox_tree_get_multi_selection — Description
  • newt_checkbox_tree_get_selection — Description
  • newt_checkbox_tree_multi — Description
  • newt_checkbox_tree_set_current — Description
  • newt_checkbox_tree_set_entry_value — Description
  • newt_checkbox_tree_set_entry — Description
  • newt_checkbox_tree_set_width — Description
  • newt_checkbox_tree — Description
  • newt_checkbox — Description
  • newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
  • newt_cls — Description
  • newt_compact_button — Description
  • newt_component_add_callback — Description
  • newt_component_takes_focus — Description
  • newt_create_grid — Description
  • newt_cursor_off — Description
  • newt_cursor_on — Description
  • newt_delay — Description
  • newt_draw_form — Description
  • newt_draw_root_text — Displays the string text at the position indicated
  • newt_entry_get_value — Description
  • newt_entry_set_filter — Description
  • newt_entry_set_flags — Description
  • newt_entry_set — Description
  • newt_entry — Description
  • newt_finished — Uninitializes newt interface
  • newt_form_add_component — Adds a single component to the form
  • newt_form_add_components — Add several components to the form
  • newt_form_add_hot_key — Description
  • newt_form_destroy — Destroys a form
  • newt_form_get_current — Description
  • newt_form_run — Runs a form
  • newt_form_set_background — Description
  • newt_form_set_height — Description
  • newt_form_set_size — Description
  • newt_form_set_timer — Description
  • newt_form_set_width — Description
  • newt_form_watch_fd — Description
  • newt_form — Create a form
  • newt_get_screen_size — Fills in the passed references with the current size of the terminal
  • newt_grid_add_components_to_form — Description
  • newt_grid_basic_window — Description
  • newt_grid_free — Description
  • newt_grid_get_size — Description
  • newt_grid_h_close_stacked — Description
  • newt_grid_h_stacked — Description
  • newt_grid_place — Description
  • newt_grid_set_field — Description
  • newt_grid_simple_window — Description
  • newt_grid_v_close_stacked — Description
  • newt_grid_v_stacked — Description
  • newt_grid_wrapped_window_at — Description
  • newt_grid_wrapped_window — Description
  • newt_init — Initialize newt
  • newt_label_set_text — Description
  • newt_label — Description
  • newt_listbox_append_entry — Description
  • newt_listbox_clear_selection — Description
  • newt_listbox_clear — Description
  • newt_listbox_delete_entry — Description
  • newt_listbox_get_current — Description
  • newt_listbox_get_selection — Description
  • newt_listbox_insert_entry — Description
  • newt_listbox_item_count — Description
  • newt_listbox_select_item — Description
  • newt_listbox_set_current_by_key — Description
  • newt_listbox_set_current — Description
  • newt_listbox_set_data — Description
  • newt_listbox_set_entry — Description
  • newt_listbox_set_width — Description
  • newt_listbox — Description
  • newt_listitem_get_data — Description
  • newt_listitem_set — Description
  • newt_listitem — Description
  • newt_open_window — Open a window of the specified size and position
  • newt_pop_help_line — Replaces the current help line with the one from the stack
  • newt_pop_window — Removes the top window from the display
  • newt_push_help_line — Saves the current help line on a stack, and displays the new line
  • newt_radio_get_current — Description
  • newt_radiobutton — Description
  • newt_redraw_help_line — Description
  • newt_reflow_text — Description
  • newt_refresh — Updates modified portions of the screen
  • newt_resize_screen — Description
  • newt_resume — Resume using the newt interface after calling newt_suspend
  • newt_run_form — Runs a form
  • newt_scale_set — Description
  • newt_scale — Description
  • newt_scrollbar_set — Description
  • newt_set_help_callback — Description
  • newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key
  • newt_suspend — Tells newt to return the terminal to its initial state
  • newt_textbox_get_num_lines — Description
  • newt_textbox_reflowed — Description
  • newt_textbox_set_height — Description
  • newt_textbox_set_text — Description
  • newt_textbox — Description
  • newt_vertical_scrollbar — Description
  • newt_wait_for_key — Doesn't return until a key has been pressed
  • newt_win_choice — Description
  • newt_win_entries — Description
  • newt_win_menu — Description
  • newt_win_message — Description
  • newt_win_messagev — Description
  • newt_win_ternary — Description
Basic usage
newt_bell
Newt


OCI8 Functions

Table of Contents

  • oci_bind_array_by_name — Binds PHP array to Oracle PL/SQL array by name
  • oci_bind_by_name — Binds a PHP variable to an Oracle placeholder
  • oci_cancel — Cancels reading from cursor
  • oci_close — Closes an Oracle connection
  • OCI-Collection->append — Appends element to the collection
  • OCI-Collection->assign — Assigns a value to the collection from another existing collection
  • OCI-Collection->assignElem — Assigns a value to the element of the collection
  • OCI-Collection->free — Frees the resources associated with the collection object
  • OCI-Collection->getElem — Returns value of the element
  • OCI-Collection->max — Returns the maximum number of elements in the collection
  • OCI-Collection->size — Returns size of the collection
  • OCI-Collection->trim — Trims elements from the end of the collection
  • oci_commit — Commits the outstanding database transaction
  • oci_connect — Connect to an Oracle database
  • oci_define_by_name — Associates a PHP variable with a column for query fetches
  • oci_error — Returns the last error found
  • oci_execute — Executes a statement
  • oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array — Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc — Returns the next row from a query as an associative array
  • oci_fetch_object — Returns the next row from a query as an object
  • oci_fetch_row — Returns the next row from a query as a numeric array
  • oci_fetch — Fetches the next row from a query into internal buffers
  • oci_field_is_null — Checks if the field is NULL
  • oci_field_name — Returns the name of a field from the statement
  • oci_field_precision — Tell the precision of a field
  • oci_field_scale — Tell the scale of the field
  • oci_field_size — Returns field's size
  • oci_field_type_raw — Tell the raw Oracle data type of the field
  • oci_field_type — Returns field's data type
  • oci_free_statement — Frees all resources associated with statement or cursor
  • oci_internal_debug — Enables or disables internal debug output
  • OCI-Lob->append — Appends data from the large object to another large object
  • OCI-Lob->close — Closes LOB descriptor
  • oci_lob_copy — Copies large object
  • OCI-Lob->eof — Tests for end-of-file on a large object's descriptor
  • OCI-Lob->erase — Erases a specified portion of the internal LOB data
  • OCI-Lob->export — Exports LOB's contents to a file
  • OCI-Lob->flush — Flushes/writes buffer of the LOB to the server
  • OCI-Lob->free — Frees resources associated with the LOB descriptor
  • OCI-Lob->getBuffering — Returns current state of buffering for the large object
  • OCI-Lob->import — Imports file data to the LOB
  • oci_lob_is_equal — Compares two LOB/FILE locators for equality
  • OCI-Lob->load — Returns large object's contents
  • OCI-Lob->read — Reads part of the large object
  • OCI-Lob->rewind — Moves the internal pointer to the beginning of the large object
  • OCI-Lob->save — Saves data to the large object
  • OCI-Lob->saveFile — Alias of oci_lob_import
  • OCI-Lob->seek — Sets the internal pointer of the large object
  • OCI-Lob->setBuffering — Changes current state of buffering for the large object
  • OCI-Lob->size — Returns size of large object
  • OCI-Lob->tell — Returns current position of internal pointer of large object
  • OCI-Lob->truncate — Truncates large object
  • OCI-Lob->write — Writes data to the large object
  • OCI-Lob->writeTemporary — Writes temporary large object
  • OCI-Lob->writeToFile — Alias of oci_lob_export
  • oci_new_collection — Allocates new collection object
  • oci_new_connect — Connect to the Oracle server using a unique connection
  • oci_new_cursor — Allocates and returns a new cursor (statement handle)
  • oci_new_descriptor — Initializes a new empty LOB or FILE descriptor
  • oci_num_fields — Returns the number of result columns in a statement
  • oci_num_rows — Returns number of rows affected during statement execution
  • oci_parse — Prepares an Oracle statement for execution
  • oci_password_change — Changes password of Oracle's user
  • oci_pconnect — Connect to an Oracle database using a persistent connection
  • oci_result — Returns field's value from the fetched row
  • oci_rollback — Rolls back the outstanding database transaction
  • oci_server_version — Returns server version
  • oci_set_action — Sets the action name
  • oci_set_client_identifier — Sets the client identifier
  • oci_set_client_info — Sets the client information
  • oci_set_edition — Sets the database edition
  • oci_set_module_name — Sets the module name
  • oci_set_prefetch — Sets number of rows to be prefetched by queries
  • oci_statement_type — Returns the type of a statement
Supported Datatypes
oci_bind_array_by_name
OCI8


OpenAL Functions

Table of Contents

  • openal_buffer_create — Generate OpenAL buffer
  • openal_buffer_data — Load a buffer with data
  • openal_buffer_destroy — Destroys an OpenAL buffer
  • openal_buffer_get — Retrieve an OpenAL buffer property
  • openal_buffer_loadwav — Load a .wav file into a buffer
  • openal_context_create — Create an audio processing context
  • openal_context_current — Make the specified context current
  • openal_context_destroy — Destroys a context
  • openal_context_process — Process the specified context
  • openal_context_suspend — Suspend the specified context
  • openal_device_close — Close an OpenAL device
  • openal_device_open — Initialize the OpenAL audio layer
  • openal_listener_get — Retrieve a listener property
  • openal_listener_set — Set a listener property
  • openal_source_create — Generate a source resource
  • openal_source_destroy — Destroy a source resource
  • openal_source_get — Retrieve an OpenAL source property
  • openal_source_pause — Pause the source
  • openal_source_play — Start playing the source
  • openal_source_rewind — Rewind the source
  • openal_source_set — Set source property
  • openal_source_stop — Stop playing the source
  • openal_stream — Begin streaming on a source
Predefined Constants
openal_buffer_create
OpenAL


OpenSSL Functions

Table of Contents

  • openssl_csr_export_to_file — Exports a CSR to a file
  • openssl_csr_export — Exports a CSR as a string
  • openssl_csr_get_public_key — Returns the public key of a CERT
  • openssl_csr_get_subject — Returns the subject of a CERT
  • openssl_csr_new — Generates a CSR
  • openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate
  • openssl_decrypt — Decrypts data
  • openssl_dh_compute_key — Computes shared secret for public value of remote DH key and local DH key
  • openssl_digest — Computes a digest
  • openssl_encrypt — Encrypts data
  • openssl_error_string — Return openSSL error message
  • openssl_free_key — Free key resource
  • openssl_get_cipher_methods — Gets available cipher methods
  • openssl_get_md_methods — Gets available digest methods
  • openssl_get_privatekey — Alias of openssl_pkey_get_private
  • openssl_get_publickey — Alias of openssl_pkey_get_public
  • openssl_open — Open sealed data
  • openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
  • openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.
  • openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array
  • openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message
  • openssl_pkcs7_encrypt — Encrypt an S/MIME message
  • openssl_pkcs7_sign — Sign an S/MIME message
  • openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message
  • openssl_pkey_export_to_file — Gets an exportable representation of a key into a file
  • openssl_pkey_export — Gets an exportable representation of a key into a string
  • openssl_pkey_free — Frees a private key
  • openssl_pkey_get_details — Returns an array with the key details
  • openssl_pkey_get_private — Get a private key
  • openssl_pkey_get_public — Extract public key from certificate and prepare it for use
  • openssl_pkey_new — Generates a new private key
  • openssl_private_decrypt — Decrypts data with private key
  • openssl_private_encrypt — Encrypts data with private key
  • openssl_public_decrypt — Decrypts data with public key
  • openssl_public_encrypt — Encrypts data with public key
  • openssl_random_pseudo_bytes — Generate a pseudo-random string
  • openssl_seal — Seal (encrypt) data
  • openssl_sign — Generate signature
  • openssl_verify — Verify signature
  • openssl_x509_check_private_key — Checks if a private key corresponds to a certificate
  • openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose
  • openssl_x509_export_to_file — Exports a certificate to file
  • openssl_x509_export — Exports a certificate as a string
  • openssl_x509_free — Free certificate resource
  • openssl_x509_parse — Parse an X509 certificate and return the information as an array
  • openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it
Certificate Verification
openssl_csr_export_to_file
OpenSSL


Output Control Functions

See Also

See also header() and setcookie().

Table of Contents

  • flush — Flush the output buffer
  • ob_clean — Clean (erase) the output buffer
  • ob_end_clean — Clean (erase) the output buffer and turn off output buffering
  • ob_end_flush — Flush (send) the output buffer and turn off output buffering
  • ob_flush — Flush (send) the output buffer
  • ob_get_clean — Get current buffer contents and delete current output buffer
  • ob_get_contents — Return the contents of the output buffer
  • ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering
  • ob_get_length — Return the length of the output buffer
  • ob_get_level — Return the nesting level of the output buffering mechanism
  • ob_get_status — Get status of output buffers
  • ob_gzhandler — ob_start callback function to gzip output buffer
  • ob_implicit_flush — Turn implicit flush on/off
  • ob_list_handlers — List all output handlers in use
  • ob_start — Turn on output buffering
  • output_add_rewrite_var — Add URL rewriter values
  • output_reset_rewrite_vars — Reset URL rewriter values
Examples
flush
Output Control


Object overloading Functions

Table of Contents

  • overload — Enable property and method call overloading for a class
Overloading a PHP class
overload
Object overloading


Ovrimos SQL Functions

Table of Contents

  • ovrimos_close — Closes the connection to ovrimos
  • ovrimos_commit — Commits the transaction
  • ovrimos_connect — Connect to the specified database
  • ovrimos_cursor — Returns the name of the cursor
  • ovrimos_exec — Executes an SQL statement
  • ovrimos_execute — Executes a prepared SQL statement
  • ovrimos_fetch_into — Fetches a row from the result set
  • ovrimos_fetch_row — Fetches a row from the result set
  • ovrimos_field_len — Returns the length of the output column
  • ovrimos_field_name — Returns the output column name
  • ovrimos_field_num — Returns the (1-based) index of the output column
  • ovrimos_field_type — Returns the type of the output column
  • ovrimos_free_result — Frees the specified result_id
  • ovrimos_longreadlen — Specifies how many bytes are to be retrieved from long datatypes
  • ovrimos_num_fields — Returns the number of columns
  • ovrimos_num_rows — Returns the number of rows affected by update operations
  • ovrimos_prepare — Prepares an SQL statement
  • ovrimos_result_all — Prints the whole result set as an HTML table
  • ovrimos_result — Retrieves the output column
  • ovrimos_rollback — Rolls back the transaction
Connect to Ovrimos SQL Server and select from a system table
ovrimos_close
Ovrimos SQL


Paradox Functions

Object oriented API

The paradox extension provides also an object oriented API. It consists of only one class called paradox_db. Its methods only differ from the functions in its name and of course the missing first parameter. The following table will list all methods and its equivalent functions.

Methods of class paradox_db
Name of method | Equivalent function
Constructor | px_new()
Destructor | px_delete()
open_fp() | px_open_fp()
create_fp() | px_create_fp()
close() | px_close()
numrecords() | px_numrecords()
numfields() | px_numfields()
get_record() | px_get_record()
put_record() | px_put_record()
retrieve_record() | px_retrieve_record()
delete_record() | px_delete_record()
insert_record() | px_insert_record()
update_record() | px_update_record()
get_field() | px_get_field()
get_schema() | px_get_schema()
get_info() | px_get_info()
set_parameter() | px_set_parameter()
get_parameter() | px_get_parameter()
set_value() | px_set_value()
get_value() | px_get_value()
get_info() | px_get_info()
set_targetencoding() | px_set_targetencoding()
set_tablename() | px_set_tablename()
set_blob_file() | px_set_blob_file()
date2string() | px_date2string()
timestamp2string() | px_timestamp2string()

Table of Contents

  • px_close — Closes a paradox database
  • px_create_fp — Create a new paradox database
  • px_date2string — Converts a date into a string.
  • px_delete_record — Deletes record from paradox database
  • px_delete — Deletes resource of paradox database
  • px_get_field — Returns the specification of a single field
  • px_get_info — Return lots of information about a paradox file
  • px_get_parameter — Gets a parameter
  • px_get_record — Returns record of paradox database
  • px_get_schema — Returns the database schema
  • px_get_value — Gets a value
  • px_insert_record — Inserts record into paradox database
  • px_new — Create a new paradox object
  • px_numfields — Returns number of fields in a database
  • px_numrecords — Returns number of records in a database
  • px_open_fp — Open paradox database
  • px_put_record — Stores record into paradox database
  • px_retrieve_record — Returns record of paradox database
  • px_set_blob_file — Sets the file where blobs are read from
  • px_set_parameter — Sets a parameter
  • px_set_tablename — Sets the name of a table (deprecated)
  • px_set_targetencoding — Sets the encoding for character fields (deprecated)
  • px_set_value — Sets a value
  • px_timestamp2string — Converts the timestamp into a string.
  • px_update_record — Updates record in paradox database
Predefined Constants
px_close
Paradox


Parsekit Functions

Table of Contents

  • parsekit_compile_file — Compile a string of PHP code and return the resulting op array
  • parsekit_compile_string — Compile a string of PHP code and return the resulting op array
  • parsekit_func_arginfo — Return information regarding function argument(s)
Predefined Constants
parsekit_compile_file
Parsekit


PCNTL Functions

See Also

A look at the section about POSIX functions may be useful.

Table of Contents

  • pcntl_alarm — Set an alarm clock for delivery of a signal
  • pcntl_exec — Executes specified program in current process space
  • pcntl_fork — Forks the currently running process
  • pcntl_getpriority — Get the priority of any process
  • pcntl_setpriority — Change the priority of any process
  • pcntl_signal_dispatch — Calls signal handlers for pending signals
  • pcntl_signal — Installs a signal handler
  • pcntl_sigprocmask — Sets and retrieves blocked signals
  • pcntl_sigtimedwait — Waits for signals, with a timeout
  • pcntl_sigwaitinfo — Waits for signals
  • pcntl_wait — Waits on or returns the status of a forked child
  • pcntl_waitpid — Waits on or returns the status of a forked child
  • pcntl_wexitstatus — Returns the return code of a terminated child
  • pcntl_wifexited — Checks if status code represents a normal exit
  • pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal
  • pcntl_wifstopped — Checks whether the child process is currently stopped
  • pcntl_wstopsig — Returns the signal which caused the child to stop
  • pcntl_wtermsig — Returns the signal which caused the child to terminate
Process Control Example
pcntl_alarm
PCNTL


PDF Functions

Remarks about Deprecated PDFlib Functions

Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib Reference Manual are supported by PHP 4 with exactly the same meaning and the same parameters. However, with PDFlib Version 5.0.4 or higher all parameters have to be specified. For compatibility reasons, this binding for PDFlib still supports most of the deprecated functions, but they should be replaced by their new versions. PDFlib GmbH will not support any problems arising from the use of these deprecated functions. The documentation in this section indicates old functions as "Deprecated" and gives the replacement function to be used instead.

Table of Contents

  • PDF_activate_item — Activate structure element or other content item
  • PDF_add_annotation — Add annotation [deprecated]
  • PDF_add_bookmark — Add bookmark for current page [deprecated]
  • PDF_add_launchlink — Add launch annotation for current page [deprecated]
  • PDF_add_locallink — Add link annotation for current page [deprecated]
  • PDF_add_nameddest — Create named destination
  • PDF_add_note — Set annotation for current page [deprecated]
  • PDF_add_outline — Add bookmark for current page [deprecated]
  • PDF_add_pdflink — Add file link annotation for current page [deprecated]
  • PDF_add_table_cell — Add a cell to a new or existing table
  • PDF_add_textflow — Create Textflow or add text to existing Textflow
  • PDF_add_thumbnail — Add thumbnail for current page
  • PDF_add_weblink — Add weblink for current page [deprecated]
  • PDF_arc — Draw a counterclockwise circular arc segment
  • PDF_arcn — Draw a clockwise circular arc segment
  • PDF_attach_file — Add file attachment for current page [deprecated]
  • PDF_begin_document — Create new PDF file
  • PDF_begin_font — Start a Type 3 font definition
  • PDF_begin_glyph — Start glyph definition for Type 3 font
  • PDF_begin_item — Open structure element or other content item
  • PDF_begin_layer — Start layer
  • PDF_begin_page_ext — Start new page
  • PDF_begin_page — Start new page [deprecated]
  • PDF_begin_pattern — Start pattern definition
  • PDF_begin_template_ext — Start template definition
  • PDF_begin_template — Start template definition [deprecated]
  • PDF_circle — Draw a circle
  • PDF_clip — Clip to current path
  • PDF_close_image — Close image
  • PDF_close_pdi_page — Close the page handle
  • PDF_close_pdi — Close the input PDF document [deprecated]
  • PDF_close — Close pdf resource [deprecated]
  • PDF_closepath_fill_stroke — Close, fill and stroke current path
  • PDF_closepath_stroke — Close and stroke path
  • PDF_closepath — Close current path
  • PDF_concat — Concatenate a matrix to the CTM
  • PDF_continue_text — Output text in next line
  • PDF_create_3dview — Create 3D view
  • PDF_create_action — Create action for objects or events
  • PDF_create_annotation — Create rectangular annotation
  • PDF_create_bookmark — Create bookmark
  • PDF_create_field — Create form field
  • PDF_create_fieldgroup — Create form field group
  • PDF_create_gstate — Create graphics state object
  • PDF_create_pvf — Create PDFlib virtual file
  • PDF_create_textflow — Create textflow object
  • PDF_curveto — Draw Bezier curve
  • PDF_define_layer — Create layer definition
  • PDF_delete_pvf — Delete PDFlib virtual file
  • PDF_delete_table — Delete table object
  • PDF_delete_textflow — Delete textflow object
  • PDF_delete — Delete PDFlib object
  • PDF_encoding_set_char — Add glyph name and/or Unicode value
  • PDF_end_document — Close PDF file
  • PDF_end_font — Terminate Type 3 font definition
  • PDF_end_glyph — Terminate glyph definition for Type 3 font
  • PDF_end_item — Close structure element or other content item
  • PDF_end_layer — Deactivate all active layers
  • PDF_end_page_ext — Finish page
  • PDF_end_page — Finish page
  • PDF_end_pattern — Finish pattern
  • PDF_end_template — Finish template
  • PDF_endpath — End current path
  • PDF_fill_imageblock — Fill image block with variable data
  • PDF_fill_pdfblock — Fill PDF block with variable data
  • PDF_fill_stroke — Fill and stroke path
  • PDF_fill_textblock — Fill text block with variable data
  • PDF_fill — Fill current path
  • PDF_findfont — Prepare font for later use [deprecated]
  • PDF_fit_image — Place image or template
  • PDF_fit_pdi_page — Place imported PDF page
  • PDF_fit_table — Place table on page
  • PDF_fit_textflow — Format textflow in rectangular area
  • PDF_fit_textline — Place single line of text
  • PDF_get_apiname — Get name of unsuccessfull API function
  • PDF_get_buffer — Get PDF output buffer
  • PDF_get_errmsg — Get error text
  • PDF_get_errnum — Get error number
  • PDF_get_font — Get font [deprecated]
  • PDF_get_fontname — Get font name [deprecated]
  • PDF_get_fontsize — Font handling [deprecated]
  • PDF_get_image_height — Get image height [deprecated]
  • PDF_get_image_width — Get image width [deprecated]
  • PDF_get_majorversion — Get major version number [deprecated]
  • PDF_get_minorversion — Get minor version number [deprecated]
  • PDF_get_parameter — Get string parameter
  • PDF_get_pdi_parameter — Get PDI string parameter [deprecated]
  • PDF_get_pdi_value — Get PDI numerical parameter [deprecated]
  • PDF_get_value — Get numerical parameter
  • PDF_info_font — Query detailed information about a loaded font
  • PDF_info_matchbox — Query matchbox information
  • PDF_info_table — Retrieve table information
  • PDF_info_textflow — Query textflow state
  • PDF_info_textline — Perform textline formatting and query metrics
  • PDF_initgraphics — Reset graphic state
  • PDF_lineto — Draw a line
  • PDF_load_3ddata — Load 3D model
  • PDF_load_font — Search and prepare font
  • PDF_load_iccprofile — Search and prepare ICC profile
  • PDF_load_image — Open image file
  • PDF_makespotcolor — Make spot color
  • PDF_moveto — Set current point
  • PDF_new — Create PDFlib object
  • PDF_open_ccitt — Open raw CCITT image [deprecated]
  • PDF_open_file — Create PDF file [deprecated]
  • PDF_open_gif — Open GIF image [deprecated]
  • PDF_open_image_file — Read image from file [deprecated]
  • PDF_open_image — Use image data [deprecated]
  • PDF_open_jpeg — Open JPEG image [deprecated]
  • PDF_open_memory_image — Open image created with PHP's image functions [not supported]
  • PDF_open_pdi_page — Prepare a page
  • PDF_open_pdi — Open PDF file [deprecated]
  • PDF_open_tiff — Open TIFF image [deprecated]
  • PDF_pcos_get_number — Get value of pCOS path with type number or boolean
  • PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string
  • PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean
  • PDF_place_image — Place image on the page [deprecated]
  • PDF_place_pdi_page — Place PDF page [deprecated]
  • PDF_process_pdi — Process imported PDF document
  • PDF_rect — Draw rectangle
  • PDF_restore — Restore graphics state
  • PDF_resume_page — Resume page
  • PDF_rotate — Rotate coordinate system
  • PDF_save — Save graphics state
  • PDF_scale — Scale coordinate system
  • PDF_set_border_color — Set border color of annotations [deprecated]
  • PDF_set_border_dash — Set border dash style of annotations [deprecated]
  • PDF_set_border_style — Set border style of annotations [deprecated]
  • PDF_set_char_spacing — Set character spacing [deprecated]
  • PDF_set_duration — Set duration between pages [deprecated]
  • PDF_set_gstate — Activate graphics state object
  • PDF_set_horiz_scaling — Set horizontal text scaling [deprecated]
  • PDF_set_info_author — Fill the author document info field [deprecated]
  • PDF_set_info_creator — Fill the creator document info field [deprecated]
  • PDF_set_info_keywords — Fill the keywords document info field [deprecated]
  • PDF_set_info_subject — Fill the subject document info field [deprecated]
  • PDF_set_info_title — Fill the title document info field [deprecated]
  • PDF_set_info — Fill document info field
  • PDF_set_layer_dependency — Define relationships among layers
  • PDF_set_leading — Set distance between text lines [deprecated]
  • PDF_set_parameter — Set string parameter
  • PDF_set_text_matrix — Set text matrix [deprecated]
  • PDF_set_text_pos — Set text position
  • PDF_set_text_rendering — Determine text rendering [deprecated]
  • PDF_set_text_rise — Set text rise [deprecated]
  • PDF_set_value — Set numerical parameter
  • PDF_set_word_spacing — Set spacing between words [deprecated]
  • PDF_setcolor — Set fill and stroke color
  • PDF_setdash — Set simple dash pattern
  • PDF_setdashpattern — Set dash pattern
  • PDF_setflat — Set flatness
  • PDF_setfont — Set font
  • PDF_setgray_fill — Set fill color to gray [deprecated]
  • PDF_setgray_stroke — Set stroke color to gray [deprecated]
  • PDF_setgray — Set color to gray [deprecated]
  • PDF_setlinecap — Set linecap parameter
  • PDF_setlinejoin — Set linejoin parameter
  • PDF_setlinewidth — Set line width
  • PDF_setmatrix — Set current transformation matrix
  • PDF_setmiterlimit — Set miter limit
  • PDF_setpolydash — Set complicated dash pattern [deprecated]
  • PDF_setrgbcolor_fill — Set fill rgb color values [deprecated]
  • PDF_setrgbcolor_stroke — Set stroke rgb color values [deprecated]
  • PDF_setrgbcolor — Set fill and stroke rgb color values [deprecated]
  • PDF_shading_pattern — Define shading pattern
  • PDF_shading — Define blend
  • PDF_shfill — Fill area with shading
  • PDF_show_boxed — Output text in a box [deprecated]
  • PDF_show_xy — Output text at given position
  • PDF_show — Output text at current position
  • PDF_skew — Skew the coordinate system
  • PDF_stringwidth — Return width of text
  • PDF_stroke — Stroke path
  • PDF_suspend_page — Suspend page
  • PDF_translate — Set origin of coordinate system
  • PDF_utf16_to_utf8 — Convert string from UTF-16 to UTF-8
  • PDF_utf32_to_utf16 — Convert string from UTF-32 to UTF-16
  • PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16
Basic Usage Examples
PDF_activate_item
PDF


Driver 4D for PDO (PDO_4D)

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

PDO_4D is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to 4D databases.

4D is an integrated platform that speeds and simplifies the development and deployment of business applications, used in over 70 countries, by a community of thousands of developers and vertical solution providers, with millions of end-users worldwide.

By offering a suite of integrated tools such as an ANSI SQL relational and transactional database, a graphical development environment, a fourth-generation language with over 1000 high-level commands, a built-in HTTP server, application server, etc., 4D facilitates the creation and maintenance of applications from one to hundreds of simultaneous users, whether on Windows, Mac or from any Web client.

4D is also an open platform, offering a complete API for plug-in creation, including various connectors that allow it to act as a back-end or front-end for many environments (Oracle via OCI, SOAP client or server, Flex data source, all ODBC databases, XML over HTTP, etc.)

In addition to the ability to interact with 4D applications across Web Services, 4D databases can now be directly accessed using the PDO_4D driver.

More details about the 4D development environment on » http://www.4d.fr/.

PDO_4D has been developed to work on Windows (Vista), Mac OS X (10.5) and Linux (Debian-tested). It is known to work with 4D versions 11.4 and up, for Mac OS X and Windows. Older plat-forms may work, but are unsupported.

Table of Contents

  • PDO_4D DSN — Connecting to 4D SQL server
  • Constants for PDO_4D — Constants for PDO_4D
  • SQL types with PDO_4D and PHP — SQL types with PDO_4D and PHP
  • SQL acceptable by 4D — PDO and SQL 4D
  • Examples with PDO_4D — Examples PDO_4D
PDO::sqliteCreateFunction
PDO_4D DSN
PDO Drivers


Connecting to 4D SQL server

Driver 4D for PDO
Constants for PDO_4D
Driver 4D for PDO
PHP Manual

PDO_4D DSN

(No version information available, might only be in SVN)

PDO_4D DSN — Connecting to 4D SQL server

Description

The PDO_4D DSN consists of:

DSN prefix

The DSN prefix is 4D: .

host

The host on which the 4D SQL server is.

port

The port number for the server. This is optional.

user

The login name when connecting to the database.

password

The password for the above login.

dbname

The name of the database. This parameter is optional, and it is not used.

charset

The 4D character set.

Examples

Example #1 DSN examples for PDO_4D

The following examples has two DSN for PDO_4D, that connects to a 4D database :

4D:host=localhost;charset=UTF-8

Other possible values :

4D:host=localhost

Driver 4D for PDO
Constants for PDO_4D
Driver 4D for PDO


PDO and SQL 4D

SQL types with PDO_4D and PHP
Examples with PDO_4D
Driver 4D for PDO
PHP Manual

SQL acceptable by 4D

(No version information available, might only be in SVN)

SQL acceptable by 4D — PDO and SQL 4D

Description

4D implements strictly the ANSI 89 standard, and have it enforced. It is highly recommended to read the 4D SQL documentation to learn about the available commands. The URL of the manual is : » http://www.4d.fr/support/docs.html. Below is a list of 4D SQL characteristics: it is not exhaustive, but may serve as an introduction.

Characteristics of 4D SQL
Characteristics | Alternative | Note
INTEGER | INT is the supported integer type. Modify the SQL to use INT. |
UNION | Unsupported. Make separate queries. |
LEFT JOIN | Use the SQL 89 notation |
SELECT 1 + 1; | SELECT 1 + 1 FROM _USER_SCHEMAS; |
FLOAT | Cast the FLOAT value with a SQL 4D function (ROUND, TRUNC or TRUNCATE) | Unsupported in the driver PDO_4D v1.0
Strong typing : one must provide the right type that 4D expect. One can't insert '1' (as a string) in an INTEGER column. | Modify your SQL query, or your PHP to adapt the type | Unsupported
PDO::execute($row)() | Use the prepared statements, and use the right types. It will also only works if all the table's column are of type TEXT. | The PDO extension cast all values through execute() as string, and expect the SQL database to parse the values.
SELECT NULL FROM TABLE | It is not allowed to use the NULL constante in the select list | Do not use NULL constants. Extract them from the table
SELECT * FROM TABLE WHERE 1 | A constant can't be used in a WHERE clause. | Use 1 = 1
SHOW TABLES | The list of tables, schemas, index, etc. are in 7 4D tables | Use _USER_TABLES, _USER_COLUMNS, _USER_INDEXES, _USER_CONSTRAINTS, _USER_IND_COLUMNS, _USER_CONS_COLUMNS, and _USER_SCHEMAS.
SQL structure delimiter | To escape SQL elements (tables, fields, users, groups, schema, primary key, etc.), closing brackets must be doubled, and the whole identifier must be between square brackets. | Use the following function to protect SQL objects, and then, put it between square brackets : str_replace(']',']]', $table).

Note: In version 11.3 and below, it wasn't possible to use the SQL syntax id INT PRIMARY KEY during the creation of a table. This have been fixed in 4D 11.4 and up. It is recommended to use at least version 11.4 with PDO_4D.

SQL types with PDO_4D and PHP
Examples with PDO_4D
Driver 4D for PDO


Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

PDO_DBLIB is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Microsoft SQL Server and Sybase databases through the FreeTDS libary.

On Windows, you should use the PDO_ODBC driver to connect to Microsoft SQL Server and Sybase databases, as the native Windows DB-LIB is ancient, thread un-safe and no longer supported by Microsoft.

Table of Contents

  • PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases
PDO Drivers
PDO_DBLIB DSN
PDO Drivers


Connecting to Microsoft SQL Server and Sybase databases

MS SQL Server (PDO)
Firebird/Interbase (PDO)
MS SQL Server (PDO)
PHP Manual

PDO_DBLIB DSN

(PECL PDO_DBLIB >= 0.9.0)

PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases

Description

The PDO_DBLIB Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is sybase: if PDO_DBLIB was linked against the FreeTDS libraries, mssql: if PDO_DBLIB was linked against the Microsoft SQL Server libraries, or dblib: if linked against any other variety of DB-lib.

host

The hostname on which the database server resides. Defaults to 127.0.0.1.

dbname

The name of the database.

charset

The client character set.

appname

The application name (used in sysprocesses). Defaults to "PHP Generic DB-lib" or "PHP freetds".

secure

Currently unused.

Examples

Example #1 PDO_DBLIB DSN examples

The following examples show a PDO_DBLIB DSN for connecting to Microsoft SQL Server and Sybase databases:

mssql:host=localhost;dbname=testdb
sybase:host=localhost;dbname=testdb
dblib:host=localhost;dbname=testdb

MS SQL Server (PDO)
Firebird/Interbase (PDO)
MS SQL Server (PDO)


Firebird/Interbase Functions (PDO_FIREBIRD)

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

PDO_FIREBIRD is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Firebird and Interbase databases.

Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver, if your code can run against multiple drivers.

PDO::FB_ATTR_DATE_FORMAT (integer)

Available since PHP 5.3.0.

Sets the date format.

PDO::FB_ATTR_TIME_FORMAT (integer)

Sets the time format.

Available since PHP 5.3.0.

PDO::FB_ATTR_TIMESTAMP_FORMAT (integer)

Sets the timestamp format.

Available since PHP 5.3.0.

Table of Contents

  • PDO_FIREBIRD DSN — Connecting to Firebird and Interbase databases
PDO_DBLIB DSN
PDO_FIREBIRD DSN
PDO Drivers


Connecting to Firebird and Interbase databases

Firebird/Interbase (PDO)
IBM (PDO)
Firebird/Interbase (PDO)
PHP Manual

PDO_FIREBIRD DSN

(PECL PDO_FIREBIRD >= 0.1.0)

PDO_FIREBIRD DSN — Connecting to Firebird and Interbase databases

Description

The PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is firebird: .

dbname

The name of the database.

charset

The character set.

role

The SQL role name.

Examples

Example #1 PDO_FIREBIRD DSN examples

The following example shows a PDO_FIREBIRD DSN for connecting to Firebird and Interbase databases:

firebird:dbname=DATABASE.GDE

Firebird/Interbase (PDO)
IBM (PDO)
Firebird/Interbase (PDO)


IBM Functions (PDO_IBM)

Introduction

PDO_IBM is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to IBM databases.

Installation

To build the PDO_IBM extension, the DB2 Client v9.1 or later must be installed on the same system as PHP. The DB2 Client can be downloaded from the IBM » Application Development Site.

Note: Note
The DB2 Client v9.1 or later supports direct access to DB2 for Linux, UNIX, and Windows v8 and v9.1 servers.
The DB2 Client v9.1 also supports access to DB2 UDB for i5 and DB2 UDB for z/OS servers using the separately purchased » DB2 Connect product.

PDO_IBM is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the PDO_IBM extension. Issue the configure command to point to the location of your DB2 Client header files and libraries as follows:

bash$ ./configure --with-pdo-ibm=/path/to/sqllib[,shared]
The configure command defaults to the value of the DB2DIR environment variable.

Table of Contents

  • PDO_IBM DSN — Connecting to IBM databases
PDO_FIREBIRD DSN
PDO_IBM DSN
PDO Drivers


Connecting to IBM databases

IBM (PDO)
Informix (PDO)
IBM (PDO)
PHP Manual

PDO_IBM DSN

(PECL PDO_IBM >= 0.9.0)

PDO_IBM DSN — Connecting to IBM databases

Description

The PDO_IBM Data Source Name (DSN) is based on the IBM CLI DSN. The major components of the PDO_IBM DSN are:

DSN prefix

The DSN prefix is ibm: .

DSN

The DSN can be any of the following:

  • a) Data source setup using db2cli.ini or odbc.ini

  • b) Catalogued database name i.e. database alias in the DB2 client catalog

  • c) Complete connection string in the following format: DRIVER={IBM DB2 ODBC DRIVER};DATABASE=database ;HOSTNAME=hostname ;PORT=port ;PROTOCOL=TCPIP;UID=username ;PWD=password ; where the parameters represent the following values:

    database

    The name of the database.

    hostname

    The hostname or IP address of the database server.

    port

    The TCP/IP port on which the database is listening for requests.

    username

    The username with which you are connecting to the database.

    password

    The password with which you are connecting to the database.

Examples

Example #1 PDO_IBM DSN example using db2cli.ini

The following example shows a PDO_IBM DSN for connecting to an DB2 database cataloged as DB2_9 in db2cli.ini:

$db = new PDO("ibm:DSN=DB2_9", "", "");

[DB2_9]
Database=testdb
Protocol=tcpip
Hostname=11.22.33.444
Servicename=56789

Example #2 PDO_IBM DSN example using a connection string

The following example shows a PDO_IBM DSN for connecting to an DB2 database named testdb using the DB2 CLI connection string syntax.

$db = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=testdb;" .
  "HOSTNAME=11.22.33.444;PORT=56789;PROTOCOL=TCPIP;", "testuser", "tespass");

IBM (PDO)
Informix (PDO)
IBM (PDO)


Informix Functions (PDO_INFORMIX)

Introduction

PDO_INFORMIX is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Informix databases.

Installation

To build the PDO_INFORMIX extension, the Informix Client SDK 2.81 UC1 or higher must be installed on the same system as PHP. The Informix Client SDK is available from the » IBM Informix Support Site.

PDO_INFORMIX is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the PDO_INFORMIX extension. Issue the configure command to point to the location of your Informix Client SDK header files and libraries as follows:

   bash$ ./configure --with-pdo-informix=/path/to/SDK[,shared]
The configure command defaults to the value of the INFORMIXDIR environment variable.

Scrollable cursors

PDO_INFORMIX supports scrollable cursors; however, they are not enabled by default. To enable scrollable cursor support, you must either set ENABLESCROLLABLECURSORS=1 in the corresponding ODBC connection settings in odbc.ini or pass the EnableScrollableCursors=1 clause in the DSN connection string.

Table of Contents

  • PDO_INFORMIX DSN — Connecting to Informix databases
PDO_IBM DSN
PDO_INFORMIX DSN
PDO Drivers


Connecting to Informix databases

Informix (PDO)
MySQL (PDO)
Informix (PDO)
PHP Manual

PDO_INFORMIX DSN

(PECL PDO_INFORMIX >= 0.1.0)

PDO_INFORMIX DSN — Connecting to Informix databases

Description

The PDO_INFORMIX Data Source Name (DSN) is based on the Informix ODBC DSN string. Details on configuring an Informix ODBC DSN are available from the » Informix Dynamic Server Information Center. The major components of the PDO_INFORMIX DSN are:

DSN prefix

The DSN prefix is informix: .

DSN

The DSN can be either a data source setup using odbc.ini or a complete » connection string.

Examples

Example #1 PDO_INFORMIX DSN example using odbc.ini

The following example shows a PDO_INFORMIX DSN for connecting to an Informix database cataloged as Infdrv33 in odbc.ini:

$db = new PDO("informix:DSN=Infdrv33", "", "");

[ODBC Data Sources]
Infdrv33=INFORMIX 3.3 32-BIT

[Infdrv33]
Driver=/opt/informix/csdk_2.81.UC1G2/lib/cli/iclis09b.so
Description=INFORMIX 3.3 32-BIT
Database=common_db
LogonID=testuser
pwd=testpass
Servername=ids_server
DB_LOCALE=en_US.819
OPTIMIZEAUTOCOMMIT=1
ENABLESCROLLABLECURSORS=1

Example #2 PDO_INFORMIX DSN example using a connection string

The following example shows a PDO_INFORMIX DSN for connecting to an Informix database named common_db using the Informix connection string syntax.

$db = new PDO("informix:host=host.domain.com; service=9800;
    database=common_db; server=ids_server; protocol=onsoctcp;
    EnableScrollableCursors=1", "testuser", "tespass");

Informix (PDO)
MySQL (PDO)
Informix (PDO)


MySQL Functions (PDO_MYSQL)

Introduction

PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL 3.x, 4.x and 5.x databases.

PDO_MYSQL will take advantage of native prepared statement support present in MySQL 4.1 and higher. If you're using an older version of the mysql client libraries, PDO will emulate them for you.

Warning

Beware: Some MySQL table types (storage engines) do not support transactions. When writing transactional database code using a table type that does not support transactions, MySQL will pretend that a transaction was initiated successfully. In addition, any DDL queries issued will implicitly commit any pending transactions.

Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver, if your code can run against multiple drivers.

PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (integer)
If this attribute is set to TRUE on a PDOStatement, the MySQL driver will use the buffered versions of the MySQL API. If you're writing portable code, you should use PDOStatement::fetchAll() instead.

Example #1 Forcing queries to be buffered in mysql

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
    $stmt = $db->prepare('select * from foo',
        array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
} else {
    die("my application only works with mysql; I should use \$stmt->fetchAll() instead");
}
?>

PDO::MYSQL_ATTR_LOCAL_INFILE (integer)

Enable LOAD LOCAL INFILE.

PDO::MYSQL_ATTR_INIT_COMMAND (integer)

Command to execute when connecting to the MySQL server. Will automatically be re-executed when reconnecting.

PDO::MYSQL_ATTR_READ_DEFAULT_FILE (integer)

Read options from the named option file instead of from my.cnf. This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_READ_DEFAULT_GROUP (integer)

Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_MAX_BUFFER_SIZE (integer)

Maximum buffer size. Defaults to 1 MiB.

PDO::MYSQL_ATTR_DIRECT_QUERY (integer)

Perform direct queries, don't use prepared statements.

Table of Contents

  • PDO_MYSQL DSN — Connecting to MySQL databases
PDO_INFORMIX DSN
PDO_MYSQL DSN
PDO Drivers


Connecting to MySQL databases

MySQL (PDO)
Oracle (PDO)
MySQL (PDO)
PHP Manual

PDO_MYSQL DSN

(PECL PDO_MYSQL >= 0.1.0)

PDO_MYSQL DSN — Connecting to MySQL databases

Description

The PDO_MYSQL Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is mysql: .

host

The hostname on which the database server resides.

port

The port number where the database server is listening.

dbname

The name of the database.

unix_socket

The MySQL Unix socket (shouldn't be used with host or port).

Examples

Example #1 PDO_MYSQL DSN examples

The following example shows a PDO_MYSQL DSN for connecting to MySQL databases:

mysql:host=localhost;dbname=testdb

More complete examples:

mysql:host=localhost;port=3307;dbname=testdb
mysql:unix_socket=/tmp/mysql.sock;dbname=testdb

MySQL (PDO)
Oracle (PDO)
MySQL (PDO)


Oracle Functions (PDO_OCI)

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.

PDO_OCI is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Oracle databases through the OCI library.

Table of Contents

  • PDO_OCI DSN — Connecting to Oracle databases
PDO_MYSQL DSN
PDO_OCI DSN
PDO Drivers


Connecting to Oracle databases

Oracle (PDO)
ODBC and DB2 (PDO)
Oracle (PDO)
PHP Manual

PDO_OCI DSN

(PECL PDO_OCI >= 0.1.0)

PDO_OCI DSN — Connecting to Oracle databases

Description

The PDO_OCI Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is oci: .

dbname (Oracle Instant Client)

The URI for the Oracle Instant Client connection takes the form of dbname=//hostname:port-number/database. If you are connecting to a database defined in tnsnames.ora, use only the name of the database: dbname=database.

charset

The client-side character set for the current environment handle.

Examples

Example #1 PDO_OCI DSN examples

The following examples show a PDO_OCI DSN for connecting to Oracle databases:

// Connect to a database defined in tnsnames.ora
oci:dbname=mydb

// Connect using the Oracle Instant Client
oci:dbname=//localhost:1521/mydb

Oracle (PDO)
ODBC and DB2 (PDO)
Oracle (PDO)


ODBC and DB2 Functions (PDO_ODBC)

Introduction

PDO_ODBC is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to databases through ODBC drivers or through the IBM DB2 Call Level Interface (DB2 CLI) library. PDO_ODBC currently supports three different "flavours" of database drivers:

ibm-db2

Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 client.

unixODBC

Supports access to database servers through the unixODBC driver manager and the database's own ODBC drivers.

generic

Offers a compile option for ODBC driver managers that are not explicitly supported by PDO_ODBC.

On Windows, PDO_ODBC is built into the PHP core by default. It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN, and is the recommended driver for connecting to Microsoft SQL Server databases.

Installation

PDO_ODBC on UNIX systems

  1. As of PHP 5.1, PDO_ODBC is included in the PHP source. You can compile the PDO_ODBC extension as either a static or shared module using the following configure commands.

    ibm_db2

    ./configure --with-pdo-odbc=ibm-db2,/opt/IBM/db2/V8.1/
    To build PDO_ODBC with the ibm-db2 flavour, you have to have previously installed the DB2 application development headers on the same machine on which you are compiling PDO_ODBC. The DB2 application development headers are an installable option in the DB2 servers, and are also available as part of the DB2 Application Development Client freely available for download from the IBM DB2 Universal Database » support site.

    If you do not supply a location for the DB2 libraries and headers to the configure command, PDO_ODBC defaults to /home/db2inst1/sqllib.

    unixODBC

    ./configure --with-pdo-odbc=unixODBC,/usr/local
    If you do not supply a location for the unixODBC libraries and headers to the configure command, PDO_ODBC defaults to /usr/local.

    generic
    ./configure --with-pdo-odbc=generic,/usr/local,libname,ldflags,cflags

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PDO_ODBC Configuration Options
Name | Default | Changeable | Changelog
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL | Available since PHP 5.1.0.
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Available since PHP 5.1.1. Removed in PHP 6.0.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

pdo_odbc.connection_pooling string

Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off" (equals to ""). The parameter describes how strict the connection manager should be when matching connection parameters to existing pooled connections. strict is the recommend default, and will result in the use of cached connections only when all the connection parameters match exactly. relaxed will result in the use of cached connections when similar connection parameters are used. This can result in increased use of the cache, at the risk of bleeding connection information between (for example) virtual hosts.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

Warning

relaxed matching should not be used on a shared server, for security reasons.

Tip

Leave this setting at the default strict setting unless you have good reason to change it.

pdo_odbc.db2_instance_name string

If you compile PDO_ODBC using the db2 flavour, this setting sets the value of the DB2INSTANCE environment variable on Linux and UNIX operating systems to the specified name of the DB2 instance. This enables PDO_ODBC to resolve the location of the DB2 libraries and make cataloged connections to DB2 databases.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

This setting has no effect on Windows.

Table of Contents

  • PDO_ODBC DSN — Connecting to ODBC or DB2 databases
PDO_OCI DSN
PDO_ODBC DSN
PDO Drivers


Connecting to ODBC or DB2 databases

ODBC and DB2 (PDO)
PostgreSQL (PDO)
ODBC and DB2 (PDO)
PHP Manual

PDO_ODBC DSN

(PECL PDO_ODBC >= 0.1.0)

PDO_ODBC DSN — Connecting to ODBC or DB2 databases

Description

The PDO_ODBC Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is odbc: . If you are connecting to a database cataloged in the ODBC driver manager or the DB2 catalog, you can append the cataloged name of the database to the DSN.

DSN

The name of the database as cataloged in the ODBC driver manager or the DB2 catalog. Alternately, you can provide a complete ODBC connection string to connect to a database as described at » http://www.connectionstrings.com/.

UID

The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

PWD

The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

Examples

Example #1 PDO_ODBC DSN example (ODBC driver manager)

The following example shows a PDO_ODBC DSN for connecting to an ODBC database cataloged as testdb in the ODBC driver manager:

odbc:testdb

Example #2 PDO_ODBC DSN example (IBM DB2 uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to an IBM DB2 database named SAMPLE using the full ODBC DSN syntax:

odbc:DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME=localhost;PORT=50000;DATABASE=SAMPLE;PROTOCOL=TCPIP;UID=db2inst1;PWD=ibmdb2;

Example #3 PDO_ODBC DSN example (Microsoft Access uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to a Microsoft Access database stored at C:\db.mdb using the full ODBC DSN syntax:

odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\db.mdb;Uid=Admin

ODBC and DB2 (PDO)
PostgreSQL (PDO)
ODBC and DB2 (PDO)


PostgreSQL Functions (PDO_PGSQL)

Introduction

PDO_PGSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to PostgreSQL databases.

Resource Types

This extension defines a stream resource returned by PDO::pgsqlLOBOpen().

Table of Contents

  • PDO_PGSQL DSN — Connecting to PostgreSQL databases
  • PDO::pgsqlLOBCreate — Creates a new large object
  • PDO::pgsqlLOBOpen — Opens an existing large object stream
  • PDO::pgsqlLOBUnlink — Deletes the large object
PDO_ODBC DSN
PDO_PGSQL DSN
PDO Drivers


Connecting to PostgreSQL databases

PostgreSQL (PDO)
PDO::pgsqlLOBCreate
PostgreSQL (PDO)
PHP Manual

PDO_PGSQL DSN

(PECL PDO_PGSQL >= 0.1.0)

PDO_PGSQL DSN — Connecting to PostgreSQL databases

Description

The PDO_PGSQL Data Source Name (DSN) is composed of the following elements, delimited by spaces:

DSN prefix

The DSN prefix is pgsql: .

host

The hostname on which the database server resides.

port

The port on which the database server is running.

dbname

The name of the database.

user

The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

password

The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

Note: The bytea fields are returned as streams.

Examples

Example #1 PDO_PGSQL DSN examples

The following example shows a PDO_PGSQL DSN for connecting to a PostgreSQL database:

pgsql:host=localhost port=5432 dbname=testdb user=bruce password=mypass

PostgreSQL (PDO)
PDO::pgsqlLOBCreate
PostgreSQL (PDO)


SQLite Functions (PDO_SQLITE)

Introduction

PDO_SQLITE is a driver that implements the PHP Data Objects (PDO) interface to enable access to SQLite 3 databases.

In PHP 5.1, the SQLite extension also provides a driver for SQLite 2 databases; while it is not technically a part of the PDO_SQLITE driver, it behaves similarly, so it is documented alongside it. The SQLite 2 driver for PDO is provided primarily to make it easier to import legacy SQLite 2 database files into an application that uses the faster, more efficient SQLite 3 driver. As a result, the SQLite 2 driver is not as feature-rich as the SQLite 3 driver.

Note: PDO_SQLITE allows using strings apart from streams together with PDO::PARAM_LOB.

Table of Contents

  • PDO_SQLITE DSN — Connecting to SQLite databases
  • PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements
  • PDO::sqliteCreateFunction — Registers a User Defined Function for use in SQL statements
PDO::pgsqlLOBUnlink
PDO_SQLITE DSN
PDO Drivers


Connecting to SQLite databases

SQLite (PDO)
PDO::sqliteCreateAggregate
SQLite (PDO)
PHP Manual

PDO_SQLITE DSN

(PECL PDO_SQLITE >= 0.2.0)

PDO_SQLITE DSN — Connecting to SQLite databases

Description

The PDO_SQLITE Data Source Name (DSN) is composed of the following elements:

DSN prefix (SQLite 3)

The DSN prefix is sqlite: .

  • To access a database on disk, append the absolute path to the DSN prefix.

  • To create a database in memory, append :memory: to the DSN prefix.

DSN prefix (SQLite 2)

The SQLite extension in PHP 5.1 provides a PDO driver that supports accessing and creating SQLite 2 databases. This enables you to access databases you may have created with the SQLite extension in previous versions of PHP.

Note: The sqlite2 driver is only available in PHP 5.1.x if you have enabled both PDO and ext/sqlite. It is not currently available via PECL.

The DSN prefix for connecting to SQLite 2 databases is sqlite2: .

  • To access a database on disk, append the absolute path to the DSN prefix.

  • To create a database in memory, append :memory: to the DSN prefix.

Examples

Example #1 PDO_SQLITE DSN examples

The following examples show PDO_SQLITE DSN for connecting to SQLite databases:

sqlite:/opt/databases/mydb.sq3
sqlite::memory:
sqlite2:/opt/databases/mydb.sq2
sqlite2::memory:

SQLite (PDO)
PDO::sqliteCreateAggregate
SQLite (PDO)


PostgreSQL Functions

Notes

Note: Not all functions are supported by all builds. It depends on your libpq (The PostgreSQL C client library) version and how libpq is compiled. If PHP PostgreSQL extensions are missing, then it is because your libpq version does not support them.

Note: Most PostgreSQL functions accept connection as the first optional parameter. If it is not provided, the last opened connection is used. If it doesn't exist, functions return FALSE.

Note: PostgreSQL automatically folds all identifiers (e.g. table/column names) to lower-case values at object creation time and at query time. To force the use of mixed or upper case identifiers, you must escape the identifier using double quotes ("").

Note: PostgreSQL does not have special commands for fetching database schema information (eg. all the tables in the current database). Instead, there is a standard schema named information_schema in PostgreSQL 7.4 and above containing system views with all the necessary information, in an easily queryable form. See the » PostgreSQL Documentation for full details.

Table of Contents

  • pg_affected_rows — Returns number of affected records (tuples)
  • pg_cancel_query — Cancel an asynchronous query
  • pg_client_encoding — Gets the client encoding
  • pg_close — Closes a PostgreSQL connection
  • pg_connect — Open a PostgreSQL connection
  • pg_connection_busy — Get connection is busy or not
  • pg_connection_reset — Reset connection (reconnect)
  • pg_connection_status — Get connection status
  • pg_convert — Convert associative array values into suitable for SQL statement
  • pg_copy_from — Insert records into a table from an array
  • pg_copy_to — Copy a table to an array
  • pg_dbname — Get the database name
  • pg_delete — Deletes records
  • pg_end_copy — Sync with PostgreSQL backend
  • pg_escape_bytea — Escape a string for insertion into a bytea field
  • pg_escape_string — Escape a string for insertion into a text field
  • pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_fetch_all_columns — Fetches all rows in a particular result column as an array
  • pg_fetch_all — Fetches all rows from a result as an array
  • pg_fetch_array — Fetch a row as an array
  • pg_fetch_assoc — Fetch a row as an associative array
  • pg_fetch_object — Fetch a row as an object
  • pg_fetch_result — Returns values from a result resource
  • pg_fetch_row — Get a row as an enumerated array
  • pg_field_is_null — Test if a field is SQL NULL
  • pg_field_name — Returns the name of a field
  • pg_field_num — Returns the field number of the named field
  • pg_field_prtlen — Returns the printed length
  • pg_field_size — Returns the internal storage size of the named field
  • pg_field_table — Returns the name or oid of the tables field
  • pg_field_type_oid — Returns the type ID (OID) for the corresponding field number
  • pg_field_type — Returns the type name for the corresponding field number
  • pg_free_result — Free result memory
  • pg_get_notify — Gets SQL NOTIFY message
  • pg_get_pid — Gets the backend's process ID
  • pg_get_result — Get asynchronous query result
  • pg_host — Returns the host name associated with the connection
  • pg_insert — Insert array into table
  • pg_last_error — Get the last error message string of a connection
  • pg_last_notice — Returns the last notice message from PostgreSQL server
  • pg_last_oid — Returns the last row's OID
  • pg_lo_close — Close a large object
  • pg_lo_create — Create a large object
  • pg_lo_export — Export a large object to file
  • pg_lo_import — Import a large object from file
  • pg_lo_open — Open a large object
  • pg_lo_read_all — Reads an entire large object and send straight to browser
  • pg_lo_read — Read a large object
  • pg_lo_seek — Seeks position within a large object
  • pg_lo_tell — Returns current seek position a of large object
  • pg_lo_unlink — Delete a large object
  • pg_lo_write — Write to a large object
  • pg_meta_data — Get meta data for table
  • pg_num_fields — Returns the number of fields in a result
  • pg_num_rows — Returns the number of rows in a result
  • pg_options — Get the options associated with the connection
  • pg_parameter_status — Looks up a current parameter setting of the server.
  • pg_pconnect — Open a persistent PostgreSQL connection
  • pg_ping — Ping database connection
  • pg_port — Return the port number associated with the connection
  • pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.
  • pg_put_line — Send a NULL-terminated string to PostgreSQL backend
  • pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
  • pg_query — Execute a query
  • pg_result_error_field — Returns an individual field of an error report.
  • pg_result_error — Get error message associated with result
  • pg_result_seek — Set internal row offset in result resource
  • pg_result_status — Get status of query result
  • pg_select — Select records
  • pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
  • pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion.
  • pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s).
  • pg_send_query — Sends asynchronous query
  • pg_set_client_encoding — Set the client encoding
  • pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error.
  • pg_trace — Enable tracing a PostgreSQL connection
  • pg_transaction_status — Returns the current in-transaction status of the server.
  • pg_tty — Return the TTY name associated with the connection
  • pg_unescape_bytea — Unescape binary for bytea type
  • pg_untrace — Disable tracing of a PostgreSQL connection
  • pg_update — Update table
  • pg_version — Returns an array with client, protocol and server version (when available)
PostgreSQL extension overview example
pg_affected_rows
PostgreSQL


POSIX Functions

See Also

The section about Process Control Functions maybe of interest for you.

Table of Contents

  • posix_access — Determine accessibility of a file
  • posix_ctermid — Get path name of controlling terminal
  • posix_errno — Alias of posix_get_last_error
  • posix_get_last_error — Retrieve the error number set by the last posix function that failed
  • posix_getcwd — Pathname of current directory
  • posix_getegid — Return the effective group ID of the current process
  • posix_geteuid — Return the effective user ID of the current process
  • posix_getgid — Return the real group ID of the current process
  • posix_getgrgid — Return info about a group by group id
  • posix_getgrnam — Return info about a group by name
  • posix_getgroups — Return the group set of the current process
  • posix_getlogin — Return login name
  • posix_getpgid — Get process group id for job control
  • posix_getpgrp — Return the current process group identifier
  • posix_getpid — Return the current process identifier
  • posix_getppid — Return the parent process identifier
  • posix_getpwnam — Return info about a user by username
  • posix_getpwuid — Return info about a user by user id
  • posix_getrlimit — Return info about system resource limits
  • posix_getsid — Get the current sid of the process
  • posix_getuid — Return the real user ID of the current process
  • posix_initgroups — Calculate the group access list
  • posix_isatty — Determine if a file descriptor is an interactive terminal
  • posix_kill — Send a signal to a process
  • posix_mkfifo — Create a fifo special file (a named pipe)
  • posix_mknod — Create a special or ordinary file (POSIX.1)
  • posix_setegid — Set the effective GID of the current process
  • posix_seteuid — Set the effective UID of the current process
  • posix_setgid — Set the GID of the current process
  • posix_setpgid — Set process group id for job control
  • posix_setsid — Make the current process a session leader
  • posix_setuid — Set the UID of the current process
  • posix_strerror — Retrieve the system error message associated with the given errno
  • posix_times — Get process times
  • posix_ttyname — Determine terminal device name
  • posix_uname — Get system name
Predefined Constants
posix_access
POSIX


PS Functions

Contact Information

If you have comments, bugfixes, enhancements for either this extension or pslib then please drop me a mail » steinm@php.net. Any help is very welcome.

Table of Contents

  • ps_add_bookmark — Add bookmark to current page
  • ps_add_launchlink — Adds link which launches file
  • ps_add_locallink — Adds link to a page in the same document
  • ps_add_note — Adds note to current page
  • ps_add_pdflink — Adds link to a page in a second pdf document
  • ps_add_weblink — Adds link to a web location
  • ps_arc — Draws an arc counterclockwise
  • ps_arcn — Draws an arc clockwise
  • ps_begin_page — Start a new page
  • ps_begin_pattern — Start a new pattern
  • ps_begin_template — Start a new template
  • ps_circle — Draws a circle
  • ps_clip — Clips drawing to current path
  • ps_close_image — Closes image and frees memory
  • ps_close — Closes a PostScript document
  • ps_closepath_stroke — Closes and strokes path
  • ps_closepath — Closes path
  • ps_continue_text — Continue text in next line
  • ps_curveto — Draws a curve
  • ps_delete — Deletes all resources of a PostScript document
  • ps_end_page — End a page
  • ps_end_pattern — End a pattern
  • ps_end_template — End a template
  • ps_fill_stroke — Fills and strokes the current path
  • ps_fill — Fills the current path
  • ps_findfont — Loads a font
  • ps_get_buffer — Fetches the full buffer containig the generated PS data
  • ps_get_parameter — Gets certain parameters
  • ps_get_value — Gets certain values
  • ps_hyphenate — Hyphenates a word
  • ps_include_file — Reads an external file with raw PostScript code
  • ps_lineto — Draws a line
  • ps_makespotcolor — Create spot color
  • ps_moveto — Sets current point
  • ps_new — Creates a new PostScript document object
  • ps_open_file — Opens a file for output
  • ps_open_image_file — Opens image from file
  • ps_open_image — Reads an image for later placement
  • ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document
  • ps_place_image — Places image on the page
  • ps_rect — Draws a rectangle
  • ps_restore — Restore previously save context
  • ps_rotate — Sets rotation factor
  • ps_save — Save current context
  • ps_scale — Sets scaling factor
  • ps_set_border_color — Sets color of border for annotations
  • ps_set_border_dash — Sets length of dashes for border of annotations
  • ps_set_border_style — Sets border style of annotations
  • ps_set_info — Sets information fields of document
  • ps_set_parameter — Sets certain parameters
  • ps_set_text_pos — Sets position for text output
  • ps_set_value — Sets certain values
  • ps_setcolor — Sets current color
  • ps_setdash — Sets appearance of a dashed line
  • ps_setflat — Sets flatness
  • ps_setfont — Sets font to use for following output
  • ps_setgray — Sets gray value
  • ps_setlinecap — Sets appearance of line ends
  • ps_setlinejoin — Sets how contected lines are joined
  • ps_setlinewidth — Sets width of a line
  • ps_setmiterlimit — Sets the miter limit
  • ps_setoverprintmode — Sets overprint mode
  • ps_setpolydash — Sets appearance of a dashed line
  • ps_shading_pattern — Creates a pattern based on a shading
  • ps_shading — Creates a shading for later use
  • ps_shfill — Fills an area with a shading
  • ps_show_boxed — Output text in a box
  • ps_show_xy2 — Output text at position
  • ps_show_xy — Output text at given position
  • ps_show2 — Output a text at current position
  • ps_show — Output text
  • ps_string_geometry — Gets geometry of a string
  • ps_stringwidth — Gets width of a string
  • ps_stroke — Draws the current path
  • ps_symbol_name — Gets name of a glyph
  • ps_symbol_width — Gets width of a glyph
  • ps_symbol — Output a glyph
  • ps_translate — Sets translation
Predefined Constants
ps_add_bookmark
PS


Pspell Functions

Table of Contents

  • pspell_add_to_personal — Add the word to a personal wordlist
  • pspell_add_to_session — Add the word to the wordlist in the current session
  • pspell_check — Check a word
  • pspell_clear_session — Clear the current session
  • pspell_config_create — Create a config used to open a dictionary
  • pspell_config_data_dir — location of language data files
  • pspell_config_dict_dir — Location of the main word list
  • pspell_config_ignore — Ignore words less than N characters long
  • pspell_config_mode — Change the mode number of suggestions returned
  • pspell_config_personal — Set a file that contains personal wordlist
  • pspell_config_repl — Set a file that contains replacement pairs
  • pspell_config_runtogether — Consider run-together words as valid compounds
  • pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist
  • pspell_new_config — Load a new dictionary with settings based on a given config
  • pspell_new_personal — Load a new dictionary with personal wordlist
  • pspell_new — Load a new dictionary
  • pspell_save_wordlist — Save the personal wordlist to a file
  • pspell_store_replacement — Store a replacement pair for a word
  • pspell_suggest — Suggest spellings of a word
Predefined Constants
pspell_add_to_personal
Pspell


Radius Functions

Contact Information

If you have comments, bugfixes, enhancements or want to help to develop this you can send me a mail at » mbretter@php.net.

Table of Contents

  • radius_acct_open — Creates a Radius handle for accounting
  • radius_add_server — Adds a server
  • radius_auth_open — Creates a Radius handle for authentication
  • radius_close — Frees all ressources
  • radius_config — Causes the library to read the given configuration file
  • radius_create_request — Create accounting or authentication request
  • radius_cvt_addr — Converts raw data to IP-Address
  • radius_cvt_int — Converts raw data to integer
  • radius_cvt_string — Converts raw data to string
  • radius_demangle_mppe_key — Derives mppe-keys from mangled data
  • radius_demangle — Demangles data
  • radius_get_attr — Extracts an attribute
  • radius_get_vendor_attr — Extracts a vendor specific attribute
  • radius_put_addr — Attaches an IP-Address attribute
  • radius_put_attr — Attaches a binary attribute
  • radius_put_int — Attaches an integer attribute
  • radius_put_string — Attaches a string attribute
  • radius_put_vendor_addr — Attaches a vendor specific IP-Address attribute
  • radius_put_vendor_attr — Attaches a vendor specific binary attribute
  • radius_put_vendor_int — Attaches a vendor specific integer attribute
  • radius_put_vendor_string — Attaches a vendor specific string attribute
  • radius_request_authenticator — Returns the request authenticator
  • radius_send_request — Sends the request and waites for a reply
  • radius_server_secret — Returns the shared secret
  • radius_strerror — Returns an error message
Examples
radius_acct_open
Radius


Readline Functions

Table of Contents

  • readline_add_history — Adds a line to the history
  • readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately
  • readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings
  • readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received
  • readline_clear_history — Clears the history
  • readline_completion_function — Registers a completion function
  • readline_info — Gets/sets various internal readline variables
  • readline_list_history — Lists the history
  • readline_on_new_line — Inform readline that the cursor has moved to a new line
  • readline_read_history — Reads the history
  • readline_redisplay — Redraws the display
  • readline_write_history — Writes the history
  • readline — Reads a line
Predefined Constants
readline_add_history
Readline


Recode Functions

Table of Contents

  • recode_file — Recode from file to file according to recode request
  • recode_string — Recode a string according to a recode request
  • recode — Alias of recode_string
Predefined Constants
recode_file
Recode


RPM Reader Functions

Table of Contents

  • rpm_close — Closes an RPM file
  • rpm_get_tag — Retrieves a header tag from an RPM file
  • rpm_is_valid — Tests a filename for validity as an RPM file
  • rpm_open — Opens an RPM file
  • rpm_version — Returns a string representing the current version of the rpmreader extension
Basic usage
rpm_close
RPM Reader


runkit Functions

Table of Contents

  • Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine
  • Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class
  • runkit_class_adopt — Convert a base class to an inherited class, add ancestral methods when appropriate
  • runkit_class_emancipate — Convert an inherited class to a base class, removes any method whose scope is ancestral
  • runkit_constant_add — Similar to define(), but allows defining in class definitions as well
  • runkit_constant_redefine — Redefine an already defined constant
  • runkit_constant_remove — Remove/Delete an already defined constant
  • runkit_function_add — Add a new function, similar to create_function
  • runkit_function_copy — Copy a function to a new function name
  • runkit_function_redefine — Replace a function definition with a new implementation
  • runkit_function_remove — Remove a function definition
  • runkit_function_rename — Change a function's name
  • runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate
  • runkit_lint_file — Check the PHP syntax of the specified file
  • runkit_lint — Check the PHP syntax of the specified php code
  • runkit_method_add — Dynamically adds a new method to a given class
  • runkit_method_copy — Copies a method from class to another
  • runkit_method_redefine — Dynamically changes the code of the given method
  • runkit_method_remove — Dynamically removes the given method
  • runkit_method_rename — Dynamically changes the name of the given method
  • runkit_return_value_used — Determines if the current functions return value will be used
  • runkit_sandbox_output_handler — Specify a function to capture and/or process output from a runkit sandbox
  • runkit_superglobals — Return numerically indexed array of registered superglobals
Resource Types
Runkit_Sandbox
runkit


Semaphore Functions

Table of Contents

  • ftok — Convert a pathname and a project identifier to a System V IPC key
  • msg_get_queue — Create or attach to a message queue
  • msg_queue_exists — Check whether a message queue exists
  • msg_receive — Receive a message from a message queue
  • msg_remove_queue — Destroy a message queue
  • msg_send — Send a message to a message queue
  • msg_set_queue — Set information in the message queue data structure
  • msg_stat_queue — Returns information from the message queue data structure
  • sem_acquire — Acquire a semaphore
  • sem_get — Get a semaphore id
  • sem_release — Release a semaphore
  • sem_remove — Remove a semaphore
  • shm_attach — Creates or open a shared memory segment
  • shm_detach — Disconnects from shared memory segment
  • shm_get_var — Returns a variable from shared memory
  • shm_has_var — Check whether a specific entry exists
  • shm_put_var — Inserts or updates a variable in shared memory
  • shm_remove_var — Removes a variable from shared memory
  • shm_remove — Removes shared memory from Unix systems
Predefined Constants
ftok
Semaphore


Shared Memory Functions

Table of Contents

  • shmop_close — Close shared memory block
  • shmop_delete — Delete shared memory block
  • shmop_open — Create or open shared memory block
  • shmop_read — Read data from shared memory block
  • shmop_size — Get size of shared memory block
  • shmop_write — Write data into shared memory block
Shared Memory Operations Overview
shmop_close
Shared Memory


SPPLUS Functions

Table of Contents

  • calcul_hmac — Obtain a hmac key (needs 8 arguments)
  • calculhmac — Obtain a hmac key (needs 2 arguments)
  • nthmac — Obtain a nthmac key (needs 2 arguments)
  • signeurlpaiement — Obtain the payment url (needs 2 arguments)
Predefined Constants
calcul_hmac
SPPLUS


SQLite Functions

Predefined Classes

SQLiteDatabase

Represents an opened SQLite database.

Constructor

  • __construct - construct a new SQLiteDatabase object

Methods

  • query - Execute a query
  • queryExec - Execute a result-less query
  • arrayQuery - Execute a query and return the result as an array
  • singleQuery - Execute a query and return either an array for one single column or the value of the first row
  • unbufferedQuery - Execute an unbuffered query
  • lastInsertRowid - Returns the rowid of the most recently inserted row
  • changes - Returns the number of rows changed by the most recent statement
  • createAggregate - Register an aggregating UDF for use in SQL statements
  • createFunction - Register a UDF for use in SQL statements
  • busyTimeout - Sets or disables busy timeout duration
  • lastError - Returns the last error code of the most recently encountered error
  • fetchColumnTypes - Return an array of column types from a particular table

SQLiteResult

Represents a buffered SQLite result set.

Methods

  • fetch - Fetches the next row from the result set as an array
  • fetchObject - Fetches the next row from the result set as an object
  • fetchSingle - Fetches the first column from the result set as a string
  • fetchAll - Fetches all rows from the result set as an array of arrays
  • column - Fetches a column from the current row of the result set
  • numFields - Returns the number of fields in the result set
  • fieldName - Returns the name of a particular field in the result set
  • current - Fetches the current row from the result set as an array
  • key - Return the current row index
  • next - Seek to the next row number
  • valid - Returns whether more rows are available
  • rewind - Seek to the first row number of the result set
  • prev - Seek to the previous row number of the result set
  • hasPrev - Returns whether or not a previous row is available
  • numRows - Returns the number of rows in the result set
  • seek - Seek to a particular row number

SQLiteUnbuffered

Represents an unbuffered SQLite result set. Unbuffered results sets are sequential, forward-seeking only.

Methods

  • fetch - Fetches the next row from the result set as an array
  • fetchObject - Fetches the next row from the result set as an object
  • fetchSingle - Fetches the first column from the result set as a string
  • fetchAll - Fetches all rows from the result set as an array of arrays
  • column - Fetches a column from the current row of the result set
  • numFields - Returns the number of fields in the result set
  • fieldName - Returns the name of a particular field in the result set
  • current - Fetches the current row from the result set as an array
  • next - Seek to the next row number
  • valid - Returns whether more rows are available

Table of Contents

  • sqlite_array_query — Execute a query against a given database and returns an array
  • sqlite_busy_timeout — Set busy timeout duration, or disable busy handlers
  • sqlite_changes — Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_close — Closes an open SQLite database
  • sqlite_column — Fetches a column from the current row of a result set
  • sqlite_create_aggregate — Register an aggregating UDF for use in SQL statements
  • sqlite_create_function — Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_current — Fetches the current row from a result set as an array
  • sqlite_error_string — Returns the textual description of an error code
  • sqlite_escape_string — Escapes a string for use as a query parameter
  • sqlite_exec — Executes a result-less query against a given database
  • sqlite_factory — Opens a SQLite database and returns a SQLiteDatabase object
  • sqlite_fetch_all — Fetches all rows from a result set as an array of arrays
  • sqlite_fetch_array — Fetches the next row from a result set as an array
  • sqlite_fetch_column_types — Return an array of column types from a particular table
  • sqlite_fetch_object — Fetches the next row from a result set as an object
  • sqlite_fetch_single — Fetches the first column of a result set as a string
  • sqlite_fetch_string — Alias of sqlite_fetch_single
  • sqlite_field_name — Returns the name of a particular field
  • sqlite_has_more — Finds whether or not more rows are available
  • sqlite_has_prev — Returns whether or not a previous row is available
  • sqlite_key — Returns the current row index
  • sqlite_last_error — Returns the error code of the last error for a database
  • sqlite_last_insert_rowid — Returns the rowid of the most recently inserted row
  • sqlite_libencoding — Returns the encoding of the linked SQLite library
  • sqlite_libversion — Returns the version of the linked SQLite library
  • sqlite_next — Seek to the next row number
  • sqlite_num_fields — Returns the number of fields in a result set
  • sqlite_num_rows — Returns the number of rows in a buffered result set
  • sqlite_open — Opens a SQLite database and create the database if it does not exist
  • sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist
  • sqlite_prev — Seek to the previous row number of a result set
  • sqlite_query — Executes a query against a given database and returns a result handle
  • sqlite_rewind — Seek to the first row number
  • sqlite_seek — Seek to a particular row number of a buffered result set
  • sqlite_single_query — Executes a query and returns either an array for one single column or the value of the first row
  • sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF
  • sqlite_udf_encode_binary — Encode binary data before returning it from an UDF
  • sqlite_unbuffered_query — Execute a query that does not prefetch and buffer all data
  • sqlite_valid — Returns whether more rows are available
Predefined Constants
sqlite_array_query
SQLite


Statistic Functions

Table of Contents

  • stats_absolute_deviation — Returns the absolute deviation of an array of values
  • stats_cdf_beta — CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.
  • stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others.
  • stats_cdf_cauchy — Not documented
  • stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others.
  • stats_cdf_exponential — Not documented
  • stats_cdf_f — Calculates any one parameter of the F distribution given values for the others.
  • stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others.
  • stats_cdf_laplace — Not documented
  • stats_cdf_logistic — Not documented
  • stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others.
  • stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others.
  • stats_cdf_noncentral_f — Calculates any one parameter of the Non-central F distribution given values for the others.
  • stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others.
  • stats_cdf_t — Calculates any one parameter of the T distribution given values for the others.
  • stats_cdf_uniform — Not documented
  • stats_cdf_weibull — Not documented
  • stats_covariance — Computes the covariance of two data sets
  • stats_den_uniform — Not documented
  • stats_dens_beta — Not documented
  • stats_dens_cauchy — Not documented
  • stats_dens_chisquare — Not documented
  • stats_dens_exponential — Not documented
  • stats_dens_f — Description
  • stats_dens_gamma — Not documented
  • stats_dens_laplace — Not documented
  • stats_dens_logistic — Not documented
  • stats_dens_negative_binomial — Not documented
  • stats_dens_normal — Not documented
  • stats_dens_pmf_binomial — Not documented
  • stats_dens_pmf_hypergeometric — Description
  • stats_dens_pmf_poisson — Not documented
  • stats_dens_t — Not documented
  • stats_dens_weibull — Not documented
  • stats_harmonic_mean — Returns the harmonic mean of an array of values
  • stats_kurtosis — Computes the kurtosis of the data in the array
  • stats_rand_gen_beta — Generates beta random deviate
  • stats_rand_gen_chisquare — Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.
  • stats_rand_gen_exponential — Generates a single random deviate from an exponential distribution with mean "av"
  • stats_rand_gen_f — Generates a random deviate
  • stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)
  • stats_rand_gen_gamma — Generates random deviates from a gamma distribution
  • stats_rand_gen_ibinomial_negative — Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).
  • stats_rand_gen_ibinomial — Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE
  • stats_rand_gen_int — Generates random integer between 1 and 2147483562
  • stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).
  • stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
  • stats_rand_gen_noncenral_chisquare — Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0
  • stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central denominator chisquare variate.
  • stats_rand_gen_noncentral_t — Generates a single random deviate from a noncentral T distribution
  • stats_rand_gen_normal — Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.
  • stats_rand_gen_t — Generates a single random deviate from a T distribution
  • stats_rand_get_seeds — Not documented
  • stats_rand_phrase_to_seeds — generate two seeds for the RGN random number generator
  • stats_rand_ranf — Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator
  • stats_rand_setall — Not documented
  • stats_skew — Computes the skewness of the data in the array
  • stats_standard_deviation — Returns the standard deviation
  • stats_stat_binomial_coef — Not documented
  • stats_stat_correlation — Not documented
  • stats_stat_gennch — Not documented
  • stats_stat_independent_t — Not documented
  • stats_stat_innerproduct — Description
  • stats_stat_noncentral_t — Calculates any one parameter of the noncentral t distribution give values for the others.
  • stats_stat_paired_t — Not documented
  • stats_stat_percentile — Not documented
  • stats_stat_powersum — Not documented
  • stats_variance — Returns the population variance
Predefined Constants
stats_absolute_deviation
Statistics


SWF Functions

Table of Contents

  • swf_actiongeturl — Get a URL from a Shockwave Flash movie
  • swf_actiongotoframe — Play a frame and then stop
  • swf_actiongotolabel — Display a frame with the specified label
  • swf_actionnextframe — Go forward one frame
  • swf_actionplay — Start playing the flash movie from the current frame
  • swf_actionprevframe — Go backwards one frame
  • swf_actionsettarget — Set the context for actions
  • swf_actionstop — Stop playing the flash movie at the current frame
  • swf_actiontogglequality — Toggle between low and high quality
  • swf_actionwaitforframe — Skip actions if a frame has not been loaded
  • swf_addbuttonrecord — Controls location, appearance and active area of the current button
  • swf_addcolor — Set the global add color to the rgba value specified
  • swf_closefile — Close the current Shockwave Flash file
  • swf_definebitmap — Define a bitmap
  • swf_definefont — Defines a font
  • swf_defineline — Define a line
  • swf_definepoly — Define a polygon
  • swf_definerect — Define a rectangle
  • swf_definetext — Define a text string
  • swf_endbutton — End the definition of the current button
  • swf_enddoaction — End the current action
  • swf_endshape — Completes the definition of the current shape
  • swf_endsymbol — End the definition of a symbol
  • swf_fontsize — Change the font size
  • swf_fontslant — Set the font slant
  • swf_fonttracking — Set the current font tracking
  • swf_getbitmapinfo — Get information about a bitmap
  • swf_getfontinfo — Gets font information
  • swf_getframe — Get the frame number of the current frame
  • swf_labelframe — Label the current frame
  • swf_lookat — Define a viewing transformation
  • swf_modifyobject — Modify an object
  • swf_mulcolor — Sets the global multiply color to the rgba value specified
  • swf_nextid — Returns the next free object id
  • swf_oncondition — Describe a transition used to trigger an action list
  • swf_openfile — Open a new Shockwave Flash file
  • swf_ortho2 — Defines 2D orthographic mapping of user coordinates onto the current viewport
  • swf_ortho — Defines an orthographic mapping of user coordinates onto the current viewport
  • swf_perspective — Define a perspective projection transformation
  • swf_placeobject — Place an object onto the screen
  • swf_polarview — Define the viewer's position with polar coordinates
  • swf_popmatrix — Restore a previous transformation matrix
  • swf_posround — Enables or Disables the rounding of the translation when objects are placed or moved
  • swf_pushmatrix — Push the current transformation matrix back unto the stack
  • swf_removeobject — Remove an object
  • swf_rotate — Rotate the current transformation
  • swf_scale — Scale the current transformation
  • swf_setfont — Change the current font
  • swf_setframe — Switch to a specified frame
  • swf_shapearc — Draw a circular arc
  • swf_shapecurveto3 — Draw a cubic bezier curve
  • swf_shapecurveto — Draw a quadratic bezier curve between two points
  • swf_shapefillbitmapclip — Set current fill mode to clipped bitmap
  • swf_shapefillbitmaptile — Set current fill mode to tiled bitmap
  • swf_shapefilloff — Turns off filling
  • swf_shapefillsolid — Set the current fill style to the specified color
  • swf_shapelinesolid — Set the current line style
  • swf_shapelineto — Draw a line
  • swf_shapemoveto — Move the current position
  • swf_showframe — Display the current frame
  • swf_startbutton — Start the definition of a button
  • swf_startdoaction — Start a description of an action list for the current frame
  • swf_startshape — Start a complex shape
  • swf_startsymbol — Define a symbol
  • swf_textwidth — Get the width of a string
  • swf_translate — Translate the current transformations
  • swf_viewport — Select an area for future drawing
Basic Usage
swf_actiongeturl
SWF


Sybase Functions

Table of Contents

  • sybase_affected_rows — Gets number of affected rows in last query
  • sybase_close — Closes a Sybase connection
  • sybase_connect — Opens a Sybase server connection
  • sybase_data_seek — Moves internal row pointer
  • sybase_deadlock_retry_count — Sets the deadlock retry count
  • sybase_fetch_array — Fetch row as array
  • sybase_fetch_assoc — Fetch a result row as an associative array
  • sybase_fetch_field — Get field information from a result
  • sybase_fetch_object — Fetch a row as an object
  • sybase_fetch_row — Get a result row as an enumerated array
  • sybase_field_seek — Sets field offset
  • sybase_free_result — Frees result memory
  • sybase_get_last_message — Returns the last message from the server
  • sybase_min_client_severity — Sets minimum client severity
  • sybase_min_error_severity — Sets minimum error severity
  • sybase_min_message_severity — Sets minimum message severity
  • sybase_min_server_severity — Sets minimum server severity
  • sybase_num_fields — Gets the number of fields in a result set
  • sybase_num_rows — Get number of rows in a result set
  • sybase_pconnect — Open persistent Sybase connection
  • sybase_query — Sends a Sybase query
  • sybase_result — Get result data
  • sybase_select_db — Selects a Sybase database
  • sybase_set_message_handler — Sets the handler called when a server message is raised
  • sybase_unbuffered_query — Send a Sybase query and do not block
Predefined Constants
sybase_affected_rows
Sybase


Unicode Functions

Table of Contents

  • unicode_decode — Convert a binary string into a Unicode string
  • unicode_encode — Convert a unicode string in any encoding
  • unicode_get_error_mode — Get the error mode for strings conversions
  • unicode_get_subst_char — Get the substitution character for string conversion errors
  • unicode_set_error_mode — Set the error mode for strings conversions
  • unicode_set_subst_char — Set the substitution character for string conversion errors
Predefined Constants
unicode_decode
Unicode


ODBC Functions

Table of Contents

  • odbc_autocommit — Toggle autocommit behaviour
  • odbc_binmode — Handling of binary column data
  • odbc_close_all — Close all ODBC connections
  • odbc_close — Close an ODBC connection
  • odbc_columnprivileges — Lists columns and associated privileges for the given table
  • odbc_columns — Lists the column names in specified tables
  • odbc_commit — Commit an ODBC transaction
  • odbc_connect — Connect to a datasource
  • odbc_cursor — Get cursorname
  • odbc_data_source — Returns information about a current connection
  • odbc_do — Alias of odbc_exec
  • odbc_error — Get the last error code
  • odbc_errormsg — Get the last error message
  • odbc_exec — Prepare and execute a SQL statement
  • odbc_execute — Execute a prepared statement
  • odbc_fetch_array — Fetch a result row as an associative array
  • odbc_fetch_into — Fetch one result row into array
  • odbc_fetch_object — Fetch a result row as an object
  • odbc_fetch_row — Fetch a row
  • odbc_field_len — Get the length (precision) of a field
  • odbc_field_name — Get the columnname
  • odbc_field_num — Return column number
  • odbc_field_precision — Alias of odbc_field_len
  • odbc_field_scale — Get the scale of a field
  • odbc_field_type — Datatype of a field
  • odbc_foreignkeys — Retrieves a list of foreign keys
  • odbc_free_result — Free resources associated with a result
  • odbc_gettypeinfo — Retrieves information about data types supported by the data source
  • odbc_longreadlen — Handling of LONG columns
  • odbc_next_result — Checks if multiple results are available
  • odbc_num_fields — Number of columns in a result
  • odbc_num_rows — Number of rows in a result
  • odbc_pconnect — Open a persistent database connection
  • odbc_prepare — Prepares a statement for execution
  • odbc_primarykeys — Gets the primary keys for a table
  • odbc_procedurecolumns — Retrieve information about parameters to procedures
  • odbc_procedures — Get the list of procedures stored in a specific data source
  • odbc_result_all — Print result as HTML table
  • odbc_result — Get result data
  • odbc_rollback — Rollback a transaction
  • odbc_setoption — Adjust ODBC settings
  • odbc_specialcolumns — Retrieves special columns
  • odbc_statistics — Retrieve statistics about a table
  • odbc_tableprivileges — Lists tables and the privileges associated with each table
  • odbc_tables — Get the list of table names stored in a specific data source
Predefined Constants
odbc_autocommit
ODBC


vpopmail Functions

Table of Contents

  • vpopmail_add_alias_domain_ex — Add alias to an existing virtual domain
  • vpopmail_add_alias_domain — Add an alias for a virtual domain
  • vpopmail_add_domain_ex — Add a new virtual domain
  • vpopmail_add_domain — Add a new virtual domain
  • vpopmail_add_user — Add a new user to the specified virtual domain
  • vpopmail_alias_add — Insert a virtual alias
  • vpopmail_alias_del_domain — Deletes all virtual aliases of a domain
  • vpopmail_alias_del — Deletes all virtual aliases of a user
  • vpopmail_alias_get_all — Get all lines of an alias for a domain
  • vpopmail_alias_get — Get all lines of an alias for a domain
  • vpopmail_auth_user — Attempt to validate a username/domain/password
  • vpopmail_del_domain_ex — Delete a virtual domain
  • vpopmail_del_domain — Delete a virtual domain
  • vpopmail_del_user — Delete a user from a virtual domain
  • vpopmail_error — Get text message for last vpopmail error
  • vpopmail_passwd — Change a virtual user's password
  • vpopmail_set_user_quota — Sets a virtual user's quota
Predefined Constants
vpopmail_add_alias_domain_ex
vpopmail


WinCache Functions

Table of Contents

  • wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo — Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
  • wincache_refresh_if_changed — Refreshes the cache entries for the cached files
  • wincache_rplist_fileinfo — Retrieves information about resolve file path cache
  • wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
Predefined Constants
wincache_fcache_fileinfo
WinCache


xattr Functions

Table of Contents

  • xattr_get — Get an extended attribute
  • xattr_list — Get a list of extended attributes
  • xattr_remove — Remove an extended attribute
  • xattr_set — Set an extended attribute
  • xattr_supported — Check if filesystem supports extended attributes
Predefined Constants
xattr_get
xattr


xdiff Functions

Table of Contents

  • xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
  • xdiff_file_bdiff — Make binary diff of two files
  • xdiff_file_bpatch — Patch a file with a binary diff
  • xdiff_file_diff_binary — Alias of xdiff_file_bdiff
  • xdiff_file_diff — Make unified diff of two files
  • xdiff_file_merge3 — Merge 3 files into one
  • xdiff_file_patch_binary — Alias of xdiff_file_bpatch
  • xdiff_file_patch — Patch a file with an unified diff
  • xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
  • xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
  • xdiff_string_bdiff — Make binary diff of two strings
  • xdiff_string_bpatch — Patch a string with a binary diff
  • xdiff_string_diff_binary — Alias of xdiff_string_bdiff
  • xdiff_string_diff — Make unified diff of two strings
  • xdiff_string_merge3 — Merge 3 strings into one
  • xdiff_string_patch_binary — Alias of xdiff_string_bpatch
  • xdiff_string_patch — Patch a string with an unified diff
  • xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
Predefined Constants
xdiff_file_bdiff_size
xdiff


Zip Functions

Table of Contents

  • zip_close — Close a ZIP file archive
  • zip_entry_close — Close a directory entry
  • zip_entry_compressedsize — Retrieve the compressed size of a directory entry
  • zip_entry_compressionmethod — Retrieve the compression method of a directory entry
  • zip_entry_filesize — Retrieve the actual file size of a directory entry
  • zip_entry_name — Retrieve the name of a directory entry
  • zip_entry_open — Open a directory entry for reading
  • zip_entry_read — Read from an open directory entry
  • zip_open — Open a ZIP file archive
  • zip_read — Read next entry in a ZIP file archive
ZipArchive::unchangeName
zip_close
Zip


Zlib Functions

Table of Contents

  • gzclose — Close an open gz-file pointer
  • gzcompress — Compress a string
  • gzdecode — Decodes a gzip compressed string
  • gzdeflate — Deflate a string
  • gzencode — Create a gzip compressed string
  • gzeof — Test for EOF on a gz-file pointer
  • gzfile — Read entire gz-file into an array
  • gzgetc — Get character from gz-file pointer
  • gzgets — Get line from file pointer
  • gzgetss — Get line from gz-file pointer and strip HTML tags
  • gzinflate — Inflate a deflated string
  • gzopen — Open gz-file
  • gzpassthru — Output all remaining data on a gz-file pointer
  • gzputs — Alias of gzwrite
  • gzread — Binary-safe gz-file read
  • gzrewind — Rewind the position of a gz-file pointer
  • gzseek — Seek on a gz-file pointer
  • gztell — Tell gz-file pointer read/write position
  • gzuncompress — Uncompress a compressed string
  • gzwrite — Binary-safe gz-file write
  • readgzfile — Output a gz-file
  • zlib_get_coding_type — Returns the coding type used for output compression
Examples
gzclose
Zlib


Other Basic Extensions

  • GeoIP — Geo IP Location
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • GeoIP Functions
  • JSON — JavaScript Object Notation
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • JSON Functions
  • Misc. — Miscellaneous Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Misc. Functions
  • Parsekit
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Parsekit Functions
  • SPL — Standard PHP Library (SPL)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Datastructures
    • Iterators
    • Interfaces
    • Exceptions
    • SPL Functions
    • File Handling
    • Miscellaneous Classes and Interfaces
  • SPL Types — SPL Type Handling
    • Introduction
    • SplInt — The SplInt class
    • SplFloat — The SplFloat class
    • SplEnum — The SplEnum class
    • SplBool — The SplBool class
    • SplString — The SplString class
  • Streams
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Stream Filters
    • Stream Contexts
    • Stream Errors
    • Examples
    • streamWrapper — The streamWrapper class
    • Stream Functions
  • Tidy
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Tidy — The Tidy class
    • TidyNode — The TidyNode class
    • Tidy Functions
  • Tokenizer
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Tokenizer Functions
  • URLs
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • URL Functions
  • Yaml — YAML Data Serialization
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Yaml Functions
shmop_write
GeoIP
Function Reference


Affecting PHP's Behaviour

  • APC — Alternative PHP Cache
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • APC Functions
  • APD — Advanced PHP debugger
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • APD Functions
  • bcompiler — PHP bytecode Compiler
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • bcompiler Functions
  • Error Handling — Error Handling and Logging
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Error Handling Functions
  • htscanner — htaccess-like support for all SAPIs
    • Introduction
    • Installing/Configuring
  • inclued — Inclusion hierarchy viewer
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • inclued Functions
  • PHP Options/Info — PHP Options and Information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • PHP Options/Info Functions
  • Memtrack
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
  • Object overloading — Object property and method call overloading
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Object overloading Functions
  • Output Control — Output Buffering Control
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Output Control Functions
  • runkit
    • Introduction
    • Predefined Constants
    • Installing/Configuring
    • runkit Functions
  • scream — Break the silence operator
    • Introduction
    • Installing/Configuring
    • Examples
  • WinCache — Windows Cache for PHP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • WinCache Functions
    • Building for Windows
Function Reference
APC
Function Reference


Date and Time Related Extensions

  • Calendar
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Calendar Functions
  • Date/Time — Date and Time
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • List of Supported Timezones
    • DateTime — The DateTime class
    • DateTimeZone — The DateTimeZone class
    • DateInterval — The DateInterval class
    • DatePeriod — The DatePeriod class
    • Date/Time Functions
radius_strerror
Calendar
Function Reference


Compression and Archive Extensions

  • Bzip2
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Bzip2 Functions
  • LZF
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • LZF Functions
  • Phar
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Using Phar Archives
    • Creating Phar Archives
    • What makes a phar a phar and not a tar or a zip?
    • Phar — The Phar class
    • PharData — The PharData class
    • PharFileInfo — The PharFileInfo class
    • PharException — The PharException class
  • Rar — Rar Archiving
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • RarArchive — The RarArchive class
    • RarEntry — The RarEntry class
    • RarException — The RarException class
  • Zip
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • ZipArchive — The ZipArchive class
    • Zip Functions
  • Zlib — Zlib Compression
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Zlib Functions
readline
Bzip2
Function Reference


Credit Card Processing

  • MCVE — MCVE (Monetra) Payment
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • MCVE Functions
  • SPPLUS — SPPLUS Payment System
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SPPLUS Functions
zlib_get_coding_type
MCVE
Function Reference


Cryptography Extensions

  • Crack — Cracklib
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Crack Functions
  • Hash — HASH Message Digest Framework
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Hash Functions
  • Mcrypt
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mcrypt ciphers
    • Examples
    • Mcrypt Functions
  • Mhash
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Mhash Functions
  • OpenSSL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Key/Certificate parameters
    • Certificate Verification
    • OpenSSL Functions
signeurlpaiement
Crack
Function Reference


Database Extensions

  • Abstraction Layers
    • DBA — Database (dbm-style) Abstraction Layer
    • dbx
    • ODBC — ODBC (Unified)
    • PDO — PHP Data Objects
  • Vendor Specific Database Extensions
    • dBase
    • DB++
    • FrontBase
    • filePro
    • Firebird/InterBase
    • Informix
    • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • Ingres — Ingres DBMS, EDBC, and Enterprise Access Gateways
    • MaxDB
    • Mongo
    • mSQL
    • Mssql — Microsoft SQL Server
    • MySQL
    • Mysqli — MySQL Improved Extension
    • Mysqlnd — MySQL Native Driver
    • OCI8 — Oracle OCI8
    • Ovrimos SQL
    • Paradox — Paradox File Access
    • PostgreSQL
    • SQLite
    • SQLite3
    • Sybase
    • tokyo_tyrant
openssl_x509_read
Abstraction Layers
Function Reference


Abstraction Layers

  • DBA — Database (dbm-style) Abstraction Layer
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • DBA Functions
  • dbx
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • dbx Functions
  • ODBC — ODBC (Unified)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • ODBC Functions
  • PDO — PHP Data Objects
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Connections and Connection management
    • Transactions and auto-commit
    • Prepared statements and stored procedures
    • Errors and error handling
    • Large Objects (LOBs)
    • PDO — The PDO class
    • PDOStatement — The PDOStatement class
    • PDOException — The PDOException class
    • PDO Drivers
Database Extensions
DBA
Database Extensions


Vendor Specific Database Extensions

  • dBase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • dBase Functions
  • DB++
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • DB++ Functions
  • FrontBase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • FrontBase Functions
  • filePro
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • filePro Functions
  • Firebird/InterBase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Firebird/InterBase Functions
  • Informix
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Informix Functions
  • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • IBM DB2 Functions
  • Ingres — Ingres DBMS, EDBC, and Enterprise Access Gateways
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Ingres Functions
  • MaxDB
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • MaxDB Functions
  • Mongo
    • Manual
    • Core Classes
    • Types
    • GridFS Classes
    • Functions
    • Exceptions
  • mSQL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • mSQL Functions
  • Mssql — Microsoft SQL Server
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mssql Functions
  • MySQL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • MySQL Functions
  • Mysqli — MySQL Improved Extension
    • Introduction
    • Overview
    • Installing/Configuring
    • The mysqli Extension and Persistent Connections
    • Predefined Constants
    • The MySQLi Extension Function Summary
    • MySQLi — The MySQLi class
    • MySQLi_STMT — The MySQLi_STMT class
    • MySQLi_Result — The MySQLi_Result class
    • MySQLi_Driver — The MySQLi_Driver class
    • MySQLi_Warning — The MySQLi_Warning class
    • Aliases and deprecated Mysqli Functions
  • Mysqlnd — MySQL Native Driver
    • Introduction
    • Overview
    • Installation
    • Configuration
    • Persistent Connections
    • Statistics
    • Notes
  • OCI8 — Oracle OCI8
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Connection Handling
    • Supported Datatypes
    • OCI8 Functions
    • OCI8 Obsolete Aliases and Functions
  • Ovrimos SQL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Ovrimos SQL Functions
  • Paradox — Paradox File Access
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Paradox Functions
  • PostgreSQL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PostgreSQL Functions
  • SQLite
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SQLite Functions
  • SQLite3
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SQLite3 — The SQLite3 class
    • SQLite3Stmt — The SQLite3Stmt class
    • SQLite3Result — The SQLite3Result class
  • Sybase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Sybase Functions
  • tokyo_tyrant
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • TokyoTyrant — The TokyoTyrant class
    • TokyoTyrantTable — The TokyoTyrantTable class
    • TokyoTyrantQuery — The TokyoTyrantQuery class
Examples with PDO_4D
dBase
Database Extensions


File System Related Extensions

  • Direct IO
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Direct IO Functions
  • Directories
    • Installing/Configuring
    • Predefined Constants
    • Directory Functions
  • Fileinfo — File Information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Fileinfo Functions
  • Filesystem
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Filesystem Functions
  • Inotify
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Inotify Functions
  • Mimetype
    • Introduction
    • Installing/Configuring
    • Predefined Constants
  • xattr
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • xattr Functions
  • xdiff
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • xdiff Functions
TokyoTyrantQuery::valid
Direct IO
Function Reference


Process Control Extensions

  • Program execution — System program execution
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Program execution Functions
  • Expect
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Expect Functions
  • Libevent
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Libevent Functions
  • PCNTL — Process Control
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PCNTL Functions
  • POSIX
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • POSIX Functions
  • Semaphore — Semaphore, Shared Memory and IPC
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Semaphore Functions
  • Shared Memory
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Shared Memory Functions
swf_viewport
Program execution
Function Reference


Human Language and Character Encoding Support

  • Enchant — Enchant spelling library
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Enchant Functions
  • FriBiDi
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • FriBiDi Functions
  • Gettext
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Gettext Functions
  • i18n — Internationalization
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • i18n Functions
  • iconv
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • iconv Functions
  • intl — Internationalization Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Collator — The Collator class
    • NumberFormatter — The NumberFormatter class
    • Locale — The Locale class
    • Normalizer — The Normalizer class
    • MessageFormatter — The MessageFormatter class
    • IntlDateFormatter — The IntlDateFormatter class
    • ResourceBundle — The ResourceBundle class
    • Grapheme Functions
    • IDN Functions
    • intl Functions
  • Multibyte String
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Summaries of supported encodings
    • Basics of Japanese multi-byte encodings
    • HTTP Input and Output
    • Supported Character Encodings
    • Function Overloading Feature
    • PHP Character Encoding Requirements
    • Multibyte String Functions
  • Pspell
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Pspell Functions
  • Recode — GNU Recode
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Recode Functions
  • Unicode
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Unicode Functions
xdiff_string_rabdiff
Enchant
Function Reference


Mathematical Extensions

  • BC Math — BCMath Arbitrary Precision Mathematics
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • BC Math Functions
  • GMP — GNU Multiple Precision
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GMP Functions
  • Math — Mathematical Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Math Functions
  • Statistics
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Statistic Functions
vpopmail_set_user_quota
BC Math
Function Reference


Authentication Services

  • KADM5 — Kerberos V
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • KADM5 Functions
  • Radius
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Radius Functions
openal_stream
KADM5
Function Reference


Mail Related Extensions

  • Cyrus — Cyrus IMAP administration
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Cyrus Functions
  • IMAP — IMAP, POP3 and NNTP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • IMAP Functions
  • Mail
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mail Functions
  • Mailparse
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mailparse Functions
  • vpopmail
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • vpopmail Functions
CairoSvgVersion
Cyrus
Function Reference


Audio Formats Manipulation

  • ID3 — ID3 Tags
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • ID3 Functions
  • KTaglib
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • KTaglib_MPEG_File — The KTagLib_MPEG_File class
    • KTaglib_MPEG_AudioProperties — The KTaglib_MPEG_AudioProperties class
    • KTaglib_Tag — The KTaglib_Tag class
    • KTaglib_ID3v2_Tag — The KTagLib_ID3v2_Tag class
    • KTaglib_ID3v2_Frame — The KTagLib_ID3v2_Frame class
    • KTaglib_ID3v2_AttachedPictureFrame — The KTaglib_ID3v2_AttachedPictureFrame class
  • oggvorbis — OGG/Vorbis
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Context options
    • Examples
  • OpenAL — OpenAL Audio Bindings
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • OpenAL Functions
Verifying the build
ID3
Function Reference


Command Line Specific Extensions

  • Newt
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Newt Functions
  • Ncurses — Ncurses Terminal Screen Control
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Ncurses Functions
  • Readline — GNU Readline
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Readline Functions
timezone_version_get
Newt
Function Reference


Image Processing and Generation

  • Exif — Exchangeable image information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Exif Functions
  • GD — Image Processing and GD
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GD and Image Functions
  • ImageMagick — Image Processing (ImageMagick)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • The Imagick class
    • The ImagickDraw class
    • The ImagickPixel class
    • The ImagickPixelIterator class
  • Gmagick
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Gmagick — The Gmagick class
    • GmagickDraw — The GmagickDraw class
    • GmagickPixel — The GmagickPixel class
  • Cairo
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Cairo Functions
    • Cairo — The Cairo class
    • CairoContext — The CairoContext class
    • CairoException — The CairoException class
    • CairoStatus — The CairoStatus class
    • CairoSurface — The CairoSurface class
    • CairoSvgSurface — Svg Surface Backend
    • CairoImageSurface — The CairoImageSurface class
    • CairoPdfSurface — The CairoPdfSurface class
    • CairoPsSurface — The CairoPsSurface class
    • CairoSurfaceType — The CairoSurfaceType class
    • CairoFontFace — The CairoFontFace class
    • CairoFontOptions — The CairoFontOptions class
    • CairoFontSlant — The CairoFontSlant class
    • CairoFontType — The CairoFontType class
    • CairoFontWeight — The CairoFontWeight class
    • CairoScaledFont — The CairoScaledFont class
    • CairoToyFontFace — The CairoToyFontFace class
    • CairoPatternType — The CairoPatternType class
    • CairoPattern — The CairoPattern class
    • CairoGradientPattern — The CairoGradientPattern class
    • CairoSolidPattern — The CairoSolidPattern class
    • CairoSurfacePattern — The CairoSurfacePattern class
    • CairoLinearGradient — The CairoLinearGradient class
    • CairoRadialGradient — The CairoRadialGradient class
    • CairoAntialias — The CairoAntialias class
    • CairoContent — The CairoContent class
    • CairoExtend — The CairoExtend class
    • CairoFormat — The CairoFormat class
    • CairoFillRule — The CairoFillRule class
    • CairoFilter — The CairoFilter class
    • CairoHintMetrics — The CairoHintMetrics class
    • CairoHintStyle — The CairoHintStyle class
    • CairoLineCap — The CairoLineCap class
    • CairoLineJoin — The CairoLineJoin class
    • CairoMatrix — The CairoMatrix class
    • CairoOperator — The CairoOperator class
    • CairoPath — The CairoPath class
    • CairoPsLevel — The CairoPsLevel class
    • CairoSubpixelOrder — The CairoSubpixelOrder class
    • CairoSvgVersion — The CairoSvgVersion class
unicode_set_subst_char
Exif
Function Reference


Non-Text MIME Output

  • FDF — Forms Data Format
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • FDF Functions
  • GnuPG — GNU Privacy Guard
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GnuPG Functions
  • haru — Haru PDF
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Builtin Fonts And Encodings
    • HaruException — The HaruException class
    • HaruDoc — The HaruDoc class
    • HaruPage — The HaruPage class
    • HaruFont — The HaruFont class
    • HaruImage — The HaruImage class
    • HaruEncoder — The HaruEncoder class
    • HaruOutline — The HaruOutline class
    • HaruAnnotation — The HaruAnnotation class
    • HaruDestination — The HaruDestination class
  • Ming — Ming (flash)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Ming Functions
    • SWFAction — The SWFAction class
    • SWFBitmap — The SWFBitmap class
    • SWFButton — The SWFButton class
    • SWFDisplayItem — The SWFDisplayItem class
    • SWFFill — The SWFFill class
    • SWFFont — The SWFFont class
    • SWFFontChar — The SWFFontChar class
    • SWFGradient — The SWFGradient class
    • SWFMorph — The SWFMorph class
    • SWFMovie — The SWFMovie class
    • SWFPrebuiltClip — The SWFPrebuiltClip class
    • SWFShape — The SWFShape class
    • SWFSound — The SWFSound class
    • SWFSoundInstance — The SWFSoundInstance class
    • SWFSprite — The SWFSprite class
    • SWFText — The SWFText class
    • SWFTextField — The SWFTextField class
    • SWFVideoStream — The SWFVideoStream class
  • PDF
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PDF Functions
  • PS — PostScript document creation
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • PS Functions
  • RPM Reader — RPM Header Reading
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • RPM Reader Functions
  • SWF — Shockwave Flash
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • SWF Functions
stats_variance
FDF
Function Reference


Predefined Exceptions

Table of Contents

  • Exception
  • ErrorException

See also the SPL Exceptions

$argv
Exception
Language Reference


Predefined Interfaces

Table of Contents

  • The Traversable interface
  • The Iterator interface
  • The IteratorAggregate interface
  • The ArrayAccess interface
  • The Serializable interface

See also the SPL Interfaces

ErrorException::getSeverity
Traversable
Language Reference


Predefined Variables

PHP provides a large number of predefined variables to all scripts. The variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers.

See also the FAQ titled "How does register_globals affect me?"

Table of Contents

  • Superglobals — Superglobals are built-in variables that are always available in all scopes
  • $GLOBALS — References all variables available in global scope
  • $_SERVER — Server and execution environment information
  • $_GET — HTTP GET variables
  • $_POST — HTTP POST variables
  • $_FILES — HTTP File Upload variables
  • $_REQUEST — HTTP Request variables
  • $_SESSION — Session variables
  • $_ENV — Environment variables
  • $_COOKIE — HTTP Cookies
  • $php_errormsg — The previous error message
  • $HTTP_RAW_POST_DATA — Raw POST data
  • $http_response_header — HTTP response headers
  • $argc — The number of arguments passed to script
  • $argv — Array of arguments passed to script
Spotting References
Superglobals
Language Reference


The number of arguments passed to script

$http_response_header
$argv
Predefined Variables
PHP Manual

$argc

$argc — The number of arguments passed to script

Description

Contains the number of arguments passed to the current script when running from the command line.

Note: The script's filename is always passed as an argument to the script, therefore the minimum value of $argc is 1.

Note: This variable is only available when register_argc_argv is enabled.

Examples

Example #1 $argc example

<?php
var_dump($argc);
?>

When executing the example with: php script.php arg1 arg2 arg3

The above example will output something similar to:

int(4)

$http_response_header
$argv
Predefined Variables


Array of arguments passed to script

$argc
Predefined Exceptions
Predefined Variables
PHP Manual

$argv

$argv — Array of arguments passed to script

Description

Contains an array of all the arguments passed to the script when running from the command line.

Note: The first argument is always the current script's filename, therefore $argv[0] is the script's name.

Note: This variable is only available when register_argc_argv is enabled.

Examples

Example #1 $argv example

<?php
var_dump($argv);
?>

When executing the example with: php script.php arg1 arg2 arg3

The above example will output something similar to:

array(4) {
  [0]=>
  string(10) "script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}

$argc
Predefined Exceptions
Predefined Variables


HTTP Cookies

$_ENV
$php_errormsg
Predefined Variables
PHP Manual

$_COOKIE

$HTTP_COOKIE_VARS [deprecated]

$_COOKIE -- $HTTP_COOKIE_VARS [deprecated] — HTTP Cookies

Description

An associative array of variables passed to the current script via HTTP Cookies.

$HTTP_COOKIE_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_COOKIE_VARS and $_COOKIE are different variables and that PHP handles them as such)

Changelog

Version | Description
4.1.0 | Introduced $_COOKIE that deprecated $HTTP_COOKIE_VARS.

Examples

Example #1 $_COOKIE example

<?php
echo 'Hello ' . htmlspecialchars($_COOKIE["name"]) . '!';
?>

Assuming the "name" cookie has been set earlier

The above example will output something similar to:

Hello Hannes!

Notes

Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • setcookie() - Send a cookie
  • Handling external variables
  • The filter extension

$_ENV
$php_errormsg
Predefined Variables


Environment variables

$_SESSION
$_COOKIE
Predefined Variables
PHP Manual

$_ENV

$HTTP_ENV_VARS [deprecated]

$_ENV -- $HTTP_ENV_VARS [deprecated] — Environment variables

Description

An associative array of variables passed to the current script via the environment method.

These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables.

Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.

$HTTP_ENV_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such)

Changelog

Version | Description
4.1.0 | Introduced $_ENV that deprecated $HTTP_ENV_VARS.

Examples

Example #1 $_ENV example

<?php
echo 'My username is ' .$_ENV["USER"] . '!';
?>

Assuming "bjori" executes this script

The above example will output something similar to:

My username is bjori!

Notes

Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • getenv() - Gets the value of an environment variable
  • The filter extension

$_SESSION
$_COOKIE
Predefined Variables


HTTP File Upload variables

$_POST
$_REQUEST
Predefined Variables
PHP Manual

$_FILES

$HTTP_POST_FILES [deprecated]

$_FILES -- $HTTP_POST_FILES [deprecated] — HTTP File Upload variables

Description

An associative array of items uploaded to the current script via the HTTP POST method.

$HTTP_POST_FILES contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such)

Changelog

Version | Description
4.1.0 | Introduced $_FILES that deprecated $HTTP_POST_FILES.

Notes

Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • move_uploaded_file() - Moves an uploaded file to a new location
  • Handling File Uploads

$_POST
$_REQUEST
Predefined Variables


HTTP GET variables

$_SERVER
$_POST
Predefined Variables
PHP Manual

$_GET

$HTTP_GET_VARS [deprecated]

$_GET -- $HTTP_GET_VARS [deprecated] — HTTP GET variables

Description

An associative array of variables passed to the current script via the URL parameters.

$HTTP_GET_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)

Changelog

Version | Description
4.1.0 | Introduced $_GET that deprecated $HTTP_GET_VARS.

Examples

Example #1 $_GET example

<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>

Assuming the user entered http://example.com/?name=Hannes

The above example will output something similar to:

Hello Hannes!

Notes

Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • Handling external variables
  • The filter extension

$_SERVER
$_POST
Predefined Variables


References all variables available in global scope

Superglobals
$_SERVER
Predefined Variables
PHP Manual

$GLOBALS

$GLOBALS — References all variables available in global scope

Description

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

Examples

Example #1 $GLOBALS example

<?php
function test() {
    $foo = "local variable";

    echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
    echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Example content";
test();
?>

The above example will output something similar to:

$foo in global scope: Example content
$foo in current scope: local variable

Notes

Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

Note: Variable availability
Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP.

Superglobals
$_SERVER
Predefined Variables


Raw POST data

$php_errormsg
$http_response_header
Predefined Variables
PHP Manual

$HTTP_RAW_POST_DATA

$HTTP_RAW_POST_DATA — Raw POST data

Description

$HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data

$php_errormsg
$http_response_header
Predefined Variables


HTTP response headers

$HTTP_RAW_POST_DATA
$argc
Predefined Variables
PHP Manual

$http_response_header

$http_response_header — HTTP response headers

Description

The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers.

Examples

Example #1 $http_response_header example

<?php
file_get_contents("http://example.com");
var_dump($http_response_header);
?>

The above example will output something similar to:

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}

$HTTP_RAW_POST_DATA
$argc
Predefined Variables


The previous error message

$_COOKIE
$HTTP_RAW_POST_DATA
Predefined Variables
PHP Manual

$php_errormsg

$php_errormsg — The previous error message

Description

$php_errormsg is a variable containing the text of the last error message generated by PHP. This variable will only be available within the scope in which the error occurred, and only if the track_errors configuration option is turned on (it defaults to off).

Note: This variable is only available when track_errors is enabled in php.ini.

Warning

If a user defined error handler (set_error_handler()) is set $php_errormsg is only set if the error handler returns FALSE

Examples

Example #1 $php_errormsg example

<?php
@strpos();
echo $php_errormsg;
?>

The above example will output something similar to:

Wrong parameter count for strpos()

$_COOKIE
$HTTP_RAW_POST_DATA
Predefined Variables


HTTP POST variables

$_GET
$_FILES
Predefined Variables
PHP Manual

$_POST

$HTTP_POST_VARS [deprecated]

$_POST -- $HTTP_POST_VARS [deprecated] — HTTP POST variables

Description

An associative array of variables passed to the current script via the HTTP POST method.

$HTTP_POST_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)

Changelog

Version | Description
4.1.0 | Introduced $_POST that deprecated $HTTP_POST_VARS.

Examples

Example #1 $_POST example

<?php
echo 'Hello ' . htmlspecialchars($_POST["name"]) . '!';
?>

Assuming the user POSTed name=Hannes

The above example will output something similar to:

Hello Hannes!

Notes

Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • Handling external variables
  • The filter extension

$_GET
$_FILES
Predefined Variables


HTTP Request variables

$_FILES
$_SESSION
Predefined Variables
PHP Manual

$_REQUEST

$_REQUEST — HTTP Request variables

Description

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.

Changelog

Version | Description
5.3.0 | Introduced request_order. This directive affects the contents of $_REQUEST.
4.3.0 | $_FILES information was removed from $_REQUEST.
4.1.0 | Introduced $_REQUEST.

Notes

Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

Note: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.

Note: The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and therefore could be modified by the remote user and cannot be trusted. The presence and order of variables listed in this array is defined according to the PHP variables_order configuration directive.

See Also

  • import_request_variables() - Import GET/POST/Cookie variables into the global scope
  • Handling external variables
  • The filter extension
$_FILES
$_SESSION
Predefined Variables


Server and execution environment information

$GLOBALS
$_GET
Predefined Variables
PHP Manual

$_SERVER

$HTTP_SERVER_VARS [deprecated]

$_SERVER -- $HTTP_SERVER_VARS [deprecated] — Server and execution environment information

Description

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI 1.1 specification, so you should be able to expect those.

$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)

Indices

You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.

'PHP_SELF'
The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
'argv'
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
'argc'
Contains the number of command line parameters passed to the script (if run on the command line).
'GATEWAY_INTERFACE'
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
'SERVER_ADDR'
The IP address of the server under which the current script is executing.
'SERVER_NAME'
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_SOFTWARE'
Server identification string, given in the headers when responding to requests.
'SERVER_PROTOCOL'
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
'REQUEST_METHOD'
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

Note: PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.

'REQUEST_TIME'
The timestamp of the start of the request. Available since PHP 5.1.0.
'QUERY_STRING'
The query string, if any, via which the page was accessed.
'DOCUMENT_ROOT'
The document root directory under which the current script is executing, as defined in the server's configuration file.
'HTTP_ACCEPT'
Contents of the Accept: header from the current request, if there is one.
'HTTP_ACCEPT_CHARSET'
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
'HTTP_ACCEPT_ENCODING'
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
'HTTP_ACCEPT_LANGUAGE'
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
'HTTP_CONNECTION'
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
'HTTP_HOST'
Contents of the Host: header from the current request, if there is one.
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
'HTTP_USER_AGENT'
Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.
'HTTPS'
Set to a non-empty value if the script was queried through the HTTPS protocol.

Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.

'REMOTE_ADDR'
The IP address from which the user is viewing the current page.
'REMOTE_HOST'
The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.

Note: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

'REMOTE_PORT'
The port being used on the user's machine to communicate with the web server.
'SCRIPT_FILENAME'

The absolute pathname of the currently executing script.

Note: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.

'SERVER_ADMIN'
The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_PORT'
The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
'SERVER_SIGNATURE'
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
'PATH_TRANSLATED'
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.

'SCRIPT_NAME'
Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
'REQUEST_URI'
The URI which was given in order to access this page; for instance, '/index.html'.
'PHP_AUTH_DIGEST'
When running under Apache as module doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).
'PHP_AUTH_USER'
When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the username provided by the user.
'PHP_AUTH_PW'
When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the password provided by the user.
'AUTH_TYPE'
When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.
'PATH_INFO'
Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff.
'ORIG_PATH_INFO'
Original version of 'PATH_INFO' before processed by PHP.

Changelog

Version | Description
4.1.0 | Introduced $_SERVER that deprecated $HTTP_SERVER_VARS.

Examples

Example #1 $_SERVER example

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

The above example will output something similar to:

www.example.com

Notes

Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • The filter extension

$GLOBALS
$_GET
Predefined Variables


Session variables

$_REQUEST
$_ENV
Predefined Variables
PHP Manual

$_SESSION

$HTTP_SESSION_VARS [deprecated]

$_SESSION -- $HTTP_SESSION_VARS [deprecated] — Session variables

Description

An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.

$HTTP_SESSION_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such)

Changelog

Version | Description
4.1.0 | Introduced $_SESSION that deprecated $HTTP_SESSION_VARS.

Notes

Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

  • session_start() - Initialize session data

$_REQUEST
$_ENV
Predefined Variables


Get number of elements in the bundle

ResourceBundle
ResourceBundle::create
ResourceBundle
PHP Manual

ResourceBundle::count

resourcebundle_count

(No version information available, might only be in SVN)

ResourceBundle::count -- resourcebundle_count — Get number of elements in the bundle

Description

Object oriented style

int ResourceBundle::count ( void )

Procedural style

int resourcebundle_count ( ResourceBundle $r )

Get the number of elements in the bundle.

Parameters

r

ResourceBundle object.

Return Values

Returns number of elements in the bundle.

Examples

Example #1 resourcebundle_count() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_count($r);
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->count();
?>

The above example will output:

42

See Also

  • resourcebundle_get() - Get data from the bundle

ResourceBundle
ResourceBundle::create
ResourceBundle


Create a resource bundle

ResourceBundle::count
ResourceBundle::getErrorCode
ResourceBundle
PHP Manual

ResourceBundle::create

resourcebundle_create

ResourceBundle::__construct

(No version information available, might only be in SVN)

ResourceBundle::create -- resourcebundle_create -- ResourceBundle::__construct — Create a resource bundle

Description

Object oriented style (method)

static ResourceBundle ResourceBundle::create ( string $locale , string $bundlename [, bool $fallback ] )

Procedural style

ResourceBundle resourcebundle_create ( string $locale , string $bundlename [, bool $fallback ] )

Object oriented style (constructor):

ResourceBundle::__construct ( string $locale , string $bundlename [, bool $fallback ] )

Creates a resource bundle.

Parameters

locale

Locale for which the resources should be loaded (locale name, e.g. en_CA).

bundlename

The directory where the data is stored or the name of the .dat file.

fallback

Whether locale should match exactly or fallback to parent locale is allowed.

Return Values

Returns ResourceBundle object or FALSE on error.

Examples

Example #1 resourcebundle_create() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>

Example #2 ResourceBundle::create() example

<?php
$r = ResourceBundle::create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>

The above example will output:

¡Hola, mundo!

See Also

  • resourcebundle_get() - Get data from the bundle

ResourceBundle::count
ResourceBundle::getErrorCode
ResourceBundle


Get data from the bundle

ResourceBundle::getErrorMessage
ResourceBundle::getLocales
ResourceBundle
PHP Manual

ResourceBundle::get

resourcebundle_get

(No version information available, might only be in SVN)

ResourceBundle::get -- resourcebundle_get — Get data from the bundle

Description

Object oriented style

mixed ResourceBundle::get ( string|int $index )

Procedural style

mixed resourcebundle_get ( ResourceBundle $r , string|int $index )

Get the data from the bundle by index or string key.

Parameters

r

ResourceBundle object.

index

Data index, must be string or integer.

Return Values

Returns the data located at the index or NULL on error. Strings, integers and binary data strings are returned as corresponding PHP types, integer array is returned as PHP array. Complex types are returned as ResourceBundle object.

Examples

Example #1 resourcebundle_get() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_get($r, 'somestring');
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->get('somestring');
?>

The above example will output:

?Hola, mundo!

See Also

  • resourcebundle_count() - Get number of elements in the bundle

ResourceBundle::getErrorMessage
ResourceBundle::getLocales
ResourceBundle


Get bundle's last error code.

ResourceBundle::create
ResourceBundle::getErrorMessage
ResourceBundle
PHP Manual

ResourceBundle::getErrorCode

resourcebundle_get_error_code

(No version information available, might only be in SVN)

ResourceBundle::getErrorCode -- resourcebundle_get_error_code — Get bundle's last error code.

Description

Object oriented style

int ResourceBundle::getErrorCode ( void )

Procedural style

int resourcebundle_get_error_code ( ResourceBundle $r )

Get error code from the last function performed by the bundle object.

Parameters

r

ResourceBundle object.

Return Values

Returns error code from last bundle object call.

Examples

Example #1 resourcebundle_get_error_code() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(resourcebundle_get_error_code($r))) {
    report_error("Bundle error");
}
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(ResourceBundle::getErrorCode($r))) {
    report_error("Bundle error");
}
?>

See Also

  • resourcebundle_get_error_message() - Get bundle's last error message.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

ResourceBundle::create
ResourceBundle::getErrorMessage
ResourceBundle


Get bundle's last error message.

ResourceBundle::getErrorCode
ResourceBundle::get
ResourceBundle
PHP Manual

ResourceBundle::getErrorMessage

resourcebundle_get_error_message

(No version information available, might only be in SVN)

ResourceBundle::getErrorMessage -- resourcebundle_get_error_message — Get bundle's last error message.

Description

Object oriented style

string ResourceBundle::getErrorMessage ( void )

Procedural style

string resourcebundle_get_error_message ( ResourceBundle $r )

Get error message from the last function performed by the bundle object.

Parameters

r

ResourceBundle object.

Return Values

Returns error message from last bundle object's call.

Examples

Example #1 resourcebundle_get_error_message() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(resourcebundle_get_error_code($r))) {
    report_error("Bundle error: ".resourcebundle_get_error_message($r));
}
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(ResourceBundle::getErrorCode($r))) {
    report_error("Bundle error: ".ResourceBundle::getErrorMessage($r));
}
?>

See Also

  • resourcebundle_get_error_code() - Get bundle's last error code.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

ResourceBundle::getErrorCode
ResourceBundle::get
ResourceBundle


Get supported locales

ResourceBundle::get
Grapheme Functions
ResourceBundle
PHP Manual

ResourceBundle::getLocales

resourcebundle_locales

(No version information available, might only be in SVN)

ResourceBundle::getLocales -- resourcebundle_locales — Get supported locales

Description

Object oriented style

array ResourceBundle::getLocales ( void )

Procedural style

array resourcebundle_locales ( ResourceBundle $r )

Get the list of locales supported by the bundle. The list is taken from the bundle table named res_index which should contain a table named InstalledLocales, which contains locales as keys. This bundle should be either in data directory as .res file or part of the .dat file for this function to work.

Parameters

r

ResourceBundle object.

Return Values

Returns the list of locales supported by the bundle.

Examples

Example #1 resourcebundle_locales() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo join("\n", resourcebundle_locales($r));
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo join("\n", $r->getLocales());
?>

The above example will output:

es
root

See Also

  • resourcebundle_get() - Get data from the bundle

ResourceBundle::get
Grapheme Functions
ResourceBundle


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The following list of constants are used to obtain information using the rpm_get_tag() function. These constants represent the tag number to be retrieved from the RPM file's header section. Descriptions are given below as to what data the tag number constants reference.

RPMREADER_MINIMUM (integer)
The minimum valid value of any RPM tag number.
RPMREADER_NAME (integer)
The name of the RPM package.
RPMREADER_VERSION (integer)
The version of the RPM package.
RPMREADER_RELEASE (integer)
The release of the RPM package.
RPMREADER_EPOCH (integer)
RPMREADER_SERIAL (integer)
RPMREADER_SUMMARY (integer)
The summary text of the RPM package.
RPMREADER_DESCRIPTION (integer)
The full description text of the RPM package.
RPMREADER_BUILDTIME (integer)
The date and time when the RPM package was built.
RPMREADER_BUILDHOST (integer)
The name of the host on which the RPM package was built.
RPMREADER_INSTALLTIME (integer)
RPMREADER_SIZE (integer)
The size of the RPM package.
RPMREADER_DISTRIBUTION (integer)
RPMREADER_VENDOR (integer)
RPMREADER_GIF (integer)
RPMREADER_XPM (integer)
RPMREADER_LICENSE (integer)
RPMREADER_COPYRIGHT (integer)
RPMREADER_PACKAGER (integer)
RPMREADER_GROUP (integer)
RPMREADER_SOURCE (integer)
RPMREADER_PATCH (integer)
RPMREADER_URL (integer)
RPMREADER_OS (integer)
RPMREADER_ARCH (integer)
RPMREADER_PREIN (integer)
RPMREADER_POSTIN (integer)
RPMREADER_PREUN (integer)
RPMREADER_POSTUN (integer)
RPMREADER_OLDFILENAMES (integer)
The list of files in an RPM package (deprecated format). The correct way is now to use a combination of 3 tags (RPMREADER_BASENAMES, RPMREADER_DIRINDEXES, RPMREADER_DIRNAMES) in what RPM now calls "CompressedFileNames". This tag is still used in older RPM files that did not use the "CompressedFileNames" method and is maintained for backward compatibility.
RPMREADER_FILESIZES (integer)
RPMREADER_FILESTATES (integer)
RPMREADER_FILEMODES (integer)
RPMREADER_FILERDEVS (integer)
RPMREADER_FILEMTIMES (integer)
RPMREADER_FILEMD5S (integer)
RPMREADER_FILELINKTOS (integer)
RPMREADER_FILEFLAGS (integer)
RPMREADER_FILEUSERNAME (integer)
RPMREADER_FILEGROUPNAME (integer)
RPMREADER_ICON (integer)
RPMREADER_SOURCERPM (integer)
RPMREADER_FILEVERIFYFLAGS (integer)
RPMREADER_ARCHIVESIZE (integer)
RPMREADER_PROVIDENAME (integer)
RPMREADER_PROVIDES (integer)
RPMREADER_REQUIREFLAGS (integer)
RPMREADER_REQUIRENAME (integer)
RPMREADER_REQUIREVERSION (integer)
RPMREADER_CONFLICTFLAGS (integer)
RPMREADER_CONFLICTNAME (integer)
RPMREADER_CONFLICTVERSION (integer)
RPMREADER_EXCLUDEARCH (integer)
RPMREADER_EXCLUDEOS (integer)
RPMREADER_EXCLUSIVEARCH (integer)
RPMREADER_EXCLUSIVEOS (integer)
RPMREADER_RPMVERSION (integer)
RPMREADER_TRIGGERSCRIPTS (integer)
RPMREADER_TRIGGERNAME (integer)
RPMREADER_TRIGGERVERSION (integer)
RPMREADER_TRIGGERFLAGS (integer)
RPMREADER_TRIGGERINDEX (integer)
RPMREADER_VERIFYSCRIPT (integer)
RPMREADER_CHANGELOGTIME (integer)
The list of dates from changelog entries.
RPMREADER_CHANGELOGNAME (integer)
The list of changelog entry names.
RPMREADER_CHANGELOGTEXT (integer)
The list of the text from changelog entries.
RPMREADER_PREINPROG (integer)
RPMREADER_POSTINPROG (integer)
RPMREADER_PREUNPROG (integer)
RPMREADER_POSTUNPROG (integer)
RPMREADER_BUILDARCHS (integer)
RPMREADER_OBSOLETENAME (integer)
RPMREADER_OBSOLETES (integer)
RPMREADER_VERIFYSCRIPTPROG (integer)
RPMREADER_TRIGGERSCRIPTPROG (integer)
RPMREADER_COOKIE (integer)
RPMREADER_FILEDEVICES (integer)
RPMREADER_FILEINODES (integer)
RPMREADER_FILELANGS (integer)
RPMREADER_PREFIXES (integer)
RPMREADER_INSTPREFIXES (integer)
RPMREADER_PROVIDEFLAGS (integer)
RPMREADER_PROVIDEVERSION (integer)
RPMREADER_OBSOLETEFLAGS (integer)
RPMREADER_OBSOLETEVERSION (integer)
RPMREADER_DIRINDEXES (integer)
The list of indices that relate directory names to files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
RPMREADER_BASENAMES (integer)
The list of the names of files in the RPM package without path information. This tag is used in conjunction with RPMREADER_DIRINDEXES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
RPMREADER_DIRNAMES (integer)
The list of directory names used by files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRINDEXES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
RPMREADER_OPTFLAGS (integer)
RPMREADER_DISTURL (integer)
RPMREADER_PAYLOADFORMAT (integer)
RPMREADER_PAYLOADCOMPRESSOR (integer)
RPMREADER_PAYLOADFLAGS (integer)
RPMREADER_INSTALLCOLOR (integer)
RPMREADER_INSTALLTID (integer)
RPMREADER_REMOVETID (integer)
RPMREADER_RHNPLATFORM (integer)
RPMREADER_PLATFORM (integer)
RPMREADER_PATCHESNAME (integer)
RPMREADER_PATCHESFLAGS (integer)
RPMREADER_PATCHESVERSION (integer)
RPMREADER_CACHECTIME (integer)
RPMREADER_CACHEPKGPATH (integer)
RPMREADER_CACHEPKGSIZE (integer)
RPMREADER_CACHEPKGMTIME (integer)
RPMREADER_FILECOLORS (integer)
RPMREADER_FILECLASS (integer)
RPMREADER_CLASSDICT (integer)
RPMREADER_FILEDEPENDSX (integer)
RPMREADER_FILEDEPENDSN (integer)
RPMREADER_DEPENDSDICT (integer)
RPMREADER_SOURCEPKGID (integer)
RPMREADER_FILECONTEXTS (integer)
RPMREADER_FSCONTEXTS (integer)
RPMREADER_RECONTEXTS (integer)
RPMREADER_POLICIES (integer)
RPMREADER_MAXIMUM (integer)
The maximum valid value of any RPM tag number.

Resource Types
Examples
RPM Reader


Examples

Table of Contents

  • Basic usage
Predefined Constants
Basic usage
RPM Reader


Basic usage

This example will open an RPM file and read the name, version, and release from the RPM file, echo the results, and close the RPM file.

Example #1 Basic RPMReader Example

<?php

$filename = "/path/to/file.rpm";

// open file
$rpmr = rpm_open($filename);

// get "Name" tag
$name = rpm_get_tag($rpmr, RPMREADER_NAME);

// get "Version" tag
$ver = rpm_get_tag($rpmr, RPMREADER_VERSION);

// get "Release" tag
$rel = rpm_get_tag($rpmr, RPMREADER_RELEASE);

echo "$name-$ver-$rel<br>\n";

// close file
rpm_close($rpmr);

?>
Examples
RPM Reader Functions
Examples


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/rpmreader.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

The RPMReader extension requires PHP 5.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

There is one resource type used by the RPMReader module. The resource is a file pointer which identifies the RPM file with which to work.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
RPM Reader


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Runkit Configuration Options
Name | Default | Changeable | Changelog
runkit.superglobal | "" | PHP_INI_PERDIR |
runkit.internal_override | "0" | PHP_INI_SYSTEM |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

runkit.superglobal string
Comma-separated list of variable names to be treated as superglobals. This value should be set in the systemwide php.ini file, but may work in perdir configuration contexts depending on your SAPI.

Example #1 Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini

<?php
function show_values() {
  echo "Foo is $_FOO\n";
  echo "Bar is $_BAR\n";
  echo "Baz is $_BAZ\n";
}

$_FOO = 'foo';
$_BAR = 'bar';
$_BAZ = 'baz';

/* Displays foo and bar, but not baz */
show_values();
?>
runkit.internal_override boolean
Enables ability to modify/rename/remove internal functions.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

RUNKIT_IMPORT_FUNCTIONS (integer)
runkit_import() flag indicating that normal functions should be imported from the specified file.
RUNKIT_IMPORT_CLASS_METHODS (integer)
runkit_import() flag indicating that class methods should be imported from the specified file.
RUNKIT_IMPORT_CLASS_CONSTS (integer)
runkit_import() flag indicating that class constants should be imported from the specified file. Note that this flag is only meaningful in PHP versions 5.1.0 and above.
RUNKIT_IMPORT_CLASS_PROPS (integer)
runkit_import() flag indicating that class standard properties should be imported from the specified file.
RUNKIT_IMPORT_CLASSES (integer)
runkit_import() flag representing a bitwise OR of the RUNKIT_IMPORT_CLASS_* constants.
RUNKIT_IMPORT_OVERRIDE (integer)
runkit_import() flag indicating that if any of the imported functions, methods, constants, or properties already exist, they should be replaced with the new definitions. If this flag is not set, then any imported definitions which already exist will be discarded.
RUNKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to runkit_method_add()
RUNKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to runkit_method_add()
RUNKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to runkit_method_add()
CLASSKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_AGGREGATE_OVERRIDE (integer)
PHP 5 specific flag to classkit_import() Only defined when classkit compatibility is enabled.
RUNKIT_VERSION (string)
Defined to the current version of the runkit package.
CLASSKIT_VERSION (string)
Defined to the current version of the runkit package. Only defined when classkit compatibility is enabled.
Introduction
Installing/Configuring
runkit


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/runkit.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

Modifying Constants, Functions, Classes, and Methods works with all releases of PHP 4 and PHP 5. No special requirements are necessary.

Custom Superglobals are only available in PHP 4.2.0 or later.

Sandboxing requires PHP 5.1.0 or later, or PHP 5.0.0 with a special TSRM patch applied. Regardless of which version of PHP is in use it must be compiled with the --enable-maintainer-zts option. See the README file in the runkit package for additional information.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension has no resource types defined.

Runtime Configuration
runkit Functions
Installing/Configuring


Runkit Sandbox Class -- PHP Virtual Machine

runkit Functions
Runkit_Sandbox_Parent
runkit Functions
PHP Manual

Runkit_Sandbox

(PECL runkit >= 0.7.0)

Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine

Description

Instantiating the Runkit_Sandbox class creates a new thread with its own scope and program stack. Using a set of options passed to the constructor, this environment may be restricted to a subset of what the primary interpreter can do and provide a safer environment for executing user supplied code.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Constructor

void Runkit_Sandbox::__construct ([ array $options ] )

options is an associative array containing any combination of the special ini options listed below.

safe_mode

If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode = off, then safe_mode may be turned on for the sandbox environment. This setting can not be used to disable safe_mode when it's already enabled in the outer script.

safe_mode_gid

If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode_gid = on, then safe_mode_gid may be turned off for the sandbox environment. This setting can not be used to enable safe_mode_gid when it's already disabled in the outer script.

safe_mode_include_dir

If the outer script which is instantiating the Runkit_Sandbox class is configured with a safe_mode_include_dir, then a new safe_mode_include_dir may be set for sandbox environments below the currently defined value. safe_mode_include_dir may also be cleared to indicate that the bypass feature is disabled. If safe_mode_include_dir was blank in the outer script, but safe_mode was not enabled, then any arbitrary safe_mode_include_dir may be set while turning safe_mode on.

open_basedir

open_basedir may be set to any path below the current setting of open_basedir. If open_basedir is not set within the global scope, then it is assumed to be the root directory and may be set to any location.

allow_url_fopen

Like safe_mode , this setting can only be made more restrictive, in this case by setting it to FALSE when it is previously set to TRUE

disable_functions

Comma separated list of functions to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled functions, they will remain disabled whether listed here or not.

disable_classes

Comma separated list of classes to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled classes, they will remain disabled whether listed here or not.

runkit.superglobal

Comma separated list of variables to be treated as superglobals within the sandbox sub-interpreter. These variables will be used in addition to any variables defined internally or through the global runkit.superglobal setting.

runkit.internal_override

Ini option runkit.internal_override may be disabled (but not re-enabled) within sandboxes.

Example #1 Instantiating a restricted sandbox

<?php
$options = array(
  'safe_mode'=>true,
  'open_basedir'=>'/var/www/users/jdoe/',
  'allow_url_fopen'=>'false',
  'disable_functions'=>'exec,shell_exec,passthru,system',
  'disable_classes'=>'myAppClass');
$sandbox = new Runkit_Sandbox($options);
/* Non-protected ini settings may set normally */
$sandbox->ini_set('html_errors',true);
?>

Accessing Variables

All variables in the global scope of the sandbox environment are accessible as properties of the sandbox object. The first thing to note is that because of the way memory between these two threads is managed, object and resource variables can not currently be exchanged between interpreters. Additionally, all arrays are deep copied and any references will be lost. This also means that references between interpreters are not possible.

Example #2 Working with variables in a sandbox

<?php
$sandbox = new Runkit_Sandbox();

$sandbox->foo = 'bar';
$sandbox->eval('echo "$foo\n"; $bar = $foo . "baz";');
echo "{$sandbox->bar}\n";
if (isset($sandbox->foo)) unset($sandbox->foo);
$sandbox->eval('var_dump(isset($foo));');
?>

The above example will output:

bar
barbaz
bool(false)

Calling PHP Functions

Any function defined within the sandbox may be called as
a method on the sandbox object.  This also includes a few
pseudo-function language constructs:  eval(),
include(), include_once(),
require(), require_once(),
echo(), print(),
die(), and exit().

Example #3 Calling sandbox functions

<?php
$sandbox = new Runkit_Sandbox();

echo $sandbox->str_replace('a','f','abc');
?>

The above example will output:

fbc

When passing arguments to a sandbox function, the arguments are taken from the outer instance of PHP. If you wish to pass arguments from the sandbox's scope, be sure to access them as properties of the sandbox object as illustrated above.

Example #4 Passing arguments to sandbox functions

<?php
$sandbox = new Runkit_Sandbox();

$foo = 'bar';
$sandbox->foo = 'baz';
echo $sandbox->str_replace('a',$foo,'a');
echo $sandbox->str_replace('a',$sandbox->foo,'a');
?>

The above example will output:

bar
baz

Changing Sandbox Settings

As of runkit version 0.5, certain Sandbox settings may be modified on the fly using ArrayAccess syntax. Some settings, such as active are read-only and meant to provide status information. Other settings, such as output_handler may be set and read much like a normal array offset. Future settings may be write-only, however no such settings currently exist.

Sandbox Settings / Status Indicators
Setting | Type | Purpose | Default
active | Boolean (Read Only) | TRUE if the Sandbox is still in a usable state, FALSE if the request is in bailout due to a call to die(), exit(), or because of a fatal error condition. | TRUE (Initial)
output_handler | Callback | When set to a valid callback, all output generated by the Sandbox instance will be processed through the named function. Sandbox output handlers follow the same calling conventions as the system-wide output handler. | None
parent_access | Boolean | May the sandbox use instances of the Runkit_Sandbox_Parent class? Must be enabled for other Runkit_Sandbox_Parent related settings to work. | FALSE
parent_read | Boolean | May the sandbox read variables in its parent's context? | FALSE
parent_write | Boolean | May the sandbox modify variables in its parent's context? | FALSE
parent_eval | Boolean | May the sandbox evaluate arbitrary code in its parent's context? DANGEROUS | FALSE
parent_include | Boolean | May the sandbox include php code files in its parent's context? DANGEROUS | FALSE
parent_echo | Boolean | May the sandbox echo data in its parent's context effectively bypassing its own output_handler? | FALSE
parent_call | Boolean | May the sandbox call functions in its parent's context? | FALSE
parent_die | Boolean | May the sandbox kill its own parent? (And thus itself) | FALSE
parent_scope | Integer | What scope will parental property access look at? 0 == Global scope, 1 == Calling scope, 2 == Scope preceeding calling scope, 3 == The scope before that, etc..., etc... | 0 (Global)
parent_scope | String | When parent_scope is set to a string value, it refers to a named array variable in the global scope. If the named variable does not exist at the time of access it will be created as an empty array. If the variable exists but it not an array, a dummy array will be created containing a reference to the named global variable. |

runkit Functions
Runkit_Sandbox_Parent
runkit Functions


Runkit Anti-Sandbox Class

Runkit_Sandbox
runkit_class_adopt
runkit Functions
PHP Manual

Runkit_Sandbox_Parent

(PECL runkit >= 0.7.0)

Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class

Description

void Runkit_Sandbox_Parent::__construct ( void )

Instantiating the Runkit_Sandbox_Parent class from within a sandbox environment created from the Runkit_Sandbox class provides some (controlled) means for a sandbox child to access its parent.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.

In order for any of the Runkit_Sandbox_Parent features to function. Support must be enabled on a per-sandbox basis by enabling the parent_access flag from the parent's context.

Example #1 Working with variables in a sandbox

<?php
$sandbox = new Runkit_Sandbox();
$sandbox['parent_access'] = true;
?>

Accessing the Parent's Variables

Just as with sandbox variable access, a sandbox parent's variables may be read from and written to as properties of the Runkit_Sandbox_Parent class. Read access to parental variables may be enabled with the parent_read setting (in addition to the base parent_access setting). Write access, in turn, is enabled through the parent_write setting.

Unlike sandbox child variable access, the variable scope is not limited to globals only. By setting the parent_scope setting to an appropriate integer value, other scopes in the active call stack may be inspected instead. A value of 0 (Default) will direct variable access at the global scope. 1 will point variable access at whatever variable scope was active at the time the current block of sandbox code was executed. Higher values progress back through the functions that called the functions that led to the sandbox executing code that tried to access its own parent's variables.

Example #2 Accessing parental variables

<?php
$php = new Runkit_Sandbox();
$php['parent_access'] = true;
$php['parent_read'] = true;

$test = "Global";

$php->eval('$PARENT = new Runkit_Sandbox_Parent;');

$php['parent_scope'] = 0;
one();

$php['parent_scope'] = 1;
one();

$php['parent_scope'] = 2;
one();

$php['parent_scope'] = 3;
one();

$php['parent_scope'] = 4;
one();

$php['parent_scope'] = 5;
one();

function one() {
    $test = "one()";
    two();
}

function two() {
    $test = "two()";
    three();
}

function three() {
    $test = "three()";
    $GLOBALS['php']->eval('var_dump($PARENT->test);');
}
?>

The above example will output:

string(6) "Global"
string(7) "three()"
string(5) "two()"
string(5) "one()"
string(6) "Global"
string(6) "Global"

Calling the Parent's Functions

Just as with sandbox access, a sandbox may access its parents functions providing that the proper settings have been enabled. Enabling parent_call will allow the sandbox to call all functions available to the parent scope. Language constructs are each controlled by their own setting: print() and echo() are enabled with parent_echo. die() and exit() are enabled with parent_die. eval() is enabled with parent_eval while include(), include_once(), require(), and require_once() are enabled through parent_include.

Runkit_Sandbox
runkit_class_adopt
runkit Functions


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Predefined Constants
Requirements
runkit


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

scream Configure Options
Name | Default | Changeable | Changelog
scream.enabled | Off | PHP_INI_ALL |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

scream.enabled int

Whether or not to enable scream.

Installation
Resource Types
Installing/Configuring


Examples

Table of Contents

  • Example that shows the effect of scream
Resource Types
Example that shows the effect of scream
scream


Example that shows the effect of scream

This example demonstrates how scream affects the behaviour of PHP's error handler.

Example #1 Enabling and disabling scream at runtime

<?php
// Make sure errors will be shown
ini_set('display_errors', true);
error_reporting(E_ALL);

// Disable scream - this is the default and produce an error
ini_set('scream.enabled', false);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/not-existing-file', 'r');

// Now enable scream and try again
ini_set('scream.enabled', true);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/another-not-existing-file', 'r');
?>

The above example will output something similar to:

Opening http://example.com/not-existing-file
Opening http://example.com/not-existing-file

Warning: fopen(http://example.com/another-not-existing-file): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in example.php on line 14

Note: Usually one would set this in the php.ini configuration file instead of changing the code.

Examples
WinCache
Examples


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/scream

Requirements
Runtime Configuration
Installing/Configuring


Resource Types

This extension has no resource types defined.

Runtime Configuration
Examples
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
scream


Security

  • Introduction
  • General considerations
  • Installed as CGI binary
    • Possible attacks
    • Case 1: only public files served
    • Case 2: using cgi.force_redirect
    • Case 3: setting doc_root or user_dir
    • Case 4: PHP parser outside of web tree
  • Installed as an Apache module
  • Filesystem Security
    • Null bytes related issues
  • Database Security
    • Designing Databases
    • Connecting to Database
    • Encrypted Storage Model
    • SQL Injection
  • Error Reporting
  • Using Register Globals
  • User Submitted Data
  • Magic Quotes
    • What are Magic Quotes
    • Why did we use Magic Quotes
    • Why not to use Magic Quotes
    • Disabling Magic Quotes
  • Hiding PHP
  • Keeping Current
Context parameters
Introduction


Installed as an Apache module

When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessible to the "nobody" user. This means a malicious script could access and modify the database, even without a username and password. It's entirely possible that a web spider could stumble across a database administrator's web page, and drop all of your databases. You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.

Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories. Or perhaps it has been prevented from accessing or changing databases. It has equally been secured from writing good and bad files, or entering good and bad database transactions.

A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache's abilities in some other way.

Escalating the Apache user's permissions to root is extremely dangerous and may compromise the entire system, so sudo'ing, chroot'ing, or otherwise running as root should not be considered by those who are not security professionals.

There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.

Case 4: PHP parser outside of web tree
Filesystem Security
Security


Installed as CGI binary

Table of Contents

  • Possible attacks
  • Case 1: only public files served
  • Case 2: using cgi.force_redirect
  • Case 3: setting doc_root or user_dir
  • Case 4: PHP parser outside of web tree
General considerations
Possible attacks
Security


Possible attacks

Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory » CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:

  • Accessing system files: http://my.host/cgi-bin/php?/etc/passwd The query information in a URL after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line. When invoked as a CGI binary, PHP refuses to interpret the command line arguments.
  • Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html The path information part of the URL after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server. In PHP, runtime configuration directives cgi.force_redirect, doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full the explanation of the different combinations.
Installed as CGI binary
Case 1: only public files served
Installed as CGI binary


Case 1: only public files served

If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option --enable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.

Redirection can be configured in Apache by using AddHandler and Action directives (see below).

Possible attacks
Case 2: using cgi.force_redirect
Installed as CGI binary


Case 3: setting doc_root or user_dir

To include active content, like scripts and executables, in the web server document directories is sometimes considered an insecure practice. If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords. Therefore many sysadmins will prefer setting up another directory structure for scripts that are accessible only through the PHP CGI, and therefore always interpreted and not displayed as such.

Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.

You can set the PHP script document root by the configuration directive doc_root in the configuration file, or you can set the environment variable PHP_DOCUMENT_ROOT. If it is set, the CGI version of PHP will always construct the file name to open with this doc_root and the path information in the request, so you can be sure no script is executed outside this directory (except for user_dir below).

Another option usable here is user_dir. When user_dir is unset, only thing controlling the opened file name is doc_root . Opening a URL like http://my.host/~user/doc.php does not result in opening a file under users home directory, but a file called ~user/doc.php under doc_root (yes, a directory name starting with a tilde [~]).

If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php will open a file called doc.php under the directory named public_php under the home directory of the user. If the home of the user is /home/user, the file executed is /home/user/public_php/doc.php.

user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.

Case 2: using cgi.force_redirect
Case 4: PHP parser outside of web tree
Installed as CGI binary


Case 2: using cgi.force_redirect

The configuration directive cgi.force_redirect prevents anyone from calling PHP directly with a URL like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule. PHP older than 4.2.0 used --enable-force-cgi-redirect compile time option for this.

Usually the redirection in the Apache configuration is done with the following directives:

Action php-script /cgi-bin/php
AddHandler php-script .php

This option has only been tested with the Apache web server, and relies on Apache to set the non-standard CGI environment variable REDIRECT_STATUS on redirected requests. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version documented here.

Case 1: only public files served
Case 3: setting doc_root or user_dir
Installed as CGI binary


Case 4: PHP parser outside of web tree

A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:

#!/usr/local/bin/php

as the first line of any file containing PHP tags. You will also need to make the file executable. That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the #! shell-escape mechanism for launching itself.

To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the PHP parser should be compiled with the --enable-discard-path configure option.

Case 3: setting doc_root or user_dir
Installed as an Apache module
Installed as CGI binary


Keeping Current

PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance security and repair any flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system.

Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.

Hiding PHP
Features
Security


Database Security

Table of Contents

  • Designing Databases
  • Connecting to Database
  • Encrypted Storage Model
  • SQL Injection

Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret information can be stored in a database, you should strongly consider protecting your databases.

To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connection. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL). See how an attacker can tamper with an SQL query.

As you can surmise, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.

Keep in mind this simple rule: defense in depth. The more places you take action to increase the protection of your database, the less probability of an attacker succeeding in exposing or abusing any stored information. Good design of the database schema and the application deals with your greatest fears.

Null bytes related issues
Designing Databases
Security


Connecting to Database

You may want to establish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of these is used, then monitoring your traffic and gaining information about your database will be difficult for a would-be attacker.

Designing Databases
Encrypted Storage Model
Database Security


Designing Databases

The first step is always to create the database, unless you want to use one from a third party. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.

Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.

You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using your applications credentials, they can only effect as many changes as your application can.

You are encouraged not to implement all the business logic in the web application (i.e. your script), instead do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to re-implement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.

Database Security
Connecting to Database
Database Security


SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query. The following examples are based on true stories, unfortunately.

Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.

Example #1 Splitting the result set into pages ... and making superusers (PostgreSQL)

<?php

$offset = $argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);

?>

Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL

0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--

If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.

Note: It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.

A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.

Example #2 Listing out articles ... and some passwords (any database server)

<?php

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

?>

The static part of the query can be combined with another SELECT statement which reveals all passwords:

'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.

SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.

Example #3 From resetting a password ... to gaining more privileges (any database server)

<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>

But a malicious user sumbits the value ' or uid like'%admin%'; -- to $uid to change the admin's password, or simply sets $pwd to "hehehe', admin='yes', trusted=100 " (with a trailing space) to gain more privileges. Then, the query will be twisted:

<?php

// $uid == ' or uid like'%admin%'; --
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --";

// $pwd == "hehehe', admin='yes', trusted=100 "
$query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE
...;";

?>

A frightening example how operating system level commands can be accessed on some database hosts.

Example #4 Attacking the database hosts operating system (MSSQL Server)

<?php

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

?>

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

<?php

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

?>

MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine.

Note: Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.

Avoiding techniques

You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management system or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.

These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.

  • Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
  • Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.

  • If the application waits for numerical input, consider verifying data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().

    Example #5 A more secure way to compose a query for paging

    <?php

    settype    ($offset, 'integer');
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";

    // please note %d in the format string, using %s would be meaningless
    $query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
                         $offset);

    ?>

  • Quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_real_escape_string(), sqlite_escape_string(), etc.). If a database-specific string escape mechanism is not available, the addslashes() and str_replace() functions may be useful (depending on database type). See the first example. As the example shows, adding quotes to the static part of the query is not enough, making this query easily crackable.
  • Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.
  • You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less.

Encrypted Storage Model
Error Reporting
Database Security


Encrypted Storage Model

SSL/SSH protects data travelling from the client to the server, SSL/SSH does not protect the persistent data stored in a database. SSL is an on-the-wire protocol.

Once an attacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.

The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this with several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data before inserting it into the database, and decrypts it when retrieving. See the references for further examples of how encryption works.

In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may also be taken into consideration. The well-known example for the hashing is storing the MD5 hash of a password in a database, instead of the password itself. See also crypt() and md5().

Example #1 Using hashed password field

<?php

// storing password hash
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            pg_escape_string($username), md5($password));
$result = pg_query($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
            pg_escape_string($username), md5($password));
$result = pg_query($connection, $query);

if (pg_num_rows($result) > 0) {
    echo 'Welcome, $username!';
} else {
    echo 'Authentication failed for $username.';
}

?>
Connecting to Database
SQL Injection
Database Security


Error Reporting

With PHP security, there are two sides to error reporting. One is beneficial to increasing security, the other is detrimental.

A standard attack tactic involves profiling a system by feeding it improper data, and checking for the kinds, and contexts, of the errors which are returned. This allows the system cracker to probe for information about the server, to determine possible weaknesses. For example, if an attacker had gleaned information about a page based on a prior form submission, they may attempt to override variables, or modify them:

Example #1 Attacking Variables with a custom HTML page

<form method="post" action="attacktarget?username=badfoo&amp;password=badfoo">
<input type="hidden" name="username" value="badfoo" />
<input type="hidden" name="password" value="badfoo" />
</form>

The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure occurred in. This is all information that can be exploited. It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure, but in a live site, this can expose hidden variables, unchecked syntax, and other dangerous information. Especially dangerous is running code from known sources with built-in debugging handlers, or using common debugging techniques. If the attacker can determine what general technique you are using, they may try to brute-force a page, by sending various common debugging strings:

Example #2 Exploiting common debugging variables

<form method="post" action="attacktarget?errors=Y&amp;showerrors=1&amp;debug=1">
<input type="hidden" name="errors" value="Y" />
<input type="hidden" name="showerrors" value="1" />
<input type="hidden" name="debug" value="1" />
</form>

Regardless of the method of error handling, the ability to probe a system for errors leads to providing an attacker with more information.

For example, the very style of a generic PHP error indicates a system is running PHP. If the attacker was looking at an .html page, and wanted to probe for the back-end (to look for known weaknesses in the system), by feeding it the wrong data they may be able to determine that a system was built with PHP.

A function error can indicate whether a system may be running a specific database engine, or give clues as to how a web page or programmed or designed. This allows for deeper investigation into open database ports, or to look for specific bugs or weaknesses in a web page. By feeding different pieces of bad data, for example, an attacker can determine the order of authentication in a script, (from the line number errors) as well as probe for exploits that may be exploited in different locations in the script.

A filesystem or general PHP error can indicate what permissions the web server has, as well as the structure and organization of files on the web server. Developer written error code can aggravate this problem, leading to easy exploitation of formerly "hidden" information.

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

One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. Once you are ready for deployment, you should either disable error reporting completely by setting error_reporting() to 0, or turn off the error display using the php.ini option display_errors, to insulate your code from probing. If you choose to do the latter, you should also define the path to your log file using the error_log ini directive, and turn log_errors on.

Example #3 Finding dangerous variables with E_ALL

<?php
if ($username) {  // Not initialized or checked before usage
    $good_login = 1;
}
if ($good_login == 1) { // If above test fails, not initialized or checked before usage
    readfile ("/highly/sensitive/data/index.html");
}
?>

SQL Injection
Using Register Globals
Security


Filesystem Security

Table of Contents

  • Null bytes related issues

PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read. Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.

Since PHP was designed to allow user level access to the filesystem, it's entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc. This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.

Consider the following script, where a user indicates that they'd like to delete a file in their home directory. This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.

Example #1 Poor variable checking leads to....

<?php
// remove a file from the user's home directory
$username = $_POST['user_submitted_name'];
$userfile = $_POST['user_submitted_filename'];
$homedir  = "/home/$username";

unlink("$homedir/$userfile");

echo "The file has been deleted!";
?>

Since the username and the filename are postable from a user form, they can submit a username and a filename belonging to someone else, and delete it even if they're not supposed to be allowed to do so. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were "../etc/" and "passwd". The code would then effectively read:

Example #2 ... A filesystem attack

<?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username = $_POST['user_submitted_name']; // "../etc"
$userfile = $_POST['user_submitted_filename']; // "passwd"
$homedir  = "/home/$username"; // "/home/../etc"

unlink("$homedir/$userfile"); // "/home/../etc/passwd"

echo "The file has been deleted!";
?>

There are two important measures you should take to prevent these issues.

  • Only allow limited permissions to the PHP web user binary.
  • Check all variables which are submitted.

Here is an improved script:

Example #3 More secure file name checking

<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$userfile = basename($_POST['user_submitted_filename']);
$homedir  = "/home/$username";

$filepath = "$homedir/$userfile";

if (file_exists($filepath) && unlink($filepath)) {
    $logstring = "Deleted $filepath\n";
} else {
    $logstring = "Failed to delete $filepath\n";
}
$fp = fopen("/home/logging/filedelete.log", "a");
fwrite($fp, $logstring);
fclose($fp);

echo htmlentities($logstring, ENT_QUOTES);

?>

However, even this is not without its flaws. If your authentication system allowed users to create their own user logins, and a user chose the login "../etc/", the system is once again exposed. For this reason, you may prefer to write a more customized check:

Example #4 More secure file name checking

<?php
$username     = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$userfile     = $_POST['user_submitted_filename'];
$homedir      = "/home/$username";

$filepath     = "$homedir/$userfile";

if (!ctype_alnum($username) || !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD', $userfile)) {
    die("Bad username/filename");
}

//etc...
?>

Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it's usually easier to create a policy where you forbid everything except for what you explicitly allow.

Installed as an Apache module
Null bytes related issues
Security


Null bytes related issues

As PHP uses the underlying C functions for filesystem related operations, it may handle null bytes in a quite unexpected way. As null bytes denote the end of a string in C, strings containing them won't be considered entirely but rather only until a null byte occurs. The following example shows a vulnerable code that demonstrates this problem:

Example #1 Script vulnerable to null bytes

<?php
$file = $_GET['file']; // "../../etc/passwd\0"
if (file_exists('/home/wwwrun/'.$file.'.php')) {
    // file_exists will return true as the file /home/wwwrun/../../etc/passwd exists
    include '/home/wwwrun/'.$file.'.php';
    // the file /etc/passwd will be included
}
?>

Therefore, any tainted string that is used in a filesystem operation should always be validated properly. Here is a better version of the previous example:

Example #2 Correctly validating the input

<?php
$file = $_GET['file'];

// Whitelisting possible values
switch ($file) {
    case 'main':
    case 'foo':
    case 'bar':
        include '/home/wwwrun/include/'.$file.'.php';
        break;
    default:
        include '/home/wwwrun/include/main.php';
}
?>
Filesystem Security
Database Security
Filesystem Security


General considerations

A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.

The best security is often unobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.

A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.

When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.

The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.

Introduction
Installed as CGI binary
Security


Using Register Globals

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP » 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.

When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:

Example #1 Example misuse with register_globals = on

<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
    $authorized = true;
}

// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
    include "/highly/sensitive/data.php";
}
?>

When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.

Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).

Example #2 Example use of sessions with register_globals on or off

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

    echo "Hello <b>{$_SESSION['username']}</b>";

} else {

    echo "Hello <b>Guest</b><br />";
    echo "Would you like to login?";

}
?>

It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from external sources.

Example #3 Detecting simple variable poisoning

<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {

    // MAGIC_COOKIE comes from a cookie.
    // Be sure to validate the cookie data!

} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {

   mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
   echo "Security violation, admin has been alerted.";
   exit;

} else {

   // MAGIC_COOKIE isn't set through this REQUEST

}
?>

Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.

For information about emulating register_globals being On or Off, see this FAQ.

Note: Superglobals: availability note
Superglobal arrays such as $_GET, $_POST, and $_SERVER, etc. are available as of PHP 4.1.0. For more information, read the manual section on superglobals

Error Reporting
User Submitted Data
Security


Hiding PHP

In general, security by obscurity is one of the weakest forms of security. But in some cases, every little bit of extra security is desirable.

A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php to off in your php.ini file, you reduce the amount of information available to them.

Another tactic is to configure web servers such as apache to parse different filetypes through PHP, either with an .htaccess directive, or in the apache configuration file itself. You can then use misleading file extensions:

Example #1 Hiding PHP as another language

# Make PHP code look like other code types
AddType application/x-httpd-php .asp .py .pl

Or obscure it completely:

Example #2 Using unknown types for PHP extensions

# Make PHP code look like unknown types
AddType application/x-httpd-php .bop .foo .133t

Or hide it as HTML code, which has a slight performance hit because all HTML will be parsed through the PHP engine:

Example #3 Using HTML types for PHP extensions

# Make all PHP code look like HTML
AddType application/x-httpd-php .htm .html

For this to work effectively, you must rename your PHP files with the above extensions. While it is a form of security through obscurity, it's a minor preventative measure with few drawbacks.

Disabling Magic Quotes
Keeping Current
Security


Introduction

PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need.

As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup.

The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer.

This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.

Security
General considerations
Security


Magic Quotes

Table of Contents

  • What are Magic Quotes
  • Why did we use Magic Quotes
  • Why not to use Magic Quotes
  • Disabling Magic Quotes
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.

User Submitted Data
What are Magic Quotes
Security


Disabling Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.

Example #1 Disabling magic quotes server side

An example that sets the value of these directives to Off in php.ini. For additional details, read the manual section titled How to change configuration settings.

; Magic quotes
;

; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off

If access to the server configuration is unavailable, use of .htaccess is also an option. For example:

php_flag magic_quotes_gpc Off

In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here's an example to disable magic_quotes_gpc at runtime. This method is inefficient so it's preferred to instead set the appropriate directives elsewhere.

Example #2 Disabling magic quotes at runtime

<?php
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}
?>

Why not to use Magic Quotes
Hiding PHP
Magic Quotes


What are Magic Quotes

When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.

There are three magic quote directives:

  • magic_quotes_gpc Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP. See also get_magic_quotes_gpc().
  • magic_quotes_runtime If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP. See also set_magic_quotes_runtime() and get_magic_quotes_runtime().
  • magic_quotes_sybase If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULL's will remain untouched and unescaped. See also ini_get() for retrieving its value.
Magic Quotes
Why did we use Magic Quotes
Magic Quotes


Why did we use Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

  • There is no reason to use magic quotes because they are no longer a supported part of PHP. However, they did exist and did help a few beginners blissfully and unknowingly write better (more secure) code. But, when dealing with code that relies upon this behavior it's better to update the code instead of turning magic quotes on. So why did this feature exist? Simple, to help prevent SQL Injection. Today developers are better aware of security and end up using database specific escaping mechanisms and/or prepared statements instead of relying upon features like magical quotes.
What are Magic Quotes
Why not to use Magic Quotes
Magic Quotes


Why not to use Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

  • Portability Assuming it to be on, or off, affects portability. Use get_magic_quotes_gpc() to check for this, and code accordingly.
  • Performance Because not every piece of escaped data is inserted into a database, there is a performance loss for escaping all this data. Simply calling on the escaping functions (like addslashes()) at runtime is more efficient. Although php.ini-development enables these directives by default, php.ini-production disables it. This recommendation is mainly due to performance reasons.
  • Inconvenience Because not all data needs escaping, it's often annoying to see escaped data where it shouldn't be. For example, emailing from a form, and seeing a bunch of \' within the email. To fix, this may require excessive use of stripslashes().
Why did we use Magic Quotes
Disabling Magic Quotes
Magic Quotes


User Submitted Data

The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.

Example #1 Dangerous Variable Usage

<?php
// remove a file from the user's home directory... or maybe
// somebody else's?
unlink ($evil_var);

// Write logging of their access... or maybe an /etc/passwd entry?
fwrite ($fp, $evil_var);

// Execute something trivial.. or rm -rf *?
system ($evil_var);
exec ($evil_var);

?>

You should always carefully examine your code to make sure that any variables being submitted from a web browser are being properly checked, and ask yourself the following questions:

  • Will this script only affect the intended files?
  • Can unusual or undesirable data be acted upon?
  • Can this script be used in unintended ways?
  • Can this be used in conjunction with other scripts in a negative manner?
  • Will any transactions be adequately logged?

By adequately asking these questions while writing the script, rather than later, you prevent an unfortunate re-write when you need to increase your security. By starting out with this mindset, you won't guarantee the security of your system, but you can help improve it.

You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).

Using Register Globals
Magic Quotes
Security


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Semaphore Configuration Options
Name | Default | Changeable | Changelog
sysvshm.init_mem | 10000 | PHP_INI_SYSTEM |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

sysvshm.init_mem int

A default size of the shared memory segment.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

System V message constants
Constant | Type | Changelog
MSG_IPC_NOWAIT | integer |
MSG_EAGAIN | integer | As of 5.2.0
MSG_ENOMSG | integer | As of 5.2.0
MSG_NOERROR | integer |
MSG_EXCEPT | integer |

Resource Types
Semaphore Functions
Semaphore


Installation

Support for this functions are not enabled by default. To enable System V semaphore support compile PHP with the option --enable-sysvsem. To enable the System V shared memory support compile PHP with the option --enable-sysvshm. To enable the System V messages support compile PHP with the option --enable-sysvmsg.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Semaphore


String representation of object

Serializable
Serializable::unserialize
Serializable
PHP Manual

Serializable::serialize

(PHP 5 >= 5.1.0)

Serializable::serialize — String representation of object

Description

abstract public string Serializable::serialize ( void )

Should return the string representation of the object.

Note: This method acts as the destructor of the object. The __destruct() method will not be called after this method.

Parameters

This function has no parameters.

Return Values

Returns the string representation of the object or NULL

Errors/Exceptions

Throws Exception when returning other types then strings and NULL

See Also

  • __sleep()

Serializable
Serializable::unserialize
Serializable


Constructs the object

Serializable::serialize
Context options and parameters
Serializable
PHP Manual

Serializable::unserialize

(PHP 5 >= 5.1.0)

Serializable::unserialize — Constructs the object

Description

abstract public mixed Serializable::unserialize ( string $serialized )

Called during unserialization of the object.

Note: This method acts as the constructor of the object. The __construct() method will not be called after this method.

Parameters

serialized

The string representation of the object.

Return Values

Returns the original value unserialized.

See Also

  • __wakeup()

Serializable::serialize
Context options and parameters
Serializable


Predefined Constants

This extension has no constants defined.

Resource Types
Examples
Shared Memory


Examples

Table of Contents

  • Shared Memory Operations Overview
Predefined Constants
Shared Memory Operations Overview
Shared Memory


Shared Memory Operations Overview

Examples
Shared Memory Functions
Examples
PHP Manual

Example #1 Shared Memory Operations Overview

<?php

// Create 100 byte shared memory block with system id of 0xff3
$shm_id = shmop_open(0xff3, "c", 0644, 100);
if (!$shm_id) {
    echo "Couldn't create shared memory segment\n";
}

// Get shared memory block's size
$shm_size = shmop_size($shm_id);
echo "SHM Block Size: " . $shm_size . " has been created.\n";

// Lets write a test string into shared memory
$shm_bytes_written = shmop_write($shm_id, "my shared memory block", 0);
if ($shm_bytes_written != strlen("my shared memory block")) {
    echo "Couldn't write the entire length of data\n";
}

// Now lets read the string back
$my_string = shmop_read($shm_id, 0, $shm_size);
if (!$my_string) {
    echo "Couldn't read from shared memory block\n";
}
echo "The data inside shared memory was: " . $my_string . "\n";

//Now lets delete the block and close the shared memory segment
if (!shmop_delete($shm_id)) {
    echo "Couldn't mark shared memory block for deletion.";
}
shmop_close($shm_id);

?>

Examples
Shared Memory Functions
Examples


Installation

To use shmop you will need to compile PHP with the --enable-shmop parameter in your configure line.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Shared Memory


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Warning

SPL uses class constants since PHP 5.1. Prior releases use global constants in the form RIT_LEAVES_ONLY.

RecursiveIteratorIterator::LEAVES_ONLY (integer)
RecursiveIteratorIterator::SELF_FIRST (integer)
RecursiveIteratorIterator::CHILD_FIRST (integer)
CachingIterator::CALL_TOSTRING (integer)
CachingIterator::CATCH_GET_CHILD (integer)
Resource Types
Datastructures
SPL


Datastructures

Table of Contents

  • The SplDoublyLinkedList class
  • The SplStack class
  • The SplQueue class
  • The SplHeap class
  • The SplMaxHeap class
  • The SplMinHeap class
  • The SplPriorityQueue class
  • The SplFixedArray class
  • The SplObjectStorage class

SPL provides a set of standard datastructures. They are grouped here by their underlying implementation which usually defines their general field of application.

Doubly Linked Lists

A Doubly Linked List (DLL) is a list of nodes linked in both directions to each others. Iterator's operations, access to both ends, addition or removal of nodes have a cost of O(1) when the underlying structure is a DLL. It hence provides a decent implementation for stacks and queues.

  • SplDoublyLinkedList
    • SplStack
    • SplQueue

Heaps

Heaps are tree-like structures that follow the heap-property: each node is greater than or equal to its children, when compared using the implemented compare method which is global to the heap.

  • SplHeap
    • SplMaxHeap
    • SplMinHeap
  • SplPriorityQueue

Arrays

Arrays are structures that store the data in a continuous way, accessible via indexes. Don't confuse them with PHP arrays: PHP arrays are in fact implemented as ordered hashtables.

  • SplFixedArray

Map

A map is a datastructure holding key-value pairs. PHP arrays can be seen as maps from integers/strings to values. SPL provides a map from objects to data. This map can also be used as an object set.

  • SplObjectStorage
Predefined Constants
SplDoublyLinkedList
SPL


Installation

This extension is available and compiled by default in PHP 5.0.0.

Note: As of PHP 5.3.0 this extension can no longer be disabled and is therefore always available.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
SPL


Peeks at the node from the beginning of the doubly linked list

SplDoublyLinkedList
SplDoublyLinkedList::__construct
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::bottom

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list

Description

mixed SplDoublyLinkedList::bottom ( void )

Parameters

This function has no parameters.

Return Values

The value of the first node.

SplDoublyLinkedList
SplDoublyLinkedList::__construct
SplDoublyLinkedList


Constructs a new doubly linked list

SplDoublyLinkedList::bottom
SplDoublyLinkedList::count
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::__construct

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::__construct — Constructs a new doubly linked list

Description

SplDoublyLinkedList::__construct ( void )

This constructs a new empty doubly linked list.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplDoublyLinkedList::__construct() example

<?php
$dll = new SplDoublyLinkedList();

$dll->push(2);
$dll->push(3);
$dll->unshift(5);

var_dump($dll);
?>

The above example will output:

object(SplDoublyLinkedList)#1 (2) {
  ["flags":"SplDoublyLinkedList":private]=>
  int(0)
  ["dllist":"SplDoublyLinkedList":private]=>
  array(3) {
    [0]=>
    int(5)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
}

SplDoublyLinkedList::bottom
SplDoublyLinkedList::count
SplDoublyLinkedList


Counts the number of elements in the doubly linked list.

SplDoublyLinkedList::__construct
SplDoublyLinkedList::current
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::count

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list.

Description

int SplDoublyLinkedList::count ( void )

Parameters

This function has no parameters.

Return Values

Returns the number of elements in the doubly linked list.

SplDoublyLinkedList::__construct
SplDoublyLinkedList::current
SplDoublyLinkedList


Return current array entry

SplDoublyLinkedList::count
SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::current

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::current — Return current array entry

Description

mixed SplDoublyLinkedList::current ( void )

Get the current doubly linked list node.

Parameters

This function has no parameters.

Return Values

The current node value.

SplDoublyLinkedList::count
SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList


Returns the mode of iteration

SplDoublyLinkedList::current
SplDoublyLinkedList::isEmpty
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::getIteratorMode

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration

Description

int SplDoublyLinkedList::getIteratorMode ( void )

Parameters

This function has no parameters.

Return Values

Returns the different modes and flags that affect the iteration.

SplDoublyLinkedList::current
SplDoublyLinkedList::isEmpty
SplDoublyLinkedList


Checks whether the doubly linked list is empty.

SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList::key
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::isEmpty

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty.

Description

bool SplDoublyLinkedList::isEmpty ( void )

Parameters

This function has no parameters.

Return Values

Returns whether the doubly linked list is empty.

SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList::key
SplDoublyLinkedList


Return current node index

SplDoublyLinkedList::isEmpty
SplDoublyLinkedList::next
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::key

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::key — Return current node index

Description

mixed SplDoublyLinkedList::key ( void )

This function returns the current node index

Parameters

This function has no parameters.

Return Values

The current node index.

SplDoublyLinkedList::isEmpty
SplDoublyLinkedList::next
SplDoublyLinkedList


Move to next entry

SplDoublyLinkedList::key
SplDoublyLinkedList::offsetExists
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::next

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::next — Move to next entry

Description

void SplDoublyLinkedList::next ( void )

Move the iterator to the next node.

Parameters

This function has no parameters.

Return Values

No value is returned.

SplDoublyLinkedList::key
SplDoublyLinkedList::offsetExists
SplDoublyLinkedList


Returns whether the requested $index exists

SplDoublyLinkedList::next
SplDoublyLinkedList::offsetGet
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetExists

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists

Description

bool SplDoublyLinkedList::offsetExists ( mixed $index )

Parameters

index

The index being checked.

Return Values

TRUE if the requested index exists, otherwise FALSE

SplDoublyLinkedList::next
SplDoublyLinkedList::offsetGet
SplDoublyLinkedList


Returns the value at the specified $index

SplDoublyLinkedList::offsetExists
SplDoublyLinkedList::offsetSet
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetGet

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetGet — Returns the value at the specified $index

Description

mixed SplDoublyLinkedList::offsetGet ( mixed $index )

Parameters

index

The index with the value.

Return Values

The value at the specified index .

SplDoublyLinkedList::offsetExists
SplDoublyLinkedList::offsetSet
SplDoublyLinkedList


Sets the value at the specified $index to $newval

SplDoublyLinkedList::offsetGet
SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetSet

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $newval

Description

void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )

Sets the value at the specified index to newval .

Parameters

index

The index being set.

newval

The new value for the index .

Return Values

No value is returned.

SplDoublyLinkedList::offsetGet
SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList


Unsets the value at the specified $index

SplDoublyLinkedList::offsetSet
SplDoublyLinkedList::pop
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetUnset

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index

Description

void SplDoublyLinkedList::offsetUnset ( mixed $index )

Unsets the value at the specified index.

Parameters

index

The index being unset.

Return Values

No value is returned.

SplDoublyLinkedList::offsetSet
SplDoublyLinkedList::pop
SplDoublyLinkedList


Pops a node from the end of the doubly linked list

SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList::prev
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::pop

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list

Description

mixed SplDoublyLinkedList::pop ( void )

Parameters

This function has no parameters.

Return Values

The value of the popped node.

SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList::prev
SplDoublyLinkedList


Move to previous entry

SplDoublyLinkedList::pop
SplDoublyLinkedList::push
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::prev

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::prev — Move to previous entry

Description

void SplDoublyLinkedList::prev ( void )

Move the iterator to the previous node.

Parameters

This function has no parameters.

Return Values

No value is returned.

SplDoublyLinkedList::pop
SplDoublyLinkedList::push
SplDoublyLinkedList


Pushes an element at the end of the doubly linked list

SplDoublyLinkedList::prev
SplDoublyLinkedList::rewind
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::push

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list

Description

void SplDoublyLinkedList::push ( mixed $value )

Pushes value at the end of the doubly linked list.

Parameters

value

The value to push.

Return Values

No value is returned.

SplDoublyLinkedList::prev
SplDoublyLinkedList::rewind
SplDoublyLinkedList


Rewind iterator back to the start

SplDoublyLinkedList::push
SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::rewind

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::rewind — Rewind iterator back to the start

Description

void SplDoublyLinkedList::rewind ( void )

This rewinds the iterator to the beginning.

Parameters

This function has no parameters.

Return Values

No value is returned.

SplDoublyLinkedList::push
SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList


Sets the mode of iteration

SplDoublyLinkedList::rewind
SplDoublyLinkedList::shift
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::setIteratorMode

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration

Description

void SplDoublyLinkedList::setIteratorMode ( int $mode )

Parameters

mode

There are two orthogonal sets of modes that can be set:

  • The direction of the iteration (either one or the other):
    • SplDoublyLinkedList::IT_MODE_LIFO (Stack style)
    • SplDoublyLinkedList::IT_MODE_FIFO (Queue style)
  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is: SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP

Return Values

No value is returned.

SplDoublyLinkedList::rewind
SplDoublyLinkedList::shift
SplDoublyLinkedList


Shifts a node from the beginning of the doubly linked list

SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList::top
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::shift

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list

Description

mixed SplDoublyLinkedList::shift ( void )

Parameters

This function has no parameters.

Return Values

The value of the shifted node.

SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList::top
SplDoublyLinkedList


Peeks at the node from the end of the doubly linked list

SplDoublyLinkedList::shift
SplDoublyLinkedList::unshift
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::top

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list

Description

mixed SplDoublyLinkedList::top ( void )

Parameters

This function has no parameters.

Return Values

The value of the last node.

SplDoublyLinkedList::shift
SplDoublyLinkedList::unshift
SplDoublyLinkedList


Prepends the doubly linked list with an element

SplDoublyLinkedList::top
SplDoublyLinkedList::valid
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::unshift

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element

Description

void SplDoublyLinkedList::unshift ( mixed $value )

Prepends value at the beginning of the doubly linked list.

Parameters

value

The value to unshift.

Return Values

No value is returned.

SplDoublyLinkedList::top
SplDoublyLinkedList::valid
SplDoublyLinkedList


Check whether the doubly linked list contains more nodes

SplDoublyLinkedList::unshift
SplStack
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::valid

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes

Description

bool SplDoublyLinkedList::valid ( void )

Checks if the doubly linked list contains any more nodes.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the doubly linked list contains any more nodes, FALSE otherwise.

SplDoublyLinkedList::unshift
SplStack
SplDoublyLinkedList


Compare elements in order to place them correctly in the heap while sifting up.

SplHeap
SplHeap::__construct
SplHeap
PHP Manual

SplHeap::compare

(PHP 5 >= 5.3.0)

SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Description

abstract int SplHeap::compare ( mixed $value1 , mixed $value2 )

Compare value1 with value2 .

Warning

Throwing exceptions in SplHeap::compare can corrupt the Heap and place it in a blocked state. You can unblock it by calling SplHeap::recoverFromCorruption. However, some elements might not be placed correctly and it may hence break the heap-property.

Parameters

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Return Values

Result of the comparison, positive integer if value1 is greater than value2 , 0 if they are equal, negative integer otherwise.

Note: Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.

SplHeap
SplHeap::__construct
SplHeap


Constructs a new empty heap

SplHeap::compare
SplHeap::count
SplHeap
PHP Manual

SplHeap::__construct

(PHP 5 >= 5.3.0)

SplHeap::__construct — Constructs a new empty heap

Description

SplHeap::__construct ( void )

This constructs a new empty heap.

Parameters

This function has no parameters.

Return Values

No value is returned.

SplHeap::compare
SplHeap::count
SplHeap


Counts the number of elements in the heap.

SplHeap::__construct
SplHeap::current
SplHeap
PHP Manual

SplHeap::count

(PHP 5 >= 5.3.0)

SplHeap::count — Counts the number of elements in the heap.

Description

int SplHeap::count ( void )

Parameters

This function has no parameters.

Return Values

Returns the number of elements in the heap.

SplHeap::__construct
SplHeap::current
SplHeap


Return current node pointed by the iterator

SplHeap::count
SplHeap::extract
SplHeap
PHP Manual

SplHeap::current

(PHP 5 >= 5.3.0)

SplHeap::current — Return current node pointed by the iterator

Description

mixed SplHeap::current ( void )

Get the current datastructure node.

Parameters

This function has no parameters.

Return Values

The current node value.

SplHeap::count
SplHeap::extract
SplHeap


Extracts a node from top of the heap and sift up.

SplHeap::current
SplHeap::insert
SplHeap
PHP Manual

SplHeap::extract

(PHP 5 >= 5.3.0)

SplHeap::extract — Extracts a node from top of the heap and sift up.

Description

mixed SplHeap::extract ( void )

Parameters

This function has no parameters.

Return Values

The value of the extracted node.

SplHeap::current
SplHeap::insert
SplHeap


Inserts an element in the heap by sifting it up.

SplHeap::extract
SplHeap::isEmpty
SplHeap
PHP Manual

SplHeap::insert

(PHP 5 >= 5.3.0)

SplHeap::insert — Inserts an element in the heap by sifting it up.

Description

void SplHeap::insert ( mixed $value )

Insert value in the heap.

Parameters

value

The value to insert.

Return Values

No value is returned.

SplHeap::extract
SplHeap::isEmpty
SplHeap


Checks whether the heap is empty.

SplHeap::insert
SplHeap::key
SplHeap
PHP Manual

SplHeap::isEmpty

(PHP 5 >= 5.3.0)

SplHeap::isEmpty — Checks whether the heap is empty.

Description

bool SplHeap::isEmpty ( void )

Parameters

This function has no parameters.

Return Values

Returns whether the heap is empty.

SplHeap::insert
SplHeap::key
SplHeap


Return current node index

SplHeap::isEmpty
SplHeap::next
SplHeap
PHP Manual

SplHeap::key

(PHP 5 >= 5.3.0)

SplHeap::key — Return current node index

Description

mixed SplHeap::key ( void )

This function returns the current node index

Parameters

This function has no parameters.

Return Values

The current node index.

SplHeap::isEmpty
SplHeap::next
SplHeap


Move to the next node

SplHeap::key
SplHeap::recoverFromCorruption
SplHeap
PHP Manual

SplHeap::next

(PHP 5 >= 5.3.0)

SplHeap::next — Move to the next node

Description

void SplHeap::next ( void )

Extracts the top node from the heap.

Parameters

This function has no parameters.

Return Values

No value is returned.

SplHeap::key
SplHeap::recoverFromCorruption
SplHeap


Recover from the corrupted state and allow further actions on the heap.

SplHeap::next
SplHeap::rewind
SplHeap
PHP Manual

SplHeap::recoverFromCorruption

(PHP 5 >= 5.3.0)

SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap.

Description

void SplHeap::recoverFromCorruption ( void )

Parameters

This function has no parameters.

Return Values

No value is returned.

SplHeap::next
SplHeap::rewind
SplHeap


Rewind iterator back to the start (no-op)

SplHeap::recoverFromCorruption
SplHeap::top
SplHeap
PHP Manual

SplHeap::rewind

(PHP 5 >= 5.3.0)

SplHeap::rewind — Rewind iterator back to the start (no-op)

Description

void SplHeap::rewind ( void )

This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap.

Parameters

This function has no parameters.

Return Values

No value is returned.

SplHeap::recoverFromCorruption
SplHeap::top
SplHeap


Peaks at the node from the top of the heap

SplHeap::rewind
SplHeap::valid
SplHeap
PHP Manual

SplHeap::top

(PHP 5 >= 5.3.0)

SplHeap::top — Peaks at the node from the top of the heap

Description

mixed SplHeap::top ( void )

Parameters

This function has no parameters.

Return Values

The value of the node on the top.

SplHeap::rewind
SplHeap::valid
SplHeap


Check whether the heap contains more nodes

SplHeap::top
SplMaxHeap
SplHeap
PHP Manual

SplHeap::valid

(PHP 5 >= 5.3.0)

SplHeap::valid — Check whether the heap contains more nodes

Description

bool SplHeap::valid ( void )

Checks if the heap contains any more nodes.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the heap contains any more nodes, FALSE otherwise.

SplHeap::top
SplMaxHeap
SplHeap


Constructs a new queue implemented using a doubly linked list

SplQueue
SplQueue::dequeue
SplQueue
PHP Manual

SplQueue::__construct

(PHP 5 >= 5.3.0)

SplQueue::__construct — Constructs a new queue implemented using a doubly linked list

Description

SplQueue::__construct ( void )

This constructs a new empty queue.

Note: This method automatically sets the iterator mode to SplDoublyLinkedList::IT_MODE_FIFO.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplQueue::__construct() example

<?php
$q = new SplQueue();

$q[] = 1;
$q[] = 2;
$q[] = 3;

foreach ($q as $elem)  {
 echo $elem."\n";
}
?>

The above example will output:

1
2
3

Example #2 Efficiently handling tasks with SplQueue

<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);

// ... enqueue some tasks on the queue ...

// process them
foreach ($q as $task) {
    // ... process $task ...

    // add new tasks on the queue
    $q[] = $newTask;
    // ...
}
?>

SplQueue
SplQueue::dequeue
SplQueue


Dequeues a node from the queue

SplQueue::__construct
SplQueue::enqueue
SplQueue
PHP Manual

SplQueue::dequeue

(PHP 5 >= 5.3.0)

SplQueue::dequeue — Dequeues a node from the queue

Description

mixed SplQueue::dequeue ( void )

Dequeues value from the top of of the queue.

Note: SplQueue::dequeue is an alias of SplDoublyLinkedList::shift.

Parameters

This function has no parameters.

Return Values

The value of the dequeued node.

SplQueue::__construct
SplQueue::enqueue
SplQueue


Adds an element to the queue.

SplQueue::dequeue
SplQueue::setIteratorMode
SplQueue
PHP Manual

SplQueue::enqueue

(PHP 5 >= 5.3.0)

SplQueue::enqueue — Adds an element to the queue.

Description

void SplQueue::enqueue ( mixed $value )

Enqueues value at the end of the queue.

Note: SplQueue::enqueue is an alias of SplDoublyLinkedList::push.

Parameters

value

The value to enqueue.

Return Values

No value is returned.

SplQueue::dequeue
SplQueue::setIteratorMode
SplQueue


Sets the mode of iteration

SplQueue::enqueue
SplHeap
SplQueue
PHP Manual

SplQueue::setIteratorMode

(PHP 5 >= 5.3.0)

SplQueue::setIteratorMode — Sets the mode of iteration

Description

void SplQueue::setIteratorMode ( int $mode )

Parameters

mode

There is only one iteration parameter you can modify.

  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is: SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP

Warning

The direction of iteration can not be changed for SplQueues, it is always SplDoublyLinkedList::IT_MODE_FIFO.

Return Values

No value is returned.

Errors/Exceptions

Throws a RuntimeException on trying to change the direction of iteration by using SplDoublyLinkedList::IT_MODE_LIFO.

SplQueue::enqueue
SplHeap
SplQueue


Constructs a new stack implemented using a doubly linked list

SplStack
SplStack::setIteratorMode
SplStack
PHP Manual

SplStack::__construct

(PHP 5 >= 5.3.0)

SplStack::__construct — Constructs a new stack implemented using a doubly linked list

Description

SplStack::__construct ( void )

This constructs a new empty stack.

Note: This method automatically sets the iterator mode to SplDoublyLinkedList::IT_MODE_LIFO.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplStack::__construct() example

<?php
$q = new SplStack();

$q[] = 1;
$q[] = 2;
$q[] = 3;

foreach ($q as $elem)  {
 echo $elem."\n";
}
?>

The above example will output:

3
2
1

SplStack
SplStack::setIteratorMode
SplStack


Sets the mode of iteration

SplStack::__construct
SplQueue
SplStack
PHP Manual

SplStack::setIteratorMode

(PHP 5 >= 5.3.0)

SplStack::setIteratorMode — Sets the mode of iteration

Description

void SplStack::setIteratorMode ( int $mode )

Parameters

mode

There is only one iteration parameter you can modify.

  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is 0x2 : SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_KEEP

Warning

The direction of iteration can no longer be changer for SplStacks. Trying to do so will result in a RuntimeException being thrown.

Return Values

No value is returned.

SplStack::__construct
SplQueue
SplStack


Predefined Constants

This extension has no constants defined.

Resource Types
SPPLUS Functions
SPPLUS


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/spplus.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Note: PHP 4.3.0 or greater is required for the compression to work.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

Note: You need at least PHP 4.1.0 and SPPLUS v.3

Note: You will need to get the new kit_php for spplus. Feel free to contact the maintainer if you can't get it.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
SPPLUS


Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

SQLite3
SQLite3::close
SQLite3
PHP Manual

SQLite3::changes

(PHP 5 >= 5.3.0)

SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

Description

public int SQLite3::changes ( void )

Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement.

Parameters

This function has no parameters.

Return Values

Returns an integer value corresponding to the number of database rows changed (or inserted or deleted) by the most recent SQL statement.

Examples

Example #1 SQLite3::changes() example

<?php
$db = new SQLite3('mysqlitedb.db');

$query = $db->exec('UPDATE counter SET views=0 WHERE page="test"');
if ($query) {
    echo 'Number of rows modified: ', $db->changes();
}
?>

SQLite3
SQLite3::close
SQLite3


Closes the database connection

SQLite3::changes
SQLite3::__construct
SQLite3
PHP Manual

SQLite3::close

(PHP 5 >= 5.3.0)

SQLite3::close — Closes the database connection

Description

public bool SQLite3::close ( void )

Closes the database connection.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success, FALSE on failure.

Examples

Example #1 SQLite3::close() example

<?php
$db = new SQLite3('mysqlitedb.db');
$db->close();
?>

SQLite3::changes
SQLite3::__construct
SQLite3


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

SQLite3 Configure Options
Name | Default | Changeable | Changelog
sqlite3.extension_dir | NULL | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

sqlite3.extension_dir string

Path to the directory where the loadable extensions for SQLite reside.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

SQLITE3_ASSOC (integer)
Specifies that the Sqlite3Result::fetchArray method shall return an array indexed by column name as returned in the corresponding result set.
SQLITE3_NUM (integer)
Specifies that the Sqlite3Result::fetchArray method shall return an array indexed by column number as returned in the corresponding result set, starting at column 0.
SQLITE3_BOTH (integer)
Specifies that the Sqlite3Result::fetchArray method shall return an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
SQLITE3_INTEGER (integer)
Represents the SQLite3 INTEGER storage class.
SQLITE3_FLOAT (integer)
Represents the SQLite3 REAL (FLOAT) storage class.
SQLITE3_TEXT (integer)
Represents the SQLite3 TEXT storage class.
SQLITE3_BLOB (integer)
Represents the SQLite3 BLOB storage class.
SQLITE3_NULL (integer)
Represents the SQLite3 NULL storage class.
SQLITE3_OPEN_READONLY (integer)
Specifies that the SQLite3 database be opened for reading only.
SQLITE3_OPEN_READWRITE (integer)
Specifies that the SQLite3 database be opened for reading and writing.
SQLITE3_OPEN_CREATE (integer)
Specifies that the SQLite3 database be created if it does not already exist.

Resource Types
SQLite3
SQLite3


Instantiates an SQLite3 object and opens an SQLite 3 database

SQLite3::close
SQLite3::createAggregate
SQLite3
PHP Manual

SQLite3::__construct

(PHP 5 >= 5.3.0)

SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database

Description

SQLite3::__construct ( string $filename [, int $flags [, string $encryption_key ]] )

Instantiates an SQLite3 object and opens a connection to an SQLite 3 database. If the build includes encryption, then it will attempt to use the key.

Parameters

filename

Path to the SQLite database.

flags

Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.

  • SQLITE3_OPEN_READONLY: Open the database for reading only.

  • SQLITE3_OPEN_READWRITE: Open the database for reading and writing.

  • SQLITE3_OPEN_CREATE: Create the database if it does not exist.

encryption_key

An optional encryption key used when encrypting and decrypting an SQLite database.

Return Values

Returns an SQLite3 object on success.

Examples

Example #1 SQLite3::__construct() example

<?php
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>

SQLite3::close
SQLite3::createAggregate
SQLite3


Registers a PHP function for use as an SQL aggregate function

SQLite3::__construct
SQLite3::createFunction
SQLite3
PHP Manual

SQLite3::createAggregate

(PHP 5 >= 5.3.0)

SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function

Description

public bool SQLite3::createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -1 ] )

Registers a PHP function or user-defined function for use as an SQL aggregate function for use within SQL statements.

Parameters

name

Name of the SQL aggregate to be created or redefined.

step_callback

The name of a PHP function or user-defined function to apply as a callback for every item in the aggregate.

final_callback

The name of a PHP function or user-defined function to apply as a callback at the end of the aggregate data.

argument_count

The number of arguments that the SQL aggregate takes. If this parameter is negative, then the SQL aggregate may take any number of arguments.

Return Values

Returns TRUE upon successful creation of the aggregate, FALSE on failure.

SQLite3::__construct
SQLite3::createFunction
SQLite3


Registers a PHP function for use as an SQL scalar function

SQLite3::createAggregate
SQLite3::escapeString
SQLite3
PHP Manual

SQLite3::createFunction

(PHP 5 >= 5.3.0)

SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function

Description

public bool SQLite3::createFunction ( string $name , mixed $callback [, int $argument_count = -1 ] )

Registers a PHP function or user-defined function for use as an SQL scalar function for use within SQL statements.

Parameters

name

Name of the SQL function to be created or redefined.

callback

The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the SQL function.

argument_count

The number of arguments that the SQL function takes. If this parameter is negative, then the SQL function may take any number of arguments.

Return Values

Returns TRUE upon successful creation of the function, FALSE on failure.

Examples

Example #1 SQLite3::createFunction() example

<?php
function my_udf_md5($string) {
    return md5($string);
}

$db = new SQLite3('mysqlitedb.db');
$db->createFunction('my_udf_md5', 'my_udf_md5');

var_dump($db->querySingle('SELECT my_udf_md5("test")'));
?>

The above example will output something similar to:

string(32) "098f6bcd4621d373cade4e832627b4f6"

SQLite3::createAggregate
SQLite3::escapeString
SQLite3


Returns a string that has been properly escaped

SQLite3::createFunction
SQLite3::exec
SQLite3
PHP Manual

SQLite3::escapeString

(PHP 5 >= 5.3.0)

SQLite3::escapeString — Returns a string that has been properly escaped

Description

public string SQLite3::escapeString ( string $value )

Returns a string that has been properly escaped for safe inclusion in an SQL statement.

Parameters

value

The string to be escaped.

Return Values

Returns a properly escaped string that may be used safely in an SQL statement.

Notes

Warning

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

SQLite3::createFunction
SQLite3::exec
SQLite3


Executes a result-less query against a given database

SQLite3::escapeString
SQLite3::lastErrorCode
SQLite3
PHP Manual

SQLite3::exec

(PHP 5 >= 5.3.0)

SQLite3::exec — Executes a result-less query against a given database

Description

public bool SQLite3::exec ( string $query )

Executes a result-less query against a given database.

Parameters

query

The SQL query to execute (typically an INSERT, UPDATE, or DELETE query).

Return Values

Returns TRUE if the query succeeded, FALSE on failure.

Examples

Example #1 SQLite3::exec() example

<?php
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE bar (bar STRING)');
?>

SQLite3::escapeString
SQLite3::lastErrorCode
SQLite3


Installation

The SQLite3 extension is enabled by default as of PHP 5.3.0. It's possible to disable it by using --without-sqlite3 at compile time.

Windows users must enable php_sqlite3.dll in order to use this extension. This DLL is included with Windows distributions of PHP as of PHP 5.3.0.

Note: This extension was briefly a PECL extension but that version is only recommended for experimental use.

Requirements
Runtime Configuration
Installing/Configuring


Returns the numeric result code of the most recent failed SQLite request

SQLite3::exec
SQLite3::lastErrorMsg
SQLite3
PHP Manual

SQLite3::lastErrorCode

(PHP 5 >= 5.3.0)

SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request

Description

public int SQLite3::lastErrorCode ( void )

Returns the numeric result code of the most recent failed SQLite request.

Parameters

This function has no parameters.

Return Values

Returns an integer value representing the numeric result code of the most recent failed SQLite request.

SQLite3::exec
SQLite3::lastErrorMsg
SQLite3


Returns English text describing the most recent failed SQLite request

SQLite3::lastErrorCode
SQLite3::lastInsertRowID
SQLite3
PHP Manual

SQLite3::lastErrorMsg

(PHP 5 >= 5.3.0)

SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request

Description

public string SQLite3::lastErrorMsg ( void )

Returns English text describing the most recent failed SQLite request.

Parameters

This function has no parameters.

Return Values

Returns an English string describing the most recent failed SQLite request.

SQLite3::lastErrorCode
SQLite3::lastInsertRowID
SQLite3


Returns the row ID of the most recent INSERT into the database

SQLite3::lastErrorMsg
SQLite3::loadExtension
SQLite3
PHP Manual

SQLite3::lastInsertRowID

(PHP 5 >= 5.3.0)

SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database

Description

public int SQLite3::lastInsertRowID ( void )

Returns the row ID of the most recent INSERT into the database.

Parameters

This function has no parameters.

Return Values

Returns the row ID of the most recent INSERT into the database

SQLite3::lastErrorMsg
SQLite3::loadExtension
SQLite3


Attempts to load an SQLite extension library

SQLite3::lastInsertRowID
SQLite3::open
SQLite3
PHP Manual

SQLite3::loadExtension

(PHP 5 >= 5.3.0)

SQLite3::loadExtension — Attempts to load an SQLite extension library

Description

public bool SQLite3::loadExtension ( string $shared_library )

Attempts to load an SQLite extension library.

Parameters

shared_library

The name of the library to load. The library must be located in the directory specified in the configure option sqlite3.extension_dir.

Return Values

Returns TRUE if the extension is successfully loaded, FALSE on failure.

Examples

Example #1 SQLite3::loadExtension() example

<?php
$db = new SQLite3('mysqlitedb.db');
$db->loadExtension('libagg.so');
?>

SQLite3::lastInsertRowID
SQLite3::open
SQLite3


Opens an SQLite database

SQLite3::loadExtension
SQLite3::prepare
SQLite3
PHP Manual

SQLite3::open

(PHP 5 >= 5.3.0)

SQLite3::open — Opens an SQLite database

Description

public bool SQLite3::open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key ]] )

Opens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.

Parameters

filename

Path to the SQLite database.

flags

Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.

  • SQLITE3_OPEN_READONLY: Open the database for reading only.

  • SQLITE3_OPEN_READWRITE: Open the database for reading and writing.

  • SQLITE3_OPEN_CREATE: Create the database if it does not exist.

encryption_key

An optional encryption key used when encrypting and decrypting an SQLite database.

Return Values

Returns TRUE on success, FALSE on failure to open the database.

Examples

Example #1 SQLite3::open() example

<?php
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>

SQLite3::loadExtension
SQLite3::prepare
SQLite3


Prepares an SQL statement for execution

SQLite3::open
SQLite3::query
SQLite3
PHP Manual

SQLite3::prepare

(PHP 5 >= 5.3.0)

SQLite3::prepare — Prepares an SQL statement for execution

Description

public SQLite3Stmt SQLite3::prepare ( string $query )

Prepares an SQL statement for execution and returns an SQLite3Stmt object.

Parameters

query

The SQL query to prepare.

Return Values

Returns an SQLite3Stmt object on success or FALSE on failure.

Examples

Example #1 SQLite3::prepare() example

<?php
unlink('mysqlitedb.db');
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);

$result = $stmt->execute();
var_dump($result->fetchArray());
?>

SQLite3::open
SQLite3::query
SQLite3


Executes an SQL query

SQLite3::prepare
SQLite3::querySingle
SQLite3
PHP Manual

SQLite3::query

(PHP 5 >= 5.3.0)

SQLite3::query — Executes an SQL query

Description

public SQLite3Result SQLite3::query ( string $query )

Executes an SQL query, returning an SQLite3Result object if the query returns results.

Parameters

query

The SQL query to execute.

Return Values

Returns an SQLite3Result object if the query returns results. Otherwise, returns TRUE if the query succeeded, FALSE on failure.

Examples

Example #1 SQLite3::query() example

<?php
$db = new SQLite3('mysqlitedb.db');

$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
    var_dump($row);
}
?>

SQLite3::prepare
SQLite3::querySingle
SQLite3


Executes a query and returns a single result

SQLite3::query
SQLite3::version
SQLite3
PHP Manual

SQLite3::querySingle

(PHP 5 >= 5.3.0)

SQLite3::querySingle — Executes a query and returns a single result

Description

public mixed SQLite3::querySingle ( string $query [, bool $entire_row = false ] )

Executes a query and returns a single result.

Parameters

query

The SQL query to execute.

entire_row

By default, querySingle returns the value of the first column returned by the query. If entire_row is TRUE, then it returns an array of the entire first row.

Return Values

Returns the value of the first column of results or an array of the entire first row (if entire_row is TRUE), otherwise FALSE on failure.

Examples

Example #1 SQLite3::querySingle() example

<?php
$db = new SQLite3('mysqlitedb.db');

var_dump($db->querySingle('SELECT username FROM user WHERE userid=1'));
print_r($db->querySingle('SELECT username, email FROM user WHERE userid=1', true));
?>

The above example will output something similar to:

string(5) "Scott"
Array
(
    [username] => Scott
    [email] => scott@example.com
)

SQLite3::query
SQLite3::version
SQLite3


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
SQLite3


Returns the SQLite3 library version as a string constant and as a number

SQLite3::querySingle
SQLite3Stmt
SQLite3
PHP Manual

SQLite3::version

(PHP 5 >= 5.3.0)

SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

Description

public array SQLite3::version ( void )

Returns the SQLite3 library version as a string constant and as a number.

Parameters

This function has no parameters.

Return Values

Returns an associative array with the keys "versionString" and "versionNumber".

Examples

Example #1 SQLite3::version() example

<?php
print_r(SQLite3::version());
?>

The above example will output something similar to:

Array
(
    [versionString] => 3.5.9
    [versionNumber] => 3005009
)

SQLite3::querySingle
SQLite3Stmt
SQLite3


Returns the name of the nth column

SQLite3Result
SQLite3Result::columnType
SQLite3Result
PHP Manual

SQLite3Result::columnName

(PHP 5 >= 5.3.0)

SQLite3Result::columnName — Returns the name of the nth column

Description

public string SQLite3Result::columnName ( int $column_number )

Returns the name of the column specified by the column_number .

Parameters

column_number

The numeric zero-based index of the column.

Return Values

Returns the string name of the column identified by column_number .

SQLite3Result
SQLite3Result::columnType
SQLite3Result


Returns the type of the nth column

SQLite3Result::columnName
SQLite3Result::fetchArray
SQLite3Result
PHP Manual

SQLite3Result::columnType

(PHP 5 >= 5.3.0)

SQLite3Result::columnType — Returns the type of the nth column

Description

public int SQLite3Result::columnType ( int $column_number )

Returns the type of the column identified by column_number .

Parameters

column_number

The numeric zero-based index of the column.

Return Values

Returns the data type index of the column identified by column_number (one of SQLITE3_INTEGER, SQLITE3_FLOAT, SQLITE3_TEXT, SQLITE3_BLOB, or SQLITE3_NULL).

SQLite3Result::columnName
SQLite3Result::fetchArray
SQLite3Result


Fetches a result row as an associative or numerically indexed array or both

SQLite3Result::columnType
SQLite3Result::finalize
SQLite3Result
PHP Manual

SQLite3Result::fetchArray

(PHP 5 >= 5.3.0)

SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both

Description

public array SQLite3Result::fetchArray ([ int $mode = SQLITE3_BOTH ] )

Fetches a result row as an associative or numerically indexed array or both. By default, fetches as both.

Parameters

mode

Controls how the next row will be returned to the caller. This value must be one of either SQLITE3_ASSOC, SQLITE3_NUM, or SQLITE3_BOTH.

  • SQLITE3_ASSOC: returns an array indexed by column name as returned in the corresponding result set

  • SQLITE3_NUM: returns an array indexed by column number as returned in the corresponding result set, starting at column 0

  • SQLITE3_BOTH: returns an array indexed by both column name and number as returned in the corresponding result set, starting at column 0

Return Values

Returns a result row as an associatively or numerically indexed array or both.

SQLite3Result::columnType
SQLite3Result::finalize
SQLite3Result


Closes the result set

SQLite3Result::fetchArray
SQLite3Result::numColumns
SQLite3Result
PHP Manual

SQLite3Result::finalize

(PHP 5 >= 5.3.0)

SQLite3Result::finalize — Closes the result set

Description

public bool SQLite3Result::finalize ( void )

Closes the result set.

Parameters

This function has no parameters.

Return Values

Returns TRUE.

SQLite3Result::fetchArray
SQLite3Result::numColumns
SQLite3Result


Returns the number of columns in the result set

SQLite3Result::finalize
SQLite3Result::reset
SQLite3Result
PHP Manual

SQLite3Result::numColumns

(PHP 5 >= 5.3.0)

SQLite3Result::numColumns — Returns the number of columns in the result set

Description

public int SQLite3Result::numColumns ( void )

Returns the number of columns in the result set.

Parameters

This function has no parameters.

Return Values

Returns the number of columns in the result set.

SQLite3Result::finalize
SQLite3Result::reset
SQLite3Result


Resets the result set back to the first row

SQLite3Result::numColumns
Sybase
SQLite3Result
PHP Manual

SQLite3Result::reset

(PHP 5 >= 5.3.0)

SQLite3Result::reset — Resets the result set back to the first row

Description

public bool SQLite3Result::reset ( void )

Resets the result set back to the first row.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the result set is successfully reset back to the first row, FALSE on failure.

SQLite3Result::numColumns
Sybase
SQLite3Result


Binds a parameter to a statement variable

SQLite3Stmt
SQLite3Stmt::bindValue
SQLite3Stmt
PHP Manual

SQLite3Stmt::bindParam

(PHP 5 >= 5.3.0)

SQLite3Stmt::bindParam — Binds a parameter to a statement variable

Description

public bool SQLite3Stmt::bindParam ( string $sql_param , mixed &$param [, int $type ] )

Binds a parameter to a statement variable.

Parameters

sql_param

An string identifying the statement variable to which the parameter should be bound.

param

The parameter to bind to a statement variable.

type

The data type of the parameter to bind.

  • SQLITE3_INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • SQLITE3_FLOAT: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • SQLITE3_TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  • SQLITE3_BLOB: The value is a blob of data, stored exactly as it was input.

  • SQLITE3_NULL: The value is a NULL value.

Return Values

Returns TRUE if the parameter is bound to the statement variable, FALSE on failure.

SQLite3Stmt
SQLite3Stmt::bindValue
SQLite3Stmt


Binds the value of a parameter to a statement variable

SQLite3Stmt::bindParam
SQLite3Stmt::clear
SQLite3Stmt
PHP Manual

SQLite3Stmt::bindValue

(PHP 5 >= 5.3.0)

SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable

Description

public bool SQLite3Stmt::bindValue ( string $sql_param , mixed $value [, int $type ] )

Binds the value of a parameter to a statement variable.

Parameters

sql_param

An string identifying the statement variable to which the value should be bound.

value

The value to bind to a statement variable.

type

The data type of the value to bind.

  • SQLITE3_INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • SQLITE3_FLOAT: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • SQLITE3_TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  • SQLITE3_BLOB: The value is a blob of data, stored exactly as it was input.

  • SQLITE3_NULL: The value is a NULL value.

Return Values

Returns TRUE if the value is bound to the statement variable, FALSE on failure.

Examples

Example #1 SQLite3Stmt::bindValue() example

<?php
unlink('mysqlitedb.db');
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);

$result = $stmt->execute();
var_dump($result->fetchArray());
?>

SQLite3Stmt::bindParam
SQLite3Stmt::clear
SQLite3Stmt


Clears all current bound parameters

SQLite3Stmt::bindValue
SQLite3Stmt::close
SQLite3Stmt
PHP Manual

SQLite3Stmt::clear

(PHP 5 >= 5.3.0)

SQLite3Stmt::clear — Clears all current bound parameters

Description

public bool SQLite3Stmt::clear ( void )

Clears all current bound parameters.

Parameters

This function has no parameters.

Return Values

Returns TRUE on successful clearing of bound parameters, FALSE on failure.

SQLite3Stmt::bindValue
SQLite3Stmt::close
SQLite3Stmt


Closes the prepared statement

SQLite3Stmt::clear
SQLite3Stmt::execute
SQLite3Stmt
PHP Manual

SQLite3Stmt::close

(PHP 5 >= 5.3.0)

SQLite3Stmt::close — Closes the prepared statement

Description

public bool SQLite3Stmt::close ( void )

Closes the prepared statement.

Parameters

This function has no parameters.

Return Values

Returns TRUE

SQLite3Stmt::clear
SQLite3Stmt::execute
SQLite3Stmt


Executes a prepared statement and returns a result set object

SQLite3Stmt::close
SQLite3Stmt::paramCount
SQLite3Stmt
PHP Manual

SQLite3Stmt::execute

(PHP 5 >= 5.3.0)

SQLite3Stmt::execute — Executes a prepared statement and returns a result set object

Description

public SQLite3Result SQLite3Stmt::execute ( void )

Executes a prepared statement and returns a result set object.

Parameters

This function has no parameters.

Return Values

Returns an SQLite3Result object on successful execution of the prepared statement, FALSE on failure.

SQLite3Stmt::close
SQLite3Stmt::paramCount
SQLite3Stmt


Returns the number of parameters within the prepared statement

SQLite3Stmt::execute
SQLite3Stmt::reset
SQLite3Stmt
PHP Manual

SQLite3Stmt::paramCount

(PHP 5 >= 5.3.0)

SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement

Description

public int SQLite3Stmt::paramCount ( void )

Returns the number of parameters within the prepared statement.

Parameters

This function has no parameters.

Return Values

Returns the number of parameters within the prepared statement.

SQLite3Stmt::execute
SQLite3Stmt::reset
SQLite3Stmt


Resets the prepared statement

SQLite3Stmt::paramCount
SQLite3Result
SQLite3Stmt
PHP Manual

SQLite3Stmt::reset

(PHP 5 >= 5.3.0)

SQLite3Stmt::reset — Resets the prepared statement

Description

public bool SQLite3Stmt::reset ( void )

Resets the prepared statement to its state prior to execution. All bindings remain intact after reset.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the statement is successfully reset, FALSE on failure.

SQLite3Stmt::paramCount
SQLite3Result
SQLite3Stmt


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

SQLite Configure Options
Name | Default | Changeable | Changelog
sqlite.assoc_case | "0" | PHP_INI_ALL | Available since PHP 5.0.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

sqlite.assoc_case int

Whether to use mixed case (0), upper case (1) or lower case (2) hash indexes.

This option is primarily useful when you need compatibility with other database systems, where the names of the columns are always returned as uppercase or lowercase, regardless of the case of the actual field names in the database schema.

The SQLite library returns the column names in their natural case (that matches the case you used in your schema). When sqlite.assoc_case is set to 0 the natural case will be preserved. When it is set to 1 or 2, PHP will apply case folding on the hash keys to upper- or lower-case the keys, respectively.

Use of this option incurs a slight performance penalty, but is MUCH faster than performing the case folding yourself using PHP script.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The functions sqlite_fetch_array() and sqlite_current() use a constant for the different types of result arrays. The following constants are defined:

SQLite result type constants
SQLITE_ASSOC (int)
Columns are returned into the array having the field name as the array index.
SQLITE_BOTH (int)
Columns are returned into the array having both a numerical index and the field name as the array index.
SQLITE_NUM (int)
Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

A number of functions may return status codes. The following constants are defined:

SQLite status code constants
SQLITE_OK (int)
Successful result.
SQLITE_ERROR (int)
SQL error or missing database.
SQLITE_INTERNAL (int)
An internal logic error in SQLite.
SQLITE_PERM (int)
Access permission denied.
SQLITE_ABORT (int)
Callback routine requested an abort.
SQLITE_BUSY (int)
The database file is locked.
SQLITE_LOCKED (int)
A table in the database is locked.
SQLITE_NOMEM (int)
Memory allocation failed.
SQLITE_READONLY (int)
Attempt to write a readonly database.
SQLITE_INTERRUPT (int)
Operation terminated internally.
SQLITE_IOERR (int)
Disk I/O error occurred.
SQLITE_NOTADB (int)
File opened that is not a database file.
SQLITE_CORRUPT (int)
The database disk image is malformed.
SQLITE_FORMAT (int)
Auxiliary database format error.
SQLITE_NOTFOUND (int)
(Internal) Table or record not found.
SQLITE_FULL (int)
Insertion failed because database is full.
SQLITE_CANTOPEN (int)
Unable to open the database file.
SQLITE_PROTOCOL (int)
Database lock protocol error.
SQLITE_EMPTY (int)
(Internal) Database table is empty.
SQLITE_SCHEMA (int)
The database schema changed.
SQLITE_TOOBIG (int)
Too much data for one row of a table.
SQLITE_CONSTRAINT (int)
Abort due to constraint violation.
SQLITE_MISMATCH (int)
Data type mismatch.
SQLITE_MISUSE (int)
Library used incorrectly.
SQLITE_NOLFS (int)
Uses of OS features not supported on host.
SQLITE_AUTH (int)
Authorized failed.
SQLITE_ROW (int)
Internal process has another row ready.
SQLITE_DONE (int)
Internal process has finished executing.
Resource Types
SQLite Functions
SQLite


Installation

As of PHP 5 this extension is enabled by default, so simply do not disable it and it'll be available.

Caution

Do not use the PECL version of this extension, as it is unmaintained. Always use the SQLite extension that comes with the PHP sources even while compiling as shared. In this case the sources are in php-src-dir/ext/sqlite and the phpize method of building applies.

Windows users must enable php_sqlite.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Windows builds must also enable PDO because as of PHP 5.1.0 it depends on it. So, php.ini will end up with something like this:

extension=php_pdo.dll
extension=php_sqlite.dll

On Linux or Unix operating systems, if you build PDO as a shared extension, you must build SQLite as a shared extension using the --with-sqlite=shared configure option.

The PHP 5.0.x series of Windows builds enabled this extension by default, where no DLL file is necessary.

SQLite 3 is supported through PDO SQLite.

Note: Windows installation for unprivileged accounts
On Windows operating systems, unprivileged accounts don't have the TMP environment variable set by default. This will make sqlite create temporary files in the windows directory, which is not desirable. So, you should set the TMP environment variable for the web server or the user account the web server is running under. If Apache is your web server, you can accomplish this via a SetEnv directive in your httpd.conf file. For example:

SetEnv TMP c:/temp

If you are unable to establish this setting at the server level, you can implement the setting in your script:

putenv('TMP=C:/temp');

The setting must refer to a directory that the web server has permission to create files in and subsequently write to and delete the files it created. Otherwise, you may receive the following error message: malformed database schema - unable to open a temporary database file for storing temporary tables

Requirements
Runtime Configuration
Installing/Configuring


Requirements

The SQLite extension is enabled by default as of PHP 5. Before that time the SQLite library is needed.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

There are two resources used in the SQLite Interface. The first one is the database connection, the second one the result set.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
SQLite


Predefined Constants

This extension has no constants defined.

Resource Types
Statistic Functions
Statistics


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/stats.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

No external libraries are needed. The extension comes bundled with the libraries used.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Statistics


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

MOD_COLOR (integer)
MOD_MATRIX (integer)
TYPE_PUSHBUTTON (integer)
TYPE_MENUBUTTON (integer)
BSHitTest (float)
BSDown (float)
BSOver (float)
BSUp (float)
OverDowntoIdle (integer)
IdletoOverDown (integer)
OutDowntoIdle (integer)
OutDowntoOverDown (integer)
OverDowntoOutDown (integer)
OverUptoOverDown (integer)
OverUptoIdle (integer)
IdletoOverUp (integer)
ButtonEnter (integer)
ButtonExit (integer)
MenuEnter (integer)
MenuExit (integer)
Resource Types
Examples
SWF


Examples

Table of Contents

  • Basic Usage
Predefined Constants
Basic Usage
SWF


Basic Usage

Once you've successfully installed PHP with Shockwave Flash support you can then go about creating Shockwave files from PHP. You would be surprised at what you can do, take the following code:

Example #1 SWF example

<?php
swf_openfile("test.swf", 256, 256, 30, 1, 1, 1);
swf_ortho2(-100, 100, -100, 100);
swf_defineline(1, -70, 0, 70, 0, .2);
swf_definerect(4, 60, -10, 70, 0, 0);
swf_definerect(5, -60, 0, -70, 10, 0);
swf_addcolor(0, 0, 0, 0);

swf_definefont(10, "Mod");
swf_fontsize(5);
swf_fontslant(10);
swf_definetext(11, "This be Flash wit PHP!", 1);

swf_pushmatrix();
swf_translate(-50, 80, 0);
swf_placeobject(11, 60);
swf_popmatrix();

for ($i = 0; $i < 30; $i++) {
    $p = $i/(30-1);
    swf_pushmatrix();
    swf_scale(1-($p*.9), 1, 1);
    swf_rotate(60*$p, 'z');
    swf_translate(20+20*$p, $p/1.5, 0);
    swf_rotate(270*$p,  'z');
    swf_addcolor($p, 0, $p/1.2, -$p);
    swf_placeobject(1, 50);
    swf_placeobject(4, 50);
    swf_placeobject(5, 50);
    swf_popmatrix();
    swf_showframe();
}

for ($i = 0; $i < 30; $i++) {
    swf_removeobject(50);
    if (($i%4) == 0) {
        swf_showframe();
    }
}

swf_startdoaction();
swf_actionstop();
swf_enddoaction();

swf_closefile();
?>

Examples
SWF Functions
Examples


Installation

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL SVN here: » http://svn.php.net/viewvc/pecl/swf.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.0.0

Requirements
Runtime Configuration
Installing/Configuring


Requirements

You need the libswf library to compile PHP with support for this extension. You can download libswf at » ftp://ftp.sgi.com/sgi/graphics/grafica/flash/.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
SWF


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Sybase configuration options
Name | Default | Changeable | Changelog
sybase.allow_persistent | "1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_persistent | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_links | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.interface_file | "/usr/sybase/interfaces" | PHP_INI_SYSTEM |
sybase.min_error_severity | "10" | PHP_INI_ALL |
sybase.min_message_severity | "10" | PHP_INI_ALL |
sybase.compatability_mode | "0" | PHP_INI_ALL |
magic_quotes_sybase | "0" | PHP_INI_ALL | Deprecated in PHP 5.3.0. Removed in PHP 6.0.0.

Here's a short explanation of the configuration directives.

sybase.allow_persistent boolean

Whether to allow persistent Sybase connections.

sybase.max_persistent integer

The maximum number of persistent Sybase connections per process. -1 means no limit.

sybase.max_links integer

The maximum number of Sybase connections per process, including persistent connections. -1 means no limit.

sybase.min_error_severity integer

Minimum error severity to display.

sybase.min_message_severity integer

Minimum message severity to display.

magic_quotes_sybase boolean

If magic_quotes_sybase is on, a single-quote is escaped with a single-quote instead of a backslash if magic_quotes_gpc or magic_quotes_runtime are enabled. This setting is also respected by addslashes() and stripslashes().

Note: Note that when magic_quotes_sybase is ON it completely overrides magic_quotes_gpc . In this case even when magic_quotes_gpc is enabled neither double quotes, backslashes or NUL's will be escaped.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

Sybase-CT configuration options
Name | Default | Changeable | Changelog
sybct.allow_persistent | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.max_persistent | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.max_links | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.min_server_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.min_client_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.hostname | NULL | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Available since PHP 4.3.0.

Here's a short explanation of the configuration directives.

sybct.allow_persistent boolean

Whether to allow persistent Sybase-CT connections. The default is on.

sybct.max_persistent integer

The maximum number of persistent Sybase-CT connections per process. The default is -1 meaning unlimited.

sybct.max_links integer

The maximum number of Sybase-CT connections per process, including persistent connections. The default is -1 meaning unlimited.

sybct.min_server_severity integer

Server messages with severity greater than or equal to sybct.min_server_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_server_severity(). The default is 10 which reports errors of information severity or greater.

sybct.min_client_severity integer

Client library messages with severity greater than or equal to sybct.min_client_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_client_severity(). The default is 10 which effectively disables reporting.

sybct.login_timeout integer

The maximum time in seconds to wait for a connection attempt to succeed before returning failure. Note that if max_execution_time has been exceeded when a connection attempt times out, your script will be terminated before it can take action on failure. The default is one minute.

sybct.timeout integer

The maximum time in seconds to wait for a select_db or query operation to succeed before returning failure. Note that if max_execution_time has been exceeded when an operation times out, your script will be terminated before it can take action on failure. The default is no limit.

sybct.hostname string

The name of the host you claim to be connecting from, for display by sp_who. The default is none.

sybct.deadlock_retry_count int

Allows you to define how often deadlocks are to be retried. The default is 0, value -1 means "forever".

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

Resource Types
Sybase Functions
Sybase


Installation

To enable Sybase-DB support configure PHP --with-sybase[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase. To enable Sybase-CT support configure PHP --with-sybase-ct[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase.

Note: As of PHP 5.3.0, the Sybase extension has been superseded by the sybase_ct extension and is no longer maintained. To continue using sybase you must use the sybase_ct extension.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Sybase


Returns the title string from a ID3 tag

KTaglib_Tag
KTaglib_Tag::getArtist
KTaglib_Tag
PHP Manual

KTaglib_Tag::getAlbum

(0.0.1)

KTaglib_Tag::getAlbum — Returns the title string from a ID3 tag

Description

public string KTaglib_Tag::getAlbum ( void )

Returns the album string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the album string

KTaglib_Tag
KTaglib_Tag::getArtist
KTaglib_Tag


Returns the artist string from a ID3 tag

KTaglib_Tag::getAlbum
KTaglib_Tag::getComment
KTaglib_Tag
PHP Manual

KTaglib_Tag::getArtist

(0.0.1)

KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag

Description

public string KTaglib_Tag::getArtist ( void )

Returns the artist string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the artist string

KTaglib_Tag::getAlbum
KTaglib_Tag::getComment
KTaglib_Tag


Returns the comment from a ID3 tag

KTaglib_Tag::getArtist
KTaglib_Tag::getGenre
KTaglib_Tag
PHP Manual

KTaglib_Tag::getComment

(0.0.1)

KTaglib_Tag::getComment — Returns the comment from a ID3 tag

Description

public string KTaglib_Tag::getComment ( void )

Returns the comment of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the comment string

KTaglib_Tag::getArtist
KTaglib_Tag::getGenre
KTaglib_Tag


Returns the genre from a ID3 tag

KTaglib_Tag::getComment
KTaglib_Tag::getTitle
KTaglib_Tag
PHP Manual

KTaglib_Tag::getGenre

(0.0.1)

KTaglib_Tag::getGenre — Returns the genre from a ID3 tag

Description

public string KTaglib_Tag::getGenre ( void )

Returns the genre of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the genre string

KTaglib_Tag::getComment
KTaglib_Tag::getTitle
KTaglib_Tag


Returns the title string from a ID3 tag

KTaglib_Tag::getGenre
KTaglib_Tag::getTrack
KTaglib_Tag
PHP Manual

KTaglib_Tag::getTitle

(0.0.1)

KTaglib_Tag::getTitle — Returns the title string from a ID3 tag

Description

public string KTaglib_Tag::getTitle ( void )

Returns the title string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the title string

KTaglib_Tag::getGenre
KTaglib_Tag::getTrack
KTaglib_Tag


Returns the track number from a ID3 tag

KTaglib_Tag::getTitle
KTaglib_Tag::getYear
KTaglib_Tag
PHP Manual

KTaglib_Tag::getTrack

(0.0.1)

KTaglib_Tag::getTrack — Returns the track number from a ID3 tag

Description

public int KTaglib_Tag::getTrack ( void )

Returns the track number of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the track number as an integer

KTaglib_Tag::getTitle
KTaglib_Tag::getYear
KTaglib_Tag


Returns the year from a ID3 tag

KTaglib_Tag::getTrack
KTaglib_Tag::isEmpty
KTaglib_Tag
PHP Manual

KTaglib_Tag::getYear

(0.0.1)

KTaglib_Tag::getYear — Returns the year from a ID3 tag

Description

public int KTaglib_Tag::getYear ( void )

Returns the year of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the year as an integer

KTaglib_Tag::getTrack
KTaglib_Tag::isEmpty
KTaglib_Tag


Returns true if the tag is empty

KTaglib_Tag::getYear
KTaglib_ID3v2_Tag
KTaglib_Tag
PHP Manual

KTaglib_Tag::isEmpty

(0.0.1)

KTaglib_Tag::isEmpty — Returns true if the tag is empty

Description

public bool KTaglib_Tag::isEmpty ( void )

Returns true if the tag exists, but is empty. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns true if the tag is empty, otherwise false.

KTaglib_Tag::getYear
KTaglib_ID3v2_Tag
KTaglib_Tag


List of Supported Timezones

Table of Contents

  • Africa
  • America
  • Antarctica
  • Arctic
  • Asia
  • Atlantic
  • Australia
  • Europe
  • Indian
  • Pacific
  • Others

Here you'll find the complete list of timezones supported by PHP, which are meant to be used with e.g. date_default_timezone_set().

Note: The latest version of the timezone database can be installed via PECL's » timezonedb.

Note: This list is based upon the timezone database version 2009.21.

Predefined Constants
Africa
Date/Time


Africa

Africa
Africa/Abidjan | Africa/Accra | Africa/Addis_Ababa | Africa/Algiers | Africa/Asmara
Africa/Asmera | Africa/Bamako | Africa/Bangui | Africa/Banjul | Africa/Bissau
Africa/Blantyre | Africa/Brazzaville | Africa/Bujumbura | Africa/Cairo | Africa/Casablanca
Africa/Ceuta | Africa/Conakry | Africa/Dakar | Africa/Dar_es_Salaam | Africa/Djibouti
Africa/Douala | Africa/El_Aaiun | Africa/Freetown | Africa/Gaborone | Africa/Harare
Africa/Johannesburg | Africa/Kampala | Africa/Khartoum | Africa/Kigali | Africa/Kinshasa
Africa/Lagos | Africa/Libreville | Africa/Lome | Africa/Luanda | Africa/Lubumbashi
Africa/Lusaka | Africa/Malabo | Africa/Maputo | Africa/Maseru | Africa/Mbabane
Africa/Mogadishu | Africa/Monrovia | Africa/Nairobi | Africa/Ndjamena | Africa/Niamey
Africa/Nouakchott | Africa/Ouagadougou | Africa/Porto-Novo | Africa/Sao_Tome | Africa/Timbuktu
Africa/Tripoli | Africa/Tunis | Africa/Windhoek |  |
List of Supported Timezones
America
List of Supported Timezones


America

America
America/Adak | America/Anchorage | America/Anguilla | America/Antigua | America/Araguaina
America/Argentina/Buenos_Aires | America/Argentina/Catamarca | America/Argentina/ComodRivadavia | America/Argentina/Cordoba | America/Argentina/Jujuy
America/Argentina/La_Rioja | America/Argentina/Mendoza | America/Argentina/Rio_Gallegos | America/Argentina/Salta | America/Argentina/San_Juan
America/Argentina/San_Luis | America/Argentina/Tucuman | America/Argentina/Ushuaia | America/Aruba | America/Asuncion
America/Atikokan | America/Atka | America/Bahia | America/Barbados | America/Belem
America/Belize | America/Blanc-Sablon | America/Boa_Vista | America/Bogota | America/Boise
America/Buenos_Aires | America/Cambridge_Bay | America/Campo_Grande | America/Cancun | America/Caracas
America/Catamarca | America/Cayenne | America/Cayman | America/Chicago | America/Chihuahua
America/Coral_Harbour | America/Cordoba | America/Costa_Rica | America/Cuiaba | America/Curacao
America/Danmarkshavn | America/Dawson | America/Dawson_Creek | America/Denver | America/Detroit
America/Dominica | America/Edmonton | America/Eirunepe | America/El_Salvador | America/Ensenada
America/Fort_Wayne | America/Fortaleza | America/Glace_Bay | America/Godthab | America/Goose_Bay
America/Grand_Turk | America/Grenada | America/Guadeloupe | America/Guatemala | America/Guayaquil
America/Guyana | America/Halifax | America/Havana | America/Hermosillo | America/Indiana/Indianapolis
America/Indiana/Knox | America/Indiana/Marengo | America/Indiana/Petersburg | America/Indiana/Tell_City | America/Indiana/Vevay
America/Indiana/Vincennes | America/Indiana/Winamac | America/Indianapolis | America/Inuvik | America/Iqaluit
America/Jamaica | America/Jujuy | America/Juneau | America/Kentucky/Louisville | America/Kentucky/Monticello
America/Knox_IN | America/La_Paz | America/Lima | America/Los_Angeles | America/Louisville
America/Maceio | America/Managua | America/Manaus | America/Marigot | America/Martinique
America/Mazatlan | America/Mendoza | America/Menominee | America/Merida | America/Mexico_City
America/Miquelon | America/Moncton | America/Monterrey | America/Montevideo | America/Montreal
America/Montserrat | America/Nassau | America/New_York | America/Nipigon | America/Nome
America/Noronha | America/North_Dakota/Center | America/North_Dakota/New_Salem | America/Panama | America/Pangnirtung
America/Paramaribo | America/Phoenix | America/Port-au-Prince | America/Port_of_Spain | America/Porto_Acre
America/Porto_Velho | America/Puerto_Rico | America/Rainy_River | America/Rankin_Inlet | America/Recife
America/Regina | America/Resolute | America/Rio_Branco | America/Rosario | America/Santarem
America/Santiago | America/Santo_Domingo | America/Sao_Paulo | America/Scoresbysund | America/Shiprock
America/St_Barthelemy | America/St_Johns | America/St_Kitts | America/St_Lucia | America/St_Thomas
America/St_Vincent | America/Swift_Current | America/Tegucigalpa | America/Thule | America/Thunder_Bay
America/Tijuana | America/Toronto | America/Tortola | America/Vancouver | America/Virgin
America/Whitehorse | America/Winnipeg | America/Yakutat | America/Yellowknife |
Africa
Antarctica
List of Supported Timezones


Antarctica

Antarctica
Antarctica/Casey | Antarctica/Davis | Antarctica/DumontDUrville | Antarctica/Mawson | Antarctica/McMurdo
Antarctica/Palmer | Antarctica/Rothera | Antarctica/South_Pole | Antarctica/Syowa | Antarctica/Vostok
America
Arctic
List of Supported Timezones


Arctic

Arctic
Arctic/Longyearbyen
Antarctica
Asia
List of Supported Timezones


Asia

Asia
Asia/Aden | Asia/Almaty | Asia/Amman | Asia/Anadyr | Asia/Aqtau
Asia/Aqtobe | Asia/Ashgabat | Asia/Ashkhabad | Asia/Baghdad | Asia/Bahrain
Asia/Baku | Asia/Bangkok | Asia/Beirut | Asia/Bishkek | Asia/Brunei
Asia/Calcutta | Asia/Choibalsan | Asia/Chongqing | Asia/Chungking | Asia/Colombo
Asia/Dacca | Asia/Damascus | Asia/Dhaka | Asia/Dili | Asia/Dubai
Asia/Dushanbe | Asia/Gaza | Asia/Harbin | Asia/Ho_Chi_Minh | Asia/Hong_Kong
Asia/Hovd | Asia/Irkutsk | Asia/Istanbul | Asia/Jakarta | Asia/Jayapura
Asia/Jerusalem | Asia/Kabul | Asia/Kamchatka | Asia/Karachi | Asia/Kashgar
Asia/Kathmandu | Asia/Katmandu | Asia/Kolkata | Asia/Krasnoyarsk | Asia/Kuala_Lumpur
Asia/Kuching | Asia/Kuwait | Asia/Macao | Asia/Macau | Asia/Magadan
Asia/Makassar | Asia/Manila | Asia/Muscat | Asia/Nicosia | Asia/Novokuznetsk
Asia/Novosibirsk | Asia/Omsk | Asia/Oral | Asia/Phnom_Penh | Asia/Pontianak
Asia/Pyongyang | Asia/Qatar | Asia/Qyzylorda | Asia/Rangoon | Asia/Riyadh
Asia/Saigon | Asia/Sakhalin | Asia/Samarkand | Asia/Seoul | Asia/Shanghai
Asia/Singapore | Asia/Taipei | Asia/Tashkent | Asia/Tbilisi | Asia/Tehran
Asia/Tel_Aviv | Asia/Thimbu | Asia/Thimphu | Asia/Tokyo | Asia/Ujung_Pandang
Asia/Ulaanbaatar | Asia/Ulan_Bator | Asia/Urumqi | Asia/Vientiane | Asia/Vladivostok
Asia/Yakutsk | Asia/Yekaterinburg | Asia/Yerevan |  |
Arctic
Atlantic
List of Supported Timezones


Atlantic

Atlantic
Atlantic/Azores | Atlantic/Bermuda | Atlantic/Canary | Atlantic/Cape_Verde | Atlantic/Faeroe
Atlantic/Faroe | Atlantic/Jan_Mayen | Atlantic/Madeira | Atlantic/Reykjavik | Atlantic/South_Georgia
Atlantic/St_Helena | Atlantic/Stanley |  |  |
Asia
Australia
List of Supported Timezones


Australia

Australia
Australia/ACT | Australia/Adelaide | Australia/Brisbane | Australia/Broken_Hill | Australia/Canberra
Australia/Currie | Australia/Darwin | Australia/Eucla | Australia/Hobart | Australia/LHI
Australia/Lindeman | Australia/Lord_Howe | Australia/Melbourne | Australia/North | Australia/NSW
Australia/Perth | Australia/Queensland | Australia/South | Australia/Sydney | Australia/Tasmania
Australia/Victoria | Australia/West | Australia/Yancowinna |  |
Atlantic
Europe
List of Supported Timezones


Europe

Europe
Europe/Amsterdam | Europe/Andorra | Europe/Athens | Europe/Belfast | Europe/Belgrade
Europe/Berlin | Europe/Bratislava | Europe/Brussels | Europe/Bucharest | Europe/Budapest
Europe/Chisinau | Europe/Copenhagen | Europe/Dublin | Europe/Gibraltar | Europe/Guernsey
Europe/Helsinki | Europe/Isle_of_Man | Europe/Istanbul | Europe/Jersey | Europe/Kaliningrad
Europe/Kiev | Europe/Lisbon | Europe/Ljubljana | Europe/London | Europe/Luxembourg
Europe/Madrid | Europe/Malta | Europe/Mariehamn | Europe/Minsk | Europe/Monaco
Europe/Moscow | Europe/Nicosia | Europe/Oslo | Europe/Paris | Europe/Podgorica
Europe/Prague | Europe/Riga | Europe/Rome | Europe/Samara | Europe/San_Marino
Europe/Sarajevo | Europe/Simferopol | Europe/Skopje | Europe/Sofia | Europe/Stockholm
Europe/Tallinn | Europe/Tirane | Europe/Tiraspol | Europe/Uzhgorod | Europe/Vaduz
Europe/Vatican | Europe/Vienna | Europe/Vilnius | Europe/Volgograd | Europe/Warsaw
Europe/Zagreb | Europe/Zaporozhye | Europe/Zurich |  |
Australia
Indian
List of Supported Timezones


Indian

Indian
Indian/Antananarivo | Indian/Chagos | Indian/Christmas | Indian/Cocos | Indian/Comoro
Indian/Kerguelen | Indian/Mahe | Indian/Maldives | Indian/Mauritius | Indian/Mayotte
Indian/Reunion |  |  |  |
Europe
Pacific
List of Supported Timezones


Others

Others
Brazil/Acre | Brazil/DeNoronha | Brazil/East | Brazil/West | Canada/Atlantic
Canada/Central | Canada/East-Saskatchewan | Canada/Eastern | Canada/Mountain | Canada/Newfoundland
Canada/Pacific | Canada/Saskatchewan | Canada/Yukon | CET | Chile/Continental
Chile/EasterIsland | CST6CDT | Cuba | EET | Egypt
Eire | EST | EST5EDT | Etc/GMT | Etc/GMT+0
Etc/GMT+1 | Etc/GMT+10 | Etc/GMT+11 | Etc/GMT+12 | Etc/GMT+2
Etc/GMT+3 | Etc/GMT+4 | Etc/GMT+5 | Etc/GMT+6 | Etc/GMT+7
Etc/GMT+8 | Etc/GMT+9 | Etc/GMT-0 | Etc/GMT-1 | Etc/GMT-10
Etc/GMT-11 | Etc/GMT-12 | Etc/GMT-13 | Etc/GMT-14 | Etc/GMT-2
Etc/GMT-3 | Etc/GMT-4 | Etc/GMT-5 | Etc/GMT-6 | Etc/GMT-7
Etc/GMT-8 | Etc/GMT-9 | Etc/GMT0 | Etc/Greenwich | Etc/UCT
Etc/Universal | Etc/UTC | Etc/Zulu | Factory | GB
GB-Eire | GMT | GMT+0 | GMT-0 | GMT0
Greenwich | Hongkong | HST | Iceland | Iran
Israel | Jamaica | Japan | Kwajalein | Libya
MET | Mexico/BajaNorte | Mexico/BajaSur | Mexico/General | MST
MST7MDT | Navajo | NZ | NZ-CHAT | Poland
Portugal | PRC | PST8PDT | ROC | ROK
Singapore | Turkey | UCT | Universal | US/Alaska
US/Aleutian | US/Arizona | US/Central | US/East-Indiana | US/Eastern
US/Hawaii | US/Indiana-Starke | US/Michigan | US/Mountain | US/Pacific
US/Pacific-New | US/Samoa | UTC | W-SU | WET
Zulu |  |  |  |
Warning

Please do not use any of the timezones listed here (besides UTC), they only exist for backward compatible reasons.

Pacific
DateTime
List of Supported Timezones


Pacific

Pacific
Pacific/Apia | Pacific/Auckland | Pacific/Chatham | Pacific/Easter | Pacific/Efate
Pacific/Enderbury | Pacific/Fakaofo | Pacific/Fiji | Pacific/Funafuti | Pacific/Galapagos
Pacific/Gambier | Pacific/Guadalcanal | Pacific/Guam | Pacific/Honolulu | Pacific/Johnston
Pacific/Kiritimati | Pacific/Kosrae | Pacific/Kwajalein | Pacific/Majuro | Pacific/Marquesas
Pacific/Midway | Pacific/Nauru | Pacific/Niue | Pacific/Norfolk | Pacific/Noumea
Pacific/Pago_Pago | Pacific/Palau | Pacific/Pitcairn | Pacific/Ponape | Pacific/Port_Moresby
Pacific/Rarotonga | Pacific/Saipan | Pacific/Samoa | Pacific/Tahiti | Pacific/Tarawa
Pacific/Tongatapu | Pacific/Truk | Pacific/Wake | Pacific/Wallis | Pacific/Yap
Indian
Others
List of Supported Timezones


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

tokyo_tyrant Configure Options
Name | Default | Changeable | Changelog
tokyo_tyrant.default_timeout | 2.0 | PHP_INI_ALL |
tokyo_tyrant.session_salt | NULL | PHP_INI_ALL |
tokyo_tyrant.key_prefix | NULL | PHP_INI_ALL |
tokyo_tyrant.allow_failover | 1 | PHP_INI_ALL |
tokyo_tyrant.fail_threshold | 5 | PHP_INI_ALL |
tokyo_tyrant.health_check_divisor | 1000 | PHP_INI_ALL |
tokyo_tyrant.php_expiration | 0 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

tokyo_tyrant.default_timeout integer

Default timeout when connecting to databases

tokyo_tyrant.session_salt string

The secret that is used to salt session id

tokyo_tyrant.key_prefix string

Prefix all keys with this string. The prefix is transparent to the developer but helps making sure that keys won't collide if multiple applications are using the same database.

tokyo_tyrant.allow_failover integer

Whether to allow session failover in case a server dies.

tokyo_tyrant.fail_threshold integer

How many read/write or connection failures is allowed before server is marked as failed.

tokyo_tyrant.health_check_divisor integer

Defines the divisor for the health check probability. If there are failed servers and the probability matches, the servers are health checked and in case the server seems healthy, it will be added back to the pool.

tokyo_tyrant.php_expiration integer

Whether to use built in session expiration mechanism or delegate the expiration to a lua-script on the server-side.

Installation
Resource Types
Installing/Configuring


Predefined Constants

TokyoTyrant constants

Resource Types
Examples
tokyo_tyrant


Examples

Basic usage

Example #1 Putting and getting a key-value pair

<?php
$tt = new TokyoTyrant("localhost");
$tt->put("key", "value");
echo $tt->get("key");
?>

The above example will output:

value
Predefined Constants
TokyoTyrant
tokyo_tyrant


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/tokyo_tyrant

Configure options

  • --with-tokyo-tyrant[=DIR] DIR is the prefix to the Tokyo Tyrant installation
  • --with-tokyo-cabinet-dir[=DIR] DIR is the prefix to the Tokyo Cabinet installation
  • --disable-tokyo-tyrant-session Disable Tokyo Tyrant session handler support

Enabling the extension

The extension can be enabled by adding extension=tokyo_tyrant.so to the INI-configuration

Running Tokyo Tyrant for the session handler

ttserver -port 2000 -ext /path/to/expire.lua -extpc expire 30.0 '/tmp/sessions.tct#idx=ts:dec'

Note: expire.lua is included in the tokyo_tyrant extension source distribution

Configuring session handler

  • tokyo_tyrant.session_salt="randomlongstring"
  • session.save_handler=tokyo_tyrant
  • session.save_path="tcp://hostname1:2000,tcp://hostname2:2000"

Note: It is important to make sure that tokyo_tyrant.session_salt matches on all servers.

How it works?

The session handler creates a session id like the following: 8b0e27a823fa4a6cf7246945b82c1d51-a5eadbbed1f2075952900628456bfd6830541629-0-5460

The parts from left to right:

  • Session id - Generated session id
  • Checksum - Checksum of session salt, session id, node id and primary key
  • Node id - The id of the node where the session maps to
  • Primary key - The primary key of the row where the session is stored

The checksum contains SHA1 sum of the node id, primary key, session id and the salt which is known only on the server side. This allows quick mapping of session id to node and primary key since there is no need to do an additional search. During session id regeneration only the parts 1 and 2 change but the mapping to the node and primary key stays constant.

In case some of the nodes fail tokyo_tyrant.allow_failover, tokyo_tyrant.fail_threshold and tokyo_tyrant.health_check_divisor INI-settings control the behavior during failover. If failover is allowed the session handler will map the session to a healthy node and creates a new empty session.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

Before using this extension Tokyo Cabinet and Tokyo Tyrant must be installed.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
tokyo_tyrant


Construct a new TokyoTyrant object

TokyoTyrant::connectUri
TokyoTyrant::copy
TokyoTyrant
PHP Manual

TokyoTyrant::__construct

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::__construct — Construct a new TokyoTyrant object

Description

TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )

Constructs a new TokyoTyrant object and optionally connects to the database

Parameters

host

The hostname. Default: NULL

port

The hostname. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Return Values

Throws TokyoTyrantException if connection to database fails

See Also

  • TokyoTyrant::connect - Connect to a database
  • TokyoTyrant::connectUri - Connects to a database

TokyoTyrant::connectUri
TokyoTyrant::copy
TokyoTyrant


Adds to a numeric key

TokyoTyrant
TokyoTyrant::connect
TokyoTyrant
PHP Manual

TokyoTyrant::add

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::add — Adds to a numeric key

Description

public number TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] )

Adds to an int or double value. This increments the value by the given amount and returns the new value. If the key does not exist a new key is created with initial value of the increment parameter.

Parameters

key

The string key

increment

The amount to increment

type

TokyoTyrant::RDB_RECINT or TokyoTyrant::RDB_RECDBL constant. If this parameter is omitted the type is guessed from the increment parameters type.

Return Values

Returns the new value on success

Examples

Example #1 TokyoTyrant::add example

<?php
$tt = new TokyoTyrant("localhost", TokyoTyrant::RDBDEF_PORT);
/* Adds integer 3 to key and creates a new key */
$tt->add("test", 3);

/* String value is converted to double */
echo $tt->add("test", "3.5", TokyoTyrant::RDB_RECDBL);
?>

The above example will output something similar to:

6.5

See Also

  • TokyoTyrant::put - Puts values
  • TokyoTyrant::putcat - Concatenates to a record
  • TokyoTyrant::putkeep - Puts a record

TokyoTyrant
TokyoTyrant::connect
TokyoTyrant


Connect to a database

TokyoTyrant::add
TokyoTyrant::connectUri
TokyoTyrant
PHP Manual

TokyoTyrant::connect

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::connect — Connect to a database

Description

public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )

Connects to a remote database

Parameters

host

The hostname

port

The port. Default: 1978

persistent

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::connect example

<?php
$tt = new TokyoTyrant();
$tt->connect("localhost", TokyoTyrant::RDBDEF_PORT)->put("test", "value");
?>

See Also

  • TokyoTyrant::connectUri - Connects to a database

TokyoTyrant::add
TokyoTyrant::connectUri
TokyoTyrant


Connects to a database

TokyoTyrant::connect
TokyoTyrant::__construct
TokyoTyrant
PHP Manual

TokyoTyrant::connectUri

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::connectUri — Connects to a database

Description

public TokyoTyrant TokyoTyrant::connectUri ( string $uri )

Connects to a database using an uri

Parameters

uri

An URI to the database. For example tcp://localhost:1979/

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::connectUri example

<?php
$tt = new TokyoTyrant();
$tt->connectUri("tcp://localhost:1978/")->put("test", "hi");
?>

See Also

  • TokyoTyrant::connect - Connect to a database

TokyoTyrant::connect
TokyoTyrant::__construct
TokyoTyrant


Copies the database

TokyoTyrant::__construct
TokyoTyrant::ext
TokyoTyrant
PHP Manual

TokyoTyrant::copy

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::copy — Copies the database

Description

public TokyoTyrant TokyoTyrant::copy ( string $path )

Makes a copy of the current database

Parameters

path

Path to where to copy the database. The user running the remote database must have a write access to the directory.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::copy example

<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->copy("/tmp/foobar.tct");
?>

See Also

  • TokyoTyrant::restore - Restore the database

TokyoTyrant::__construct
TokyoTyrant::ext
TokyoTyrant


Execute a remote script

TokyoTyrant::copy
TokyoTyrant::fwmKeys
TokyoTyrant
PHP Manual

TokyoTyrant::ext

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::ext — Execute a remote script

Description

public string TokyoTyrant::ext ( string $name , int $options , string $key , string $value )

Executes a remote script extension.

Parameters

name

Name of the function to execute

options

Either TokyoTyrant::RDBXO_LCKREC for record locking and TokyoTyrant::RDBXO_LCKGLB for global locking.

key

The key to pass to the function

value

The value to pass to the function

Return Values

Returns the result of the script function

Examples

Example #1 TokyoTyrant::ext example

<?php
$tt = new TokyoTyrant("localhost", 1978);
echo $tt->ext("somefunc", TokyoTyrant::RDBXO_LCKREC, "some_key", "some_value");
?>

TokyoTyrant::copy
TokyoTyrant::fwmKeys
TokyoTyrant


Returns the forward matching keys

TokyoTyrant::ext
TokyoTyrant::get
TokyoTyrant
PHP Manual

TokyoTyrant::fwmKeys

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::fwmKeys — Returns the forward matching keys

Description

public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )

Returns the forward matching keys from the database

Parameters

prefix

Prefix of the keys

max_recs

Maximum records to return

Return Values

Returns an array of matching keys. The values are not returned

Examples

Example #1 TokyoTyrant::fwmKeys example

<?php

$tt = new TokyoTyrant("localhost");

/* Create 20 macthing keys */
for ($i = 0; $i < 20; $i++) {
    $tt->put("key_" . $i, "value_" . $i);
}

/* Create 20 non-macthing keys */
for ($i = 0; $i < 20; $i++) {
    $tt->put("something_" . $i, "data_" . $i);
}

/* Get five matching keys */
var_dump($tt->fwmKeys("key_", 5));
?>

The above example will output something similar to:

array(5) {
  [0]=>
  string(5) "key_5"
  [1]=>
  string(6) "key_14"
  [2]=>
  string(5) "key_6"
  [3]=>
  string(6) "key_15"
  [4]=>
  string(5) "key_7"
}

TokyoTyrant::ext
TokyoTyrant::get
TokyoTyrant


The get purpose

TokyoTyrant::fwmKeys
TokyoTyrant::getIterator
TokyoTyrant
PHP Manual

TokyoTyrant::get

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::get — The get purpose

Description

public mixed TokyoTyrant::get ( mixed $keys )

This method is used to return a value or multiple values. This method accepts a string or an array as a value.

Parameters

keys

A string key or an array of string keys

Return Values

Returns a string or an array based on the given parameters. Throws a TokyoTyrantException on error. If string is passed null is returned if the key is not found. In case an array is given as an parameter only existing keys will be returned. It is not an error to pass a key that does not exist.

Examples

Example #1 TokyoTyrant::get example

<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->put("key1", "value1");
$tt->put("key2", "value2");
var_dump($tt->get(array("key1", "key2")));
var_dump($tt->get("key1"));
?>

The above example will output:

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key2"]=>
  string(6) "value2"
}
string(6) "value1"

See Also

  • TokyoTyrant::put - Puts values

TokyoTyrant::fwmKeys
TokyoTyrant::getIterator
TokyoTyrant


Get an iterator

TokyoTyrant::get
TokyoTyrant::num
TokyoTyrant
PHP Manual

TokyoTyrant::getIterator

(No version information available, might only be in SVN)

TokyoTyrant::getIterator — Get an iterator

Description

public TokyoTyrantIterator TokyoTyrant::getIterator ( void )

Gets an iterator for iterating all keys / values in the database.

Parameters

This function has no parameters.

Return Values

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::getIterator example

<?php
$tt = new TokyoTyrant("localhost");
$it = $tt->getIterator();

foreach ($it as $k => $v) {

}
?>

See Also

  • TokyoTyrantTable::getQuery - Get a query object
  • TokyoTyrantTable::getIterator - Get an iterator

TokyoTyrant::get
TokyoTyrant::num
TokyoTyrant


Number of records in the database

TokyoTyrant::getIterator
TokyoTyrant::out
TokyoTyrant
PHP Manual

TokyoTyrant::num

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::num — Number of records in the database

Description

public int TokyoTyrant::num ( void )

Returns the number of records in the database

Parameters

This function has no parameters.

Return Values

Returns number of records in the database

Examples

Example #1 TokyoTyrant::num example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Echo the number of records */
echo $tt->num();
?>

The above example will output something similar to:

1234

See Also

  • TokyoTyrant::stat - Get statistics

TokyoTyrant::getIterator
TokyoTyrant::out
TokyoTyrant


Removes records

TokyoTyrant::num
TokyoTyrant::put
TokyoTyrant
PHP Manual

TokyoTyrant::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::out — Removes records

Description

public TokyoTyrant TokyoTyrant::out ( mixed $keys )

Removes a record or multiple records. This method accepts a string for a single key or an array of keys for multiple records.

Parameters

keys

A string key or an array of string keys

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::out example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

$tt->put("test1", "value1");
$tt->put("test2", "value2");

$tt->out(array("test1", "test2"));
?>

See Also

  • TokyoTyrant::put - Puts values

TokyoTyrant::num
TokyoTyrant::put
TokyoTyrant


Puts values

TokyoTyrant::out
TokyoTyrant::putCat
TokyoTyrant
PHP Manual

TokyoTyrant::put

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::put — Puts values

Description

public TokyoTyrant TokyoTyrant::put ( mixed $keys [, string $value ] )

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. If the key exists the value will be replaced with new value.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::put example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Put single key-value pair */
$tt->put("key", "value");

/* Put key-value pairs, new value overwrites the old */
$tt->put(array("key1" => "value1", "key" => "value2"));

/* Get back one key */
echo $tt->get("key");
?>

The above example will output:

value2

See Also

  • TokyoTyrant::putKeep - Puts a record
  • TokyoTyrant::putCat - Concatenates to a record

TokyoTyrant::out
TokyoTyrant::putCat
TokyoTyrant


Concatenates to a record

TokyoTyrant::put
TokyoTyrant::putKeep
TokyoTyrant
PHP Manual

TokyoTyrant::putCat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putCat — Concatenates to a record

Description

public TokyoTyrant TokyoTyrant::putCat ( mixed $keys [, string $value ] )

Appends a value into existing key or multiple values if keys is an array. The second parameter is mandatory if keys is a string. If the record does not exist a new record is created.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putCat example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "value");

/* Concatenate single key-value pair */
$tt->putCat("key", " has more data");

/* Echo the key */
echo $tt->get("key");
?>

The above example will output:

value has more data

See Also

  • TokyoTyrant::put - Puts values
  • TokyoTyrant::putKeep - Puts a record

TokyoTyrant::put
TokyoTyrant::putKeep
TokyoTyrant


Puts a record

TokyoTyrant::putCat
TokyoTyrant::putNr
TokyoTyrant
PHP Manual

TokyoTyrant::putKeep

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putKeep — Puts a record

Description

public TokyoTyrant TokyoTyrant::putKeep ( mixed $keys [, string $value ] )

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. If the key already exists this method throws an exception indicating that the records exists.

Parameters

keys

A string key or an array of key-value pairs

value

The string value

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 tokyotyrant::putKeep example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "value");

try {
    $tt->putKeep("key", "new value");
} catch (TokyoTyrantException $e) {
    if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
        echo "Existing record! Not modified\n";
    } else {
        echo "Error: " , $e->getMessage() , "\n";
    }
}
echo $tt->get("key");
?>

The above example will output:

Existing record! Not modified
value

See Also

  • TokyoTyrant::put - Puts values
  • TokyoTyrant::putCat - Concatenates to a record

TokyoTyrant::putCat
TokyoTyrant::putNr
TokyoTyrant


Puts value

TokyoTyrant::putKeep
TokyoTyrant::putShl
TokyoTyrant
PHP Manual

TokyoTyrant::putNr

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putNr — Puts value

Description

public TokyoTyrant TokyoTyrant::putNr ( mixed $keys [, string $value ] )

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. This method does not wait for the response from the server.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putNr example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Put single key-value pair */
$tt->putNr("key", "value");

/* Put key-value pairs */
$tt->putNr(array("key1" => "value1", "key2" => "value2"));

/* Get back one key */
echo $tt->get("key1");
?>

The above example will output:

value1

See Also

  • TokyoTyrant::putNr
  • TokyoTyrant::putKeep - Puts a record
  • TokyoTyrant::putCat - Concatenates to a record

TokyoTyrant::putKeep
TokyoTyrant::putShl
TokyoTyrant


Concatenates to a record

TokyoTyrant::putNr
TokyoTyrant::restore
TokyoTyrant
PHP Manual

TokyoTyrant::putShl

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putShl — Concatenates to a record

Description

public mixed TokyoTyrant::putShl ( string $key , string $value , int $width )

Concatenate to a record and shift to left.

Parameters

key

A string key

value

The value to concatenate

width

The width of the record

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putShl example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "just a long piece of data");

/* Concatenate and shift to left */
$tt->putShl("key", " and string", 15);

/* Echo the key */
echo $tt->get("key");
?>

The above example will output:

data and string

See Also

  • TokyoTyrant::put - Puts values
  • TokyoTyrant::putKeep - Puts a record
  • TokyoTyrant::putCat - Concatenates to a record

TokyoTyrant::putNr
TokyoTyrant::restore
TokyoTyrant


Restore the database

TokyoTyrant::putShl
TokyoTyrant::setMaster
TokyoTyrant
PHP Manual

TokyoTyrant::restore

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::restore — Restore the database

Description

public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )

Restore the database from the update log.

Warning

This method is not supported on 32bit platforms.

Parameters

log_dir

Directory where the log is

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency: Default: TRUE

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

TokyoTyrant::putShl
TokyoTyrant::setMaster
TokyoTyrant


Set the replication master

TokyoTyrant::restore
TokyoTyrant::size
TokyoTyrant
PHP Manual

TokyoTyrant::setMaster

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::setMaster — Set the replication master

Description

public mixed TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )

Sets the replication master of the database

Warning

This method is not supported on 32bit platforms.

Parameters

host

Hostname of the replication master. If NULL the replication is disabled.

port

Port of the replication master

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::setMaster example

<?php
/* Connect to a database */
$tt = new TokyoTyrant("tokyotyrant.example.com");

/* Disable the replication */
$tt->setMaster(NULL, 0, 0);
?>

See Also

  • Classname::Method

TokyoTyrant::restore
TokyoTyrant::size
TokyoTyrant


Returns the size of the value

TokyoTyrant::setMaster
TokyoTyrant::stat
TokyoTyrant
PHP Manual

TokyoTyrant::size

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::size — Returns the size of the value

Description

public int TokyoTyrant::size ( string $key )

Returns the size of a value by key

Parameters

key

The key of which size to fetch

Return Values

Returns the size of the key or throw TokyoTyrantException on error

Examples

Example #1 TokyoTyrant::size example

<?php
$tt = new TokyoTyrant("localhost");

$tt->put("test_key", "12345");

echo $tt->size("test_key");
?>

The above example will output:

5

TokyoTyrant::setMaster
TokyoTyrant::stat
TokyoTyrant


Get statistics

TokyoTyrant::size
TokyoTyrant::sync
TokyoTyrant
PHP Manual

TokyoTyrant::stat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::stat — Get statistics

Description

public array TokyoTyrant::stat ( void )

Returns statistics of the remote database

Parameters

This function has no parameters.

Return Values

Returns an array of key value pairs describing the statistics

Examples

Example #1 TokyoTyrant::stat example

<?php
$tt = new TokyoTyrant("localhost");

var_dump($tt->stat());
?>

The above example will output something similar to:

array(19) {
  ["version"]=>
  string(6) "1.1.28"
  ["libver"]=>
  string(3) "311"
  ["protver"]=>
  string(4) "0.91"
  ["os"]=>
  string(5) "Linux"
  ["time"]=>
  string(17) "1247358357.665630"
  ["pid"]=>
  string(5) "14348"
  ["sid"]=>
  string(8) "59025947"
  ["type"]=>
  string(9) "on-memory"
  ["path"]=>
  string(1) "*"
  ["rnum"]=>
  string(1) "4"
  ["size"]=>
  string(6) "262856"
  ["bigend"]=>
  string(1) "0"
  ["fd"]=>
  string(1) "5"
  ["loadavg"]=>
  string(8) "0.000000"
  ["memsize"]=>
  string(8) "77328384"
  ["memrss"]=>
  string(7) "1183744"
  ["ru_real"]=>
  string(13) "162776.042152"
  ["ru_user"]=>
  string(8) "0.476029"
  ["ru_sys"]=>
  string(8) "8.652540"
}

See Also

  • Classname::Method

TokyoTyrant::size
TokyoTyrant::sync
TokyoTyrant


Synchronize the database

TokyoTyrant::stat
TokyoTyrant::tune
TokyoTyrant
PHP Manual

TokyoTyrant::sync

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::sync — Synchronize the database

Description

public mixed TokyoTyrant::sync ( void )

Synchronizes the database on to the physical device

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

TokyoTyrant::stat
TokyoTyrant::tune
TokyoTyrant


Tunes connection values

TokyoTyrant::sync
TokyoTyrant::vanish
TokyoTyrant
PHP Manual

TokyoTyrant::tune

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrant::tune — Tunes connection values

Description

public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )

Tunes database connection options.

Parameters

timeout

The objects timeout value (default: 5.0)

options

Bitmask of options to tune. This can be either 0 or TokyoTyrant::RDBT_RECON. It is recommended not to change the second parameter.

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

TokyoTyrant::sync
TokyoTyrant::vanish
TokyoTyrant


Empties the database

TokyoTyrant::tune
TokyoTyrantTable
TokyoTyrant
PHP Manual

TokyoTyrant::vanish

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::vanish — Empties the database

Description

public mixed TokyoTyrant::vanish ( void )

Empties a remote database

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::vanish example

<?php
$tt = new TokyoTyrant("localhost");
$tt->vanish();
?>

See Also

  • TokyoTyrant::out - Removes records

TokyoTyrant::tune
TokyoTyrantTable
TokyoTyrant


Construct a new query

TokyoTyrantQuery::addCond
TokyoTyrantQuery::count
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::__construct

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::__construct — Construct a new query

Description

TokyoTyrantQuery::__construct ( TokyoTyrantTable $table )

Construct a new query object

Parameters

table

TokyoTyrantTable object with active database connection

Return Values

Returns a new TokyoTyrantQuery object and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::__construct example

<?php
$tt = new TokyoTyrantTable("localhost", 1979);

$query = new TokyoTyrantQuery($tt);

/* Work with $query */
?>

See Also

  • TokyoTyrantTable::getQuery - Get a query object

TokyoTyrantQuery::addCond
TokyoTyrantQuery::count
TokyoTyrantQuery


Adds a condition to the query

TokyoTyrantQuery
TokyoTyrantQuery::__construct
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::addCond

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::addCond — Adds a condition to the query

Description

public mixed TokyoTyrantQuery::addCond ( string $name , int $op , string $expr )

Adds a condition to the query. Condition can be something like: get all keys which value matches expr.

Parameters

name

Name of the column in the condition

op

The operator. One of the TokyoTyrant::RDBQC_* constants

expr

The expression

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantQuery::addCond example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Dump the search results */
var_dump($query->search());
?>

The above example will output:

array(2) {
  [1]=>
  array(2) {
    ["column1"]=>
    string(9) "some data"
    ["column2"]=>
    string(14) "something here"
  }
  [4]=>
  array(2) {
    ["column45"]=>
    string(11) "random data"
    ["column2"]=>
    string(25) "something along the lines"
  }
}

See Also

  • Classname::Method

TokyoTyrantQuery
TokyoTyrantQuery::__construct
TokyoTyrantQuery


Counts records

TokyoTyrantQuery::__construct
TokyoTyrantQuery::current
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::count

(No version information available, might only be in SVN)

TokyoTyrantQuery::count — Counts records

Description

public int TokyoTyrantQuery::count ( void )

Returns a count of how many records a query returns.

Parameters

This function has no parameters.

Return Values

Returns a count of matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::count example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Count the results */
var_dump($query->count());
?>

The above example will output:

int(2)

See Also

  • TokyoTyrantQuery::out - Removes records based on query
  • TokyoTyrantQuery::search - Searches records
  • TokyoTyrantQuery::metaSearch - Retrieve records with multiple queries

TokyoTyrantQuery::__construct
TokyoTyrantQuery::current
TokyoTyrantQuery


Returns the current element

TokyoTyrantQuery::count
TokyoTyrantQuery::hint
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::current

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::current — Returns the current element

Description

public array TokyoTyrantQuery::current ( void )

Returns the current element. Part of Iterator interface

Parameters

This function has no parameters.

Return Values

Returns the current row

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond - Adds a condition to the query

TokyoTyrantQuery::count
TokyoTyrantQuery::hint
TokyoTyrantQuery


Get the hint string of the query

TokyoTyrantQuery::current
TokyoTyrantQuery::key
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::hint

(No version information available, might only be in SVN)

TokyoTyrantQuery::hint — Get the hint string of the query

Description

public string TokyoTyrantQuery::hint ( void )

Get the hint string of the query. The hint string contains information about an executed query and it could be compared to for example MySQL EXPLAIN statement.

Parameters

This function has no parameters.

Return Values

This method always returns a string

Examples

Example #1 TokyoTyrantQuery::hint example

<?php
$tt = new TokyoTyrantTable("localhost", 1979);
$tt->vanish();

for ($i = 0; $i < 11; $i++) {
     $tt->put(null, array('a_col' => 'a' . $i, 'b_col' => 'b' . $i));
}

$query = $tt->getQuery();
$query->addCond('a_col', TokyoTyrant::RDBQC_STRBW, 'a');

$query->search();
var_dump($query->hint());

The above example will output something similar to:

string(72) "
scanning the whole table
result set size: 11
leaving the natural order
"

See Also

  • TokyoTyrantQuery::addCond - Adds a condition to the query

TokyoTyrantQuery::current
TokyoTyrantQuery::key
TokyoTyrantQuery


Returns the current key

TokyoTyrantQuery::hint
TokyoTyrantQuery::metaSearch
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::key

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::key — Returns the current key

Description

public string TokyoTyrantQuery::key ( void )

Returns the current key. Part of the Iterator interface

Parameters

This function has no parameters.

Return Values

Returns the current key and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond - Adds a condition to the query

TokyoTyrantQuery::hint
TokyoTyrantQuery::metaSearch
TokyoTyrantQuery


Retrieve records with multiple queries

TokyoTyrantQuery::key
TokyoTyrantQuery::next
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::metaSearch

(No version information available, might only be in SVN)

TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries

Description

public array TokyoTyrantQuery::metaSearch ( array $queries , int $type )

Executes multiple queries on a database and returns matching records. The current object is always the left most object in the search.

Parameters

queries

Array of TokyoTyrantQuery objects

type

One of the TokyoTyrant::RDBMS_* constants

Return Values

Returns the matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::metaSearch example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add test data */
$tt->put('cherry',     array('color' => 'red'));
$tt->put('strawberry', array('color' => 'red'));
$tt->put('apple',      array('color' => 'green'));
$tt->put('lemon',      array('color' => 'yellow'));

/* First query */
$query = $tt->getQuery();
$query->addCond('color', TokyoTyrant::RDBQC_STREQ, 'red')->setOrder('color', TokyoTyrant::RDBQO_STRASC);

/* Second query */
$query1 = $tt->getQuery();
$query1->addCond('color', TokyoTyrant::RDBQC_STREQ, 'yellow');

/* Get union between the queries */
var_dump($query->metaSearch(array($query1), TokyoTyrant::RDBMS_UNION));
?>

The above example will output:

array(3) {
  ["cherry"]=>
  array(1) {
    ["color"]=>
    string(3) "red"
  }
  ["strawberry"]=>
  array(1) {
    ["color"]=>
    string(3) "red"
  }
  ["lemon"]=>
  array(1) {
    ["color"]=>
    string(6) "yellow"
  }
}

See Also

  • TokyoTyrantQuery::search - Searches records

TokyoTyrantQuery::key
TokyoTyrantQuery::next
TokyoTyrantQuery


Moves the iterator to next entry

TokyoTyrantQuery::metaSearch
TokyoTyrantQuery::out
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::next

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::next — Moves the iterator to next entry

Description

public array TokyoTyrantQuery::next ( void )

Returns the next result in the resultset. Part of the Iterator interface.

Parameters

This function has no parameters.

Return Values

Returns the next row and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond - Adds a condition to the query

TokyoTyrantQuery::metaSearch
TokyoTyrantQuery::out
TokyoTyrantQuery


Removes records based on query

TokyoTyrantQuery::next
TokyoTyrantQuery::rewind
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::out — Removes records based on query

Description

public TokyoTyrantQuery TokyoTyrantQuery::out ( void )

Removes all records that match the query. Works exactly like search but removes the records instead of returning them.

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantQuery::out example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Remove matching records */
$query->out();
?>

See Also

  • TokyoTyrantQuery::addCond - Adds a condition to the query

TokyoTyrantQuery::next
TokyoTyrantQuery::rewind
TokyoTyrantQuery


Rewinds the iterator

TokyoTyrantQuery::out
TokyoTyrantQuery::search
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::rewind

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::rewind — Rewinds the iterator

Description

public bool TokyoTyrantQuery::rewind ( void )

Rewind the resultset and executes the query if it has not been executed. Part of the Iterator interface.

Parameters

This function has no parameters.

Return Values

Returns TRUE

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond - Adds a condition to the query

TokyoTyrantQuery::out
TokyoTyrantQuery::search
TokyoTyrantQuery


Searches records

TokyoTyrantQuery::rewind
TokyoTyrantQuery::setLimit
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::search

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::search — Searches records

Description

public array TokyoTyrantQuery::search ( void )

Executes a search on the table database. Returns an array of arrays containing the matching records. In the returned array the first level is the primary key of the data and the second level is the row data.

Parameters

This function has no parameters.

Return Values

Returns the matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::search example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Dump the search results */
var_dump($query->search());
?>

The above example will output:

array(2) {
  [1]=>
  array(2) {
    ["column1"]=>
    string(9) "some data"
    ["column2"]=>
    string(14) "something here"
  }
  [4]=>
  array(2) {
    ["column45"]=>
    string(11) "random data"
    ["column2"]=>
    string(25) "something along the lines"
  }
}

See Also

  • TokyoTyrantQuery::out - Removes records based on query
  • TokyoTyrantQuery::metaSearch - Retrieve records with multiple queries

TokyoTyrantQuery::rewind
TokyoTyrantQuery::setLimit
TokyoTyrantQuery


Limit results

TokyoTyrantQuery::search
TokyoTyrantQuery::valid
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::setLimit

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::setLimit — Limit results

Description

public mixed TokyoTyrantQuery::setLimit ([ int $max [, int $skip ]] )

Set the maximum amount of records to return on a query.

Parameters

max

Maximum amount of records. Default: -1

skip

How many records to skip from the start. Default: -1

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

TokyoTyrantQuery::search
TokyoTyrantQuery::valid
TokyoTyrantQuery


Checks the validity of current item

TokyoTyrantQuery::setLimit
File System Related Extensions
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::valid

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::valid — Checks the validity of current item

Description

public bool TokyoTyrantQuery::valid ( void )

Checks if the current item is valid. Part of the Iterator interface

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current item is valid and FALSE if not.

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond - Adds a condition to the query

TokyoTyrantQuery::setLimit
File System Related Extensions
TokyoTyrantQuery


Adds a record

TokyoTyrantTable
TokyoTyrantTable::genUid
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::add

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::add — Adds a record

Description

public void TokyoTyrantTable::add ( string $key , mixed $increment [, string $type ] )

This method is not supported with table databases.

Parameters

key

The string key

increment

The amount to increment

type

TokyoTyrant::RDB_RECINT or TokyoTyrant::RDB_RECDBL constant. If this parameter is omitted the type is guessed from the increment parameters type.

Return Values

This method throws an TokyoTyrantException if used through this class.

See Also

  • TokyoTyrant::add - Adds to a numeric key

TokyoTyrantTable
TokyoTyrantTable::genUid
TokyoTyrantTable


Generate unique id

TokyoTyrantTable::add
TokyoTyrantTable::get
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::genUid

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::genUid — Generate unique id

Description

public int TokyoTyrantTable::genUid ( void )

Generates an unique id inside the table database. In table databases rows are referenced using a numeric primary key.

Parameters

This function has no parameters.

Return Values

Returns an unique id or throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::genUid example

<?php
$tt = new TokyoTyrantTable("localhost", 1122);

echo $tt->genUid();
?>

The above example will output something similar to:

4

See Also

  • TokyoTyrantTable::put - Store a row

TokyoTyrantTable::add
TokyoTyrantTable::get
TokyoTyrantTable


Get a row

TokyoTyrantTable::genUid
TokyoTyrantTable::getIterator
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::get

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::get — Get a row

Description

public void TokyoTyrantTable::get ( string $keys )

Gets a row from table database. keys is a single integer for the primary key of the row or an array of integers for multiple rows.

Parameters

keys

The primary key, can be a string or an integer

Return Values

Returns the row as an array

Examples

Example #1 TokyoTyrantTable::get example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

See Also

  • TokyoTyrantTable::put - Store a row

TokyoTyrantTable::genUid
TokyoTyrantTable::getIterator
TokyoTyrantTable


Get an iterator

TokyoTyrantTable::get
TokyoTyrantTable::getQuery
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::getIterator

(No version information available, might only be in SVN)

TokyoTyrantTable::getIterator — Get an iterator

Description

public TokyoTyrantIterator TokyoTyrantTable::getIterator ( void )

Gets an iterator for iterating all keys / values in the database.

Parameters

This function has no parameters.

Return Values

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantTable::getIterator example

<?php
$tt = new TokyoTyrantTable("localhost");
$it = $tt->getIterator();

foreach ($it as $k => $v) {
  var_dump($k, $v);
}
?>

See Also

  • TokyoTyrantTable::getQuery - Get a query object
  • TokyoTyrant::getIterator - Get an iterator

TokyoTyrantTable::get
TokyoTyrantTable::getQuery
TokyoTyrantTable


Get a query object

TokyoTyrantTable::getIterator
TokyoTyrantTable::out
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::getQuery

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::getQuery — Get a query object

Description

public TokyoTyrantQuery TokyoTyrantTable::getQuery ( void )

Get a query object to execute searches on the database

Parameters

This function has no parameters.

Return Values

Returns TokyoTyrantQuery on success and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::getQuery example

<?php
/* Connect to a table database */
$table = new TokyoTyrantTable("localhost", 1979);

/* Put a few rows */
$table->put(null, array("column1" => "some data", "column2" => "more data"));
$table->put(null, array("something" => "value", "data" => "good data"));

/* Get query object */
$query = $table->getQuery();

/* Add condition to query */
$query->addCond('data', TokyoTyrant::RDBQC_STREQ, 'good data');

/* Get matching rows */
var_dump($query->search());
?>

The above example will output something similar to:

array(1) {
  [11]=>
  array(2) {
    ["something"]=>
    string(5) "value"
    ["data"]=>
    string(9) "good data"
  }
}

See Also

  • TokyoTyrantQuery::search - Searches records
  • TokyoTyrantQuery::out - Removes records based on query

TokyoTyrantTable::getIterator
TokyoTyrantTable::out
TokyoTyrantTable


Remove records

TokyoTyrantTable::getQuery
TokyoTyrantTable::put
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::out — Remove records

Description

public void TokyoTyrantTable::out ( mixed $keys )

Removes records from a table database.

Parameters

keys

A single integer key or an array of integers

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantTable::out example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Delete the row */
$tt->out($index);
?>

See Also

  • TokyoTyrantTable::put - Store a row

TokyoTyrantTable::getQuery
TokyoTyrantTable::put
TokyoTyrantTable


Store a row

TokyoTyrantTable::out
TokyoTyrantTable::putCat
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::put

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::put — Store a row

Description

public int TokyoTyrantTable::put ( string $key , array $columns )

Puts a new row into the database. This method parameters are key which is the primary key of the row, passing NULL will generate a new unique id. value is an array containing the row contents which is usually key value pairs.

Parameters

key

The primary key of the row

columns

The row contents

Return Values

Returns the primary key on success and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::put example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

/* Modify an existing row */
$tt->put($index, array("column1" => "other data", "column2" => "better data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
array(2) {
  ["column1"]=>
  string(10) "other data"
  ["column2"]=>
  string(11) "better data"
}

See Also

  • TokyoTyrantTable::get - Get a row

TokyoTyrantTable::out
TokyoTyrantTable::putCat
TokyoTyrantTable


Concatenates to a row

TokyoTyrantTable::put
TokyoTyrantTable::putKeep
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::putCat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putCat — Concatenates to a row

Description

public void TokyoTyrantTable::putCat ( string $key , array $columns )

This method can be used to add new columns to existing records. Existing keys will be left unmodified but any new columns will be appended to the row. Passing null as key will generate a new row.

Parameters

key

The primary key of the row or NULL

columns

Array of row contents

Return Values

Returns the primary key and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantTable::putCat example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

/* Modify an existing row */
$tt->putcat($index, array("column1" => "something new", "new_column" => "other data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
array(3) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
  ["new_column"]=>
  string(10) "other data"
}

See Also

  • TokyoTyrantTable::put - Store a row

TokyoTyrantTable::put
TokyoTyrantTable::putKeep
TokyoTyrantTable


Put a new record

TokyoTyrantTable::putCat
TokyoTyrantTable::putNr
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::putKeep

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putKeep — Put a new record

Description

public void TokyoTyrantTable::putKeep ( string $key , array $columns )

Puts a new record into the database. If the key already exists this method throws an exception indicating that the records exists.

Parameters

key

The primary key of the row or NULL

columns

Array of the row contents

Return Values

Returns the primary key and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantTable::putKeep example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

try {
    $tt->putKeep($index, array("column1" => "something new", "new_column" => "other data"));
} catch (TokyoTyrantException $e) {
    if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
        echo "Existing record! Not modified\n";
    } else {
        echo "Error: " , $e->getMessage() , "\n";
    }
}

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output something similar to:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
Existing record! Not modified
array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

See Also

  • TokyoTyrantTable::put - Store a row

TokyoTyrantTable::putCat
TokyoTyrantTable::putNr
TokyoTyrantTable


Puts value

TokyoTyrantTable::putKeep
TokyoTyrantTable::putShl
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::putNr

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putNr — Puts value

Description

public void TokyoTyrantTable::putNr ( mixed $keys [, string $value ] )

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

See Also

  • TokyoTyrant::putNr - Puts value
  • TokyoTyrant::putKeep - Puts a record
  • TokyoTyrant::putCat - Concatenates to a record

TokyoTyrantTable::putKeep
TokyoTyrantTable::putShl
TokyoTyrantTable


Concatenates to a record

TokyoTyrantTable::putNr
TokyoTyrantTable::setIndex
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::putShl

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putShl — Concatenates to a record

Description

public void TokyoTyrantTable::putShl ( string $key , string $value , int $width )

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Parameters

key

A string key

value

The value to concatenate

width

The width of the record

Return Values

This method is not supported on table databases.

See Also

  • TokyoTyrant::put - Puts values
  • TokyoTyrant::putKeep - Puts a record
  • TokyoTyrant::putCat - Concatenates to a record
  • TokyoTyrantTable::put - Store a row
  • TokyoTyrantTable::putKeep - Put a new record
  • TokyoTyrantTable::putCat - Concatenates to a row

TokyoTyrantTable::putNr
TokyoTyrantTable::setIndex
TokyoTyrantTable


Sets index

TokyoTyrantTable::putShl
TokyoTyrantQuery
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::setIndex

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::setIndex — Sets index

Description

public mixed TokyoTyrantTable::setIndex ( string $column , int $type )

Sets an index on a specified column. The index type is one of the TokyoTyrant::RDBIT_* constants. Passing TokyoTyrant::RDBIT_VOID removes the index.

Parameters

column

The name of the column

type

The index type

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

TokyoTyrantTable::putShl
TokyoTyrantQuery
TokyoTyrantTable


A simple tutorial

Table of Contents

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

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

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

What can PHP do?
What do I need?
Getting Started


Your first PHP-enabled page

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

Example #1 Our first PHP script: hello.php

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

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

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

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

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

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

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

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

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

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

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

Example #2 Get system information from PHP

<?php phpinfo(); ?>

What do I need?
Something Useful
A simple tutorial


Dealing with Forms

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

Example #1 A simple HTML form

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

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

Example #2 Printing data from our form

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

A sample output of this script may be:

Hi Joe. You are 22 years old.

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

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

Something Useful
Using old code with new versions of PHP
A simple tutorial


Using old code with new versions of PHP

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

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

  • The deprecation of the old $HTTP_*_VARS arrays (which need to be indicated as global when used inside a function or method). The following superglobal arrays were introduced in PHP » 4.1.0. They are: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, and $_SESSION. The older $HTTP_*_VARS arrays, such as $HTTP_POST_VARS, also exist. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.
  • External variables are no longer registered in the global scope by default. In other words, as of PHP » 4.2.0 the PHP directive register_globals is off by default in php.ini. The preferred method of accessing these values is via the superglobal arrays mentioned above. Older scripts, books, and tutorials may rely on this directive being on. If it were on, for example, one could use $id from the URL http://www.example.com/foo.php?id=42. Whether on or off, $_GET['id'] is available.

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

Dealing with Forms
What's next?
A simple tutorial


What do I need?

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

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

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

A simple tutorial
Your first PHP-enabled page
A simple tutorial


Something Useful

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

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

To display this variable, you can simply do:

Example #1 Printing a variable (Array element)

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

A sample output of this script may be:

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

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

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

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

Example #2 Example using control structures and functions

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

A sample output of this script may be:

You are using Internet Explorer.<br />

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

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

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

Example #3 Mixing both HTML and PHP modes

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

A sample output of this script may be:

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

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

Your first PHP-enabled page
Dealing with Forms
A simple tutorial


What's next?

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

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

Using old code with new versions of PHP
Installation and Configuration
A simple tutorial


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Unicode Configuration Options
Name | Default | Changeable | Changelog
unicode.fallback_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.from_error_mode | "2" | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.from_error_subst_char | "3f" | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.http_input_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.output_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.runtime_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.
unicode.script_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

unicode.output_encoding string

Default encoding for output.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

constant | value | description
U_INVALID_STOP | 0 | stop at first invalid character
U_INVALID_SKIP | 1 | skip invalid characters
U_INVALID_SUBSTITUTE | 2 | replace invalid characters
U_INVALID_ESCAPE | 3 | escape invalid characters

Resource Types
Unicode Functions
Unicode


Installation

First you should download and install ICU:

Example #1 Install ICU on Unix

./configure --enable-weak-threads
make && make install

Then checkout latest PHP and configure it --with-icu-dir=<dir> option, where <dir> was the dir to where you installed ICU. You don't need to explicitly use this option if you install ICU to a standard location.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

» ICU 3.4 or later is required.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Unicode


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

ODBC_TYPE (integer)
ODBC_BINMODE_PASSTHRU (integer)
ODBC_BINMODE_RETURN (integer)
ODBC_BINMODE_CONVERT (integer)
SQL_ODBC_CURSORS (integer)
SQL_CUR_USE_DRIVER (integer)
SQL_CUR_USE_IF_NEEDED (integer)
SQL_CUR_USE_ODBC (integer)
SQL_CONCURRENCY (integer)
SQL_CONCUR_READ_ONLY (integer)
SQL_CONCUR_LOCK (integer)
SQL_CONCUR_ROWVER (integer)
SQL_CONCUR_VALUES (integer)
SQL_CURSOR_TYPE (integer)
SQL_CURSOR_FORWARD_ONLY (integer)
SQL_CURSOR_KEYSET_DRIVEN (integer)
SQL_CURSOR_DYNAMIC (integer)
SQL_CURSOR_STATIC (integer)
SQL_KEYSET_SIZE (integer)
SQL_CHAR (integer)
SQL_VARCHAR (integer)
SQL_LONGVARCHAR (integer)
SQL_DECIMAL (integer)
SQL_NUMERIC (integer)
SQL_BIT (integer)
SQL_TINYINT (integer)
SQL_SMALLINT (integer)
SQL_INTEGER (integer)
SQL_BIGINT (integer)
SQL_REAL (integer)
SQL_FLOAT (integer)
SQL_DOUBLE (integer)
SQL_BINARY (integer)
SQL_VARBINARY (integer)
SQL_LONGVARBINARY (integer)
SQL_DATE (integer)
SQL_TIME (integer)
SQL_TIMESTAMP (integer)
SQL_TYPE_DATE (integer)
SQL_TYPE_TIME (integer)
SQL_TYPE_TIMESTAMP (integer)
SQL_BEST_ROWID (integer)
SQL_ROWVER (integer)
SQL_SCOPE_CURROW (integer)
SQL_SCOPE_TRANSACTION (integer)
SQL_SCOPE_SESSION (integer)
SQL_NO_NULLS (integer)
SQL_NULLABLE (integer)
SQL_INDEX_UNIQUE (integer)
SQL_INDEX_ALL (integer)
SQL_ENSURE (integer)
SQL_QUICK (integer)
Resource Types
ODBC Functions
ODBC


Requirements

To access any of the supported databases you need to have the required libraries installed.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension defines two resource types: an ODBC connection identifier and an ODBC result identifier.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
ODBC


Predefined Constants

This extension has no constants defined.

Resource Types
vpopmail Functions
vpopmail


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/vpopmail.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
vpopmail


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

The following table lists and explains the configuration settings provided by the WinCache extension:

WinCache configuration options
Name | Default | Minimum | Maximum | Changeable | Changelog
wincache.fcenabled | "1" | "0" | "1" | PHP_INI_ALL | Available since WinCache 1.0.0
wincache.fcenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.fcachesize | "24" | "5" | "85" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.maxfilesize | "256" | "10" | "2048" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.ocenabled | "1" | "0" | "1" | PHP_INI_ALL | Available since WinCache 1.0.0
wincache.ocenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.ocachesize | "96" | "15" | "255" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.filecount | "4096" | "1024" | "16384" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.chkinterval | "30" | "0" | "300" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.ttlmax | "1200" | "0" | "7200" | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.enablecli | 0 | 0 | 1 | PHP_INI_SYSTEM | Available since WinCache 1.0.0
wincache.ignorelist | NULL | NULL | NULL | PHP_INI_ALL | Available since WinCache 1.0.0
wincache.namesalt | NULL | NULL | NULL | PHP_INI_SYSTEM | Available since WinCache 1.0.0

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

wincache.fcenabled boolean
Enables or disables the file cache functionality.
wincache.fcenabledfilter string
Defines a comma-separated list of IIS web site identifiers where file cache should be enabled or disabled. This setting works in conjunction with wincache.fcenabled: if wincache.fcenabled is set to 1, then the sites listed in the wincache.fcenabledfilter will have the file cache turned off; if wincache.fcenabled is set to 0, then the sites listed in the wincache.fcenabledfilter will have the file cache turned on.
wincache.fcachesize integer
Defines the maximum memory size (in megabytes) that is allocated for the file cache. If the total size of all the cached files exceeds the value specified in this setting, then most stale files will be removed from the file cache.
wincache.maxfilesize integer
Defines the maximum allowed size (in kilobytes) for a single file to be cached. If a file size exceeds the specified value, the file will not be cached. This setting applies to the file cache only.
wincache.ocenabled boolean
Enables or disables the opcode cache functionality
wincache.ocenabledfilter string
Defines a comma-separated list of IIS web site identifiers where opcode cache should be enabled or disabled. This setting works in conjunction with wincache.ocenabled: if wincache.ocenabled is set to 1, then the sites listed in the wincache.ocenabledfilter will have the opcode cache turned off; if wincache.ocenabled is set to 0, then the sites listed in the wincache.ocenabledfilter will have the opcode cache turned on.
wincache.ocachesize integer
Defines the maximum memory size (in megabytes) that is allocated for the opcode cache. If the cached opcode size exceeds the specified value, then most stale opcode will be removed from the cache. Note that the opcode cache size must be at least 3 times bigger than file cache size. If that is not the case the opcode cache size will be automatically increased.
wincache.filecount integer
Defines how many files are expected to be cached by the extension, so that appropriate memory size is allocated at the startup time. If the number of files exceeds the specified value, the WinCache will re-allocate more memory as needed.
wincache.chkinterval integer
Defines how often (in seconds) the extension checks for file changes in order to refresh the cache. Setting it to 0 will disable the refreshing of the cache. The file changes will not be reflected in the cache unless the cache entry for that file is removed by scavenger or IIS application pool is recycled or wincache_refresh_if_changed function is called.
wincache.ttlmax integer
Defines the maximum time to live (in seconds) for a cached entry without being used. Setting it to 0 will disable the cache scavenger, so the cached entries will never be removed from the cache during the lifetime of the IIS worker process.
wincache.enablecli boolean
Defines if caching is enabled when PHP is running in command line (CLI) mode.
wincache.ignorelist string

Defines a list of files that should not be cached by the extension. The files list is specified by using file names only, separated by the pipe symbol - "|".

Example #1 wincache.ignorelist example

wincache.ignorelist = "index.php|misc.php|admin.php"

wincache.namesalt boolean
Defines a string that will be used when naming the extension specific objects that are stored in shared memory. This is used to avoid conflicts that may be caused if other applications within an IIS worker process tries to access shared memory.

Installation
WinCache Statistics Script
Installing/Configuring


Predefined Constants

This extension has no constants defined.

Resource Types
WinCache Functions
WinCache


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/wincache.

There are two packages for this extension: one package is for PHP versions 5.2.X, and the other package is for PHP 5.3.X. Select the package that is appropriate for the PHP version being used.

To install and enable the extension, follow these steps:

  1. Unpack the package into some temporary location.

  2. Copy the php_wincache.dll file into the PHP extensions folder. Typically this folder is called "ext" and it is located in the same folder with all PHP binary files. For example: C:\Program Files\PHP\ext.

  3. Using a text editor, open the php.ini file, which is usually located in the same folder where all PHP binary files are. For example: C:\Program Files\PHP\php.ini.

  4. Add the following line at the end of the php.ini file: extension = php_wincache.dll.

  5. Save and close the php.ini file.

  6. Recycle the IIS Application Pools for PHP to pick up the configuration changes. To check that the extension has been enabled, create a file called phpinfo.php with a PHP code that calls phpinfo function.

  7. Save the phpinfo.php file in the root folder of a IIS web site that uses PHP, then open a browser and make a request to http://localhost/phpinfo.php. Search within the returned web page for a section called wincache. If the extension is enabled, then the phpinfo output will list the configuration settings provided by the WinCache.

Note: Do not forget to remove phpinfo.php file from the web site's root folder after verifying that extension has been enabled.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

The extension is currently supported only on the following configurations:

Windows OS:

  • Windows XP SP3 with IIS 5.1 and » FastCGI Extension
  • Windows Server 2003 with IIS 6.0 and » FastCGI Extension
  • Windows Vista SP1 with IIS 7.0 and FastCGI Module
  • Windows Server 2008 with IIS 7.0 and FastCGI Module
  • Windows 7 with IIS 7.5 and FastCGI Module
  • Windows Server 2008 R2 with IIS 7.5 and FastCGI Module

PHP:

  • PHP 5.2.X, Non-thread-safe build
  • PHP 5.3 X86, Non-thread-safe VC9 build

Note: The WinCache Extension can only be used when IIS is configured to run PHP via FastCGI.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension has no resource types defined.

WinCache Statistics Script
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • WinCache Statistics Script
  • Resource Types
Introduction
Requirements
WinCache


WinCache Statistics Script

The installation package for WinCache includes a PHP script, wincache.php, that can be used to obtain cache information and statistics.

If the WinCache extension was installed via the Microsoft Web Platform Installer, then this script is located in %SystemDrive%\Program Files\IIS\Windows Cache for PHP\. On a 64-bit version of the Windows Server operating system, the script is located in %SystemDrive%\Program Files (x86)\IIS\Windows Cache for PHP. If the extension was installed manually, then the wincache.php will be located in the same folder from which the content of the installation package was extracted.

To use wincache.php, copy it into a root folder of a Web site or into any subfolder. To protect the script, open it in any text editor and replace the values for USERNAME and PASSWORD constants. If any other IIS authentication is enabled on the server, then follow the instructions in the comments:

Example #1 Authentication configuration for wincache.php

/**
 * ======================== CONFIGURATION SETTINGS ==============================
 * If you do not want to use authentication for this page, set USE_AUTHENTICATION to 0.
 * If you use authentication then replace the default password.
 */
define('USE_AUTHENTICATION', 1);
define('USERNAME', 'wincache');
define('PASSWORD', 'wincache');

/**
 * The Basic PHP authentication will work only when IIS is configured to support
 * Anonymous Authentication' and nothing else. If IIS is configured to support/use
 * any other kind of authentication like Basic/Negotiate/Digest etc, this will not work.
 * In that case use the array below to define the names of users in your
 * domain/network/workgroup which you want to grant access to.
 */
$user_allowed = array('DOMAIN\user1', 'DOMAIN\user2', 'DOMAIN\user3');

/**
 * If the array contains string 'all', then all the users authenticated by IIS
 * will have access to the page. Uncomment the below line and comment above line
 * to grant access to all users who gets authenticated by IIS.
 */
/* $user_allowed = array('all'); */

/** ===================== END OF CONFIGURATION SETTINGS ========================== */

Note: Always protect the wincache.php script by using either the built-in authentication or the server's authentication mechanism. Leaving this script unprotected may compromise the security of your web application and web server.

Runtime Configuration
Resource Types
Installing/Configuring


Building for Windows

Table of Contents

  • Prerequisites
  • Compiling and building
  • Verifying the build
wincache_rplist_meminfo
Prerequisites
WinCache


Compiling and building

The following steps describe how to compile and build WinCache on Windows OS:

  1. Open a command prompt which is used to build PHP

  2. Go to the root folder where PHP sources are present

  3. Run the command:

    cscript.exe win32\build\buildconf.js

  4. Run the command:

    configure.bat --help

    The output will contain a new flag --enable-wincache.

  5. Run the command:

    configure.js [all options used to build PHP] --enable-wincache

    --enable-wincache is the only extra option which is required to ensure that WinCache extension gets built properly. This option will build WinCache and will statically link it with PHP dll. To build WinCache extension as a stand-alone DLL use the option --enable-wincache=shared.

  6. Run the command:

    nmake

Prerequisites
Verifying the build
Building for Windows


Prerequisites

Building WinCache extension will require:

  1. PHP source code
  2. PHP build environment
  3. WinCache source code

For completing first two steps, follow the step-by-step guide for how to » build PHP on Windows.

For getting the WinCache source code follow the instructions described in Downloading PECL extensions.

Building for Windows
Compiling and building
Building for Windows


Verifying the build

The following steps describe how to verify that WinCache has been built correctly:

  1. Go to the folder where the PHP binaries are built

  2. Run the command:

    php.exe -n -d extension=php_wincache.dll -re wincache

    If WinCache has been built properly, the output of this command will list the INI directives and functions supported by WinCache.

Compiling and building
Audio Formats Manipulation
Building for Windows


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

XATTR_ROOT (integer)
Set attribute in root (trusted) namespace. Requires root privileges.
XATTR_DONTFOLLOW (integer)
Do not follow the symbolic link but operate on symbolic link itself.
XATTR_CREATE (integer)
Function will fail if extended attribute already exists.
XATTR_REPLACE (integer)
Function will fail if extended attribute doesn't exist.
Resource Types
xattr Functions
xattr


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/xattr.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To use xattr, you will need libattr installed. It is available at » http://oss.sgi.com/projects/xfs/.

Note: These functions only work on filesystems that support extended attributes, and have them enabled at mount time. Some common filesystems that support extended attributes are ext2, ext3, reiserfs, jfs, and xfs.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
xattr


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

XDIFF_PATCH_NORMAL (integer)
This flag indicates that xdiff_string_patch() and xdiff_file_patch() functions should create result by applying patch to original content thus creating newer version of file. This is the default mode of operation.
XDIFF_PATCH_REVERSE (integer)
This flag indicated that xdiff_string_patch() and xdiff_file_patch() functions should create result by reversing patch changed from newer content thus creating original version.
Resource Types
xdiff Functions
xdiff


Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/xdiff.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

To use xdiff, you will need libxdiff installed, available on the libxdiff homepage » http://www.xmailserver.org/xdiff-lib.html.

Note: You'll need at least libxdiff 0.7 for these functions to be aware of memory_limit.

Installing/Configuring
Installation
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
xdiff


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

ZipArchive uses class constants. There are three types of constants : Flags (prefixed with FL_), errors (prefixed with ER_) and mode (no prefix).

ZIPARCHIVE::CREATE (integer)
Create the archive if it does not exist.
ZIPARCHIVE::OVERWRITE (integer)
Always start a new archive, this mode will overwrite the file if it already exists.
ZIPARCHIVE::EXCL (integer)
Error if archive already exists.
ZIPARCHIVE::CHECKCONS (integer)
Perform additional consistency checks on the archive, and error if they fail.
ZIPARCHIVE::FL_NOCASE (integer)
Ignore case on name lookup
ZIPARCHIVE::FL_NODIR (integer)
Ignore directory component
ZIPARCHIVE::FL_COMPRESSED (integer)
Read compressed data
ZIPARCHIVE::FL_UNCHANGED (integer)
Use original data, ignoring changes.
ZIPARCHIVE::CM_DEFAULT (integer)
better of deflate or store.
ZIPARCHIVE::CM_STORE (integer)
stored (uncompressed).
ZIPARCHIVE::CM_SHRINK (integer)
shrunk
ZIPARCHIVE::CM_REDUCE_1 (integer)
reduced with factor 1
ZIPARCHIVE::CM_REDUCE_2 (integer)
reduced with factor 2
ZIPARCHIVE::CM_REDUCE_3 (integer)
reduced with factor 3
ZIPARCHIVE::CM_REDUCE_4 (integer)
reduced with factor 4
ZIPARCHIVE::CM_IMPLODE (integer)
imploded
ZIPARCHIVE::CM_DEFLATE (integer)
deflated
ZIPARCHIVE::CM_DEFLATE64 (integer)
deflate64
ZIPARCHIVE::CM_PKWARE_IMPLODE (integer)
PKWARE imploding
ZIPARCHIVE::CM_BZIP2 (integer)
BZIP2 algorithm
ZIPARCHIVE::ER_OK (integer)
No error.
ZIPARCHIVE::ER_MULTIDISK (integer)
Multi-disk zip archives not supported.
ZIPARCHIVE::ER_RENAME (integer)
Renaming temporary file failed.
ZIPARCHIVE::ER_CLOSE (integer)
Closing zip archive failed
ZIPARCHIVE::ER_SEEK (integer)
Seek error
ZIPARCHIVE::ER_READ (integer)
Read error
ZIPARCHIVE::ER_WRITE (integer)
Write error
ZIPARCHIVE::ER_CRC (integer)
CRC error
ZIPARCHIVE::ER_ZIPCLOSED (integer)
Containing zip archive was closed
ZIPARCHIVE::ER_NOENT (integer)
No such file.
ZIPARCHIVE::ER_EXISTS (integer)
File already exists
ZIPARCHIVE::ER_OPEN (integer)
Can't open file
ZIPARCHIVE::ER_TMPOPEN (integer)
Failure to create temporary file.
ZIPARCHIVE::ER_ZLIB (integer)
Zlib error
ZIPARCHIVE::ER_MEMORY (integer)
Memory allocation failure
ZIPARCHIVE::ER_CHANGED (string)
Entry has been changed
ZIPARCHIVE::ER_COMPNOTSUPP (integer)
Compression method not supported.
ZIPARCHIVE::ER_EOF (integer)
Premature EOF
ZIPARCHIVE::ER_INVAL (integer)
Invalid argument
ZIPARCHIVE::ER_NOZIP (integer)
Not a zip archive
ZIPARCHIVE::ER_INTERNAL (integer)
Internal error
ZIPARCHIVE::ER_INCONS (integer)
Zip archive inconsistent
ZIPARCHIVE::ER_REMOVE (integer)
Can't remove file
ZIPARCHIVE::ER_DELETED (integer)
Entry has been deleted
Resource Types
Examples
Zip


Examples

Example #1 Create a Zip archive

<?php

$zip = new ZipArchive();
$filename = "./test112.zip";

if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
    exit("cannot open <$filename>\n");
}

$zip->addFromString("testfilephp.txt" . time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip->addFromString("testfilephp2.txt" . time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip->addFile($thisdir . "/too.php","/testfromfile.php");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
?>

Example #2 Dump the archive details and listing

<?php
$za = new ZipArchive();

$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
echo "numFiles: " . $za->numFiles . "\n";
echo "status: " . $za->status  . "\n";
echo "statusSys: " . $za->statusSys . "\n";
echo "filename: " . $za->filename . "\n";
echo "comment: " . $za->comment . "\n";

for ($i=0; $i<$za->numFiles;$i++) {
    echo "index: $i\n";
    print_r($za->statIndex($i));
}
echo "numFile:" . $za->numFiles . "\n";
?>

Example #3 Zip stream wrapper, read an OpenOffice meta info

<?php
$reader = new XMLReader();

$reader->open('zip://' . dirname(__FILE__) . '/test.odt#meta.xml');
$odt_meta = array();
while ($reader->read()) {
    if ($reader->nodeType == XMLREADER::ELEMENT) {
        $elm = $reader->name;
    } else {
        if ($reader->nodeType == XMLREADER::END_ELEMENT && $reader->name == 'office:meta') {
            break;
        }
        if (!trim($reader->value)) {
            continue;
        }
        $odt_meta[$elm] = $reader->value;
    }
}
print_r($odt_meta);
?>

This example uses the old API (PHP 4), it opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.

Example #4 Zip Usage Example

<?php

$zip = zip_open("/tmp/test2.zip");

if ($zip) {
    while ($zip_entry = zip_read($zip)) {
        echo "Name:               " . zip_entry_name($zip_entry) . "\n";
        echo "Actual Filesize:    " . zip_entry_filesize($zip_entry) . "\n";
        echo "Compressed Size:    " . zip_entry_compressedsize($zip_entry) . "\n";
        echo "Compression Method: " . zip_entry_compressionmethod($zip_entry) . "\n";

        if (zip_entry_open($zip, $zip_entry, "r")) {
            echo "File Contents:\n";
            $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
            echo "$buf\n";

            zip_entry_close($zip_entry);
        }
        echo "\n";

    }

    zip_close($zip);

}
?>
Predefined Constants
ZipArchive
Zip


Installation

PHP 4

Note: Zip support before PHP 4.1.0 is experimental.

Warning

Because the PHP 4 zip extension is unmaintained we recommend that the PECL extension is used rather than the bundled one.

Linux systems

In order to use these functions you must compile PHP with zip support by using the --with-zip[=DIR] configure option, where [DIR] is the prefix of the » ZZIPlib library install.

Windows

Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

PHP 5.2.0 and later

Linux systems

In order to use these functions you must compile PHP with zip support by using the --enable-zip configure option.

Windows

Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

Installation via PECL

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/zip.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

PHP 4

The bundled PHP 4 version requires » ZZIPlib, by Guido Draheim, version 0.10.6 or later

PHP 5.2.0 or later

This extension uses the functions of » zlib by Jean-loup Gailly and Mark Adler.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

There are two resource types used in the Zip module. The first one is the Zip directory for the Zip archive, the second Zip Entry for the archive entries.

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Zip


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

The zlib extension offers the option to transparently compress your pages on-the-fly, if the requesting browser supports this. Therefore there are three options in the configuration file php.ini.

Zlib Configuration Options
Name | Default | Changeable | Changelog
zlib.output_compression | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
zlib.output_compression_level | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
zlib.output_handler | "" | PHP_INI_ALL | Available since PHP 4.3.0.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

zlib.output_compression boolean/integer

Whether to transparently compress pages. If this option is set to "On" in php.ini or the Apache configuration, pages are compressed if the browser sends an "Accept-Encoding: gzip" or "deflate" header. "Content-Encoding: gzip" (respectively "deflate") and "Vary: Accept-Encoding" headers are added to the output. In runtime, it can be set only before sending any output.

This option also accepts integer values instead of boolean "On"/"Off", using this you can set the output buffer size (default is 4KB).

Note: output_handler must be empty if this is set 'On' ! Instead you must use zlib.output_handler.

zlib.output_compression_level integer

Compression level used for transparent output compression. Specify a value between 0 (no compression) to 9 (most compression). The default value, -1, lets the server decide which level to use.

zlib.output_handler string

You cannot specify additional output handlers if zlib.output_compression is activated here. This setting does the same as output_handler but in a different order.

Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FORCE_GZIP (integer)
FORCE_DEFLATE (integer)
Resource Types
Examples
Zlib


Examples

This example opens a temporary file and writes a test string to it, then it prints out the content of this file twice.

Example #1 Small Zlib Example

<?php

$filename = tempnam('/tmp', 'zlibtest') . '.gz';
echo "<html>\n<head></head>\n<body>\n<pre>\n";
$s = "Only a test, test, test, test, test, test, test, test!\n";

// open file for writing with maximum compression
$zp = gzopen($filename, "w9");

// write string to file
gzwrite($zp, $s);

// close file
gzclose($zp);

// open file for reading
$zp = gzopen($filename, "r");

// read 3 char
echo gzread($zp, 3);

// output until end of the file and close it.
gzpassthru($zp);
gzclose($zp);

echo "\n";

// open file and print content (the 2nd time).
if (readgzfile($filename) != strlen($s)) {
        echo "Error with zlib functions!";
}
unlink($filename);
echo "</pre>\n</body>\n</html>\n";

?>
Predefined Constants
Zlib Functions
Zlib


Installation

Zlib support in PHP is not enabled by default. You will need to configure PHP --with-zlib[=DIR]

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

Note: Built-in support for zlib on Windows is available with PHP 4.3.0.

Requirements
Runtime Configuration
Installing/Configuring


Requirements

This module uses the functions of » zlib by Jean-loup Gailly and Mark Adler. You have to use a zlib version >= 1.0.9 with this module.

Installing/Configuring
Installation
Installing/Configuring


Resource Types

This extension defines a file pointer resource returned by gzopen().

Runtime Configuration
Predefined Constants
Installing/Configuring


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
Introduction
Requirements
Zlib